diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..3833f4606 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,24 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +[*.md] +trim_trailing_whitespace = false + +[*.{rb,rake,gemspec,rbs,ru}] +indent_style = space +indent_size = 2 + +[*.{yml,yaml,json}] +indent_style = space +indent_size = 2 + +[*.sh] +indent_style = space +indent_size = 2 + +[Makefile] +indent_style = tab diff --git a/.github/workflows/_publish-code.yml b/.github/workflows/_publish-code.yml index 4002d731a..31a65647f 100644 --- a/.github/workflows/_publish-code.yml +++ b/.github/workflows/_publish-code.yml @@ -5,18 +5,17 @@ on: workflow_dispatch: jobs: - linting: + publish: name: Publish to Rubygems runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: recursive - - name: Set up Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: "3.0" + ruby-version: "3.2" bundler-cache: true - name: Set credentials @@ -28,10 +27,13 @@ jobs: echo -e "---\n:rubygems_api_key: ${RUBYGEMS_API_KEY}" > ~/.gem/credentials chmod 600 ~/.gem/credentials - - name: Build the Gem + - name: Build the Gems run: | - gem build --strict --output mindee.gem + gem build mindee.gemspec --strict --output mindee.gem + gem build mindee-lite.gemspec --strict --output mindee-lite.gem - - name: Publish the Gem + - name: Publish the Gems run: | + # Push both generated files to Rubygems gem push mindee.gem + gem push mindee-lite.gem diff --git a/.github/workflows/_publish-docs.yml b/.github/workflows/_publish-docs.yml index 247a56170..989494d9d 100644 --- a/.github/workflows/_publish-docs.yml +++ b/.github/workflows/_publish-docs.yml @@ -12,12 +12,12 @@ jobs: name: Publish Documentation runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: set up Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: "3.1" + ruby-version: "3.2" bundler-cache: true - name: Analyse the code with Rubocop diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index d200c288f..d35199286 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -12,16 +12,32 @@ jobs: name: Run Static Analysis runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: recursive - name: set up Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: "3.0.0" + ruby-version: "3.2.0" bundler-cache: true + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.x" + + - name: Install pre-commit + run: | + python -m pip install --upgrade pip + python -m pip install pre-commit + + - name: Run pre-commit checks (security + hygiene) + env: + SKIP: rubocop,steep + run: | + pre-commit run --all-files --show-diff-on-failure + - name: Analyse the code with Rubocop run: | bundle install diff --git a/.github/workflows/_test-cli.yml b/.github/workflows/_test-cli.yml new file mode 100644 index 000000000..d8c2581b5 --- /dev/null +++ b/.github/workflows/_test-cli.yml @@ -0,0 +1,47 @@ +name: CLI Test + +on: + workflow_call: + workflow_dispatch: + +env: + MINDEE_API_KEY: ${{ secrets.MINDEE_API_KEY_SE_TESTS }} + MINDEE_V2_API_KEY: ${{ secrets.MINDEE_V2_SE_TESTS_API_KEY }} + MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID }} + +jobs: + test: + name: Run Tests + timeout-minutes: 30 + strategy: + max-parallel: 4 + matrix: + os_config: + - os: "ubuntu-24.04" + rid: "linux-x64" + - os: "macos-latest" + rid: "osx-x64" + - os: "windows-latest" + rid: "win-x64" + ruby: + - "3.2" + - "4.0" + runs-on: ${{ matrix.os_config.os }} + steps: + - uses: actions/checkout@v5 + with: + submodules: recursive + + - name: set up Ruby ${{ matrix.ruby }} + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + + - name: Tests V2 CLI + run: | + ./spec/test_v2_cli.sh ./spec/data/file_types/pdf/blank_1.pdf ${{ matrix.os_config.rid }} + + - name: Tests V1 CLI + run: | + ./spec/test_v1_cli.sh ./spec/data/file_types/pdf/blank_1.pdf ${{ matrix.os_config.rid }} diff --git a/.github/workflows/_test-integration-lite.yml b/.github/workflows/_test-integration-lite.yml new file mode 100644 index 000000000..f283269a2 --- /dev/null +++ b/.github/workflows/_test-integration-lite.yml @@ -0,0 +1,50 @@ +# +# Run integration tests. +# +name: Integration Tests - Minimal Dependencies + +on: + workflow_call: + workflow_dispatch: + +env: + MINDEE_API_KEY: ${{ secrets.MINDEE_API_KEY_SE_TESTS }} + WORKFLOW_ID: ${{ secrets.WORKFLOW_ID_SE_TESTS }} + MINDEE_V2_API_KEY: ${{ secrets.MINDEE_V2_SE_TESTS_API_KEY }} + MINDEE_V2_FINDOC_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID }} + MINDEE_V2_SE_TESTS_BLANK_PDF_URL: ${{ secrets.MINDEE_V2_SE_TESTS_BLANK_PDF_URL }} + MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID }} + MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID }} + MINDEE_V2_SE_TESTS_CROP_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_CROP_MODEL_ID }} + MINDEE_V2_SE_TESTS_OCR_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_OCR_MODEL_ID }} + MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID }} + MINDEE_LOG_LEVEL: DEBUG + MINDEE_GEM_NAME: mindee-lite + +jobs: + integration-tests: + name: Run Integration Tests + timeout-minutes: 30 + runs-on: ${{ matrix.os }} + strategy: + max-parallel: 3 + matrix: + os: + - "ubuntu-24.04" + - "macos-latest" + ruby: + - "4.0" + steps: + - uses: actions/checkout@v5 + with: + submodules: recursive + + - name: set up Ruby ${{ matrix.ruby }} + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + + - name: Run Rspec for integration tests + run: | + bundle exec rake integration diff --git a/.github/workflows/_test-integrations.yml b/.github/workflows/_test-integration.yml similarity index 61% rename from .github/workflows/_test-integrations.yml rename to .github/workflows/_test-integration.yml index 75a72a712..32e06f697 100644 --- a/.github/workflows/_test-integrations.yml +++ b/.github/workflows/_test-integration.yml @@ -1,12 +1,25 @@ # # Run integration tests. # -name: Integration Tests +name: Integration Tests - All Dependencies on: workflow_call: workflow_dispatch: +env: + MINDEE_API_KEY: ${{ secrets.MINDEE_API_KEY_SE_TESTS }} + WORKFLOW_ID: ${{ secrets.WORKFLOW_ID_SE_TESTS }} + MINDEE_V2_API_KEY: ${{ secrets.MINDEE_V2_SE_TESTS_API_KEY }} + MINDEE_V2_FINDOC_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID }} + MINDEE_V2_SE_TESTS_BLANK_PDF_URL: ${{ secrets.MINDEE_V2_SE_TESTS_BLANK_PDF_URL }} + MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID }} + MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID }} + MINDEE_V2_SE_TESTS_CROP_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_CROP_MODEL_ID }} + MINDEE_V2_SE_TESTS_OCR_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_OCR_MODEL_ID }} + MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID }} + MINDEE_LOG_LEVEL: DEBUG + jobs: integration-tests: name: Run Integration Tests @@ -19,10 +32,10 @@ jobs: - "ubuntu-24.04" - "macos-latest" ruby: - - "3.0" + - "3.2" - "4.0" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: recursive @@ -32,11 +45,11 @@ jobs: ruby-version: ${{ matrix.ruby }} bundler-cache: true - - name: Install Ghostscript on Ubuntu + - name: Install Ghostscript and ImageMagick on Ubuntu if: runner.os == 'Linux' run: | sudo apt update - sudo apt-get install -y ghostscript + sudo apt-get install -y ghostscript imagemagick - name: Install Ghostscript and ImageMagick on macOS if: runner.os == 'macOS' @@ -50,17 +63,6 @@ jobs: sudo sed -i "s/$SRC/$RPL/" /etc/ImageMagick-6/policy.xml - name: Run Rspec for integration tests - env: - MINDEE_API_KEY: ${{ secrets.MINDEE_API_KEY_SE_TESTS }} - WORKFLOW_ID: ${{ secrets.WORKFLOW_ID_SE_TESTS }} - MINDEE_V2_API_KEY: ${{ secrets.MINDEE_V2_SE_TESTS_API_KEY }} - MINDEE_V2_FINDOC_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID }} - MINDEE_V2_SE_TESTS_BLANK_PDF_URL: ${{ secrets.MINDEE_V2_SE_TESTS_BLANK_PDF_URL }} - MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID }} - MINDEE_V2_SE_TESTS_CROP_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_CROP_MODEL_ID }} - MINDEE_V2_SE_TESTS_OCR_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_OCR_MODEL_ID }} - MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID }} - MINDEE_LOG_LEVEL: DEBUG run: | bundle exec rake integration diff --git a/.github/workflows/_test-code-samples.yml b/.github/workflows/_test-smoke.yml similarity index 53% rename from .github/workflows/_test-code-samples.yml rename to .github/workflows/_test-smoke.yml index 81e76f0b3..7a3579d46 100644 --- a/.github/workflows/_test-code-samples.yml +++ b/.github/workflows/_test-smoke.yml @@ -1,4 +1,4 @@ -name: Test Code Samples +name: Smoke Test on: workflow_call: @@ -9,12 +9,13 @@ env: MINDEE_ACCOUNT_SE_TESTS: ${{ secrets.MINDEE_ACCOUNT_SE_TESTS }} MINDEE_API_KEY_SE_TESTS: ${{ secrets.MINDEE_API_KEY_SE_TESTS }} MINDEE_V2_API_KEY: ${{ secrets.MINDEE_V2_SE_TESTS_API_KEY }} - MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID }} - MINDEE_V2_SE_TESTS_FAILURE_WEBHOOK_ID: ${{ secrets.MINDEE_V2_SE_TESTS_FAILURE_WEBHOOK_ID }} - MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID }} - MINDEE_V2_SE_TESTS_CROP_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_CROP_MODEL_ID }} - MINDEE_V2_SE_TESTS_OCR_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_OCR_MODEL_ID }} - MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID }} + MINDEE_V2_FINDOC_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID }} + MINDEE_V2_SE_TESTS_BLANK_PDF_URL: ${{ secrets.MINDEE_V2_SE_TESTS_BLANK_PDF_URL }} + MINDEE_V2_CLASSIFICATION_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID }} + MINDEE_V2_CROP_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_CROP_MODEL_ID }} + MINDEE_V2_FAILURE_WEBHOOK_ID: ${{ secrets.MINDEE_V2_SE_TESTS_FAILURE_WEBHOOK_ID }} + MINDEE_V2_OCR_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_OCR_MODEL_ID }} + MINDEE_V2_SPLIT_MODEL_ID: ${{ secrets.MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID }} jobs: test: @@ -23,14 +24,13 @@ jobs: strategy: matrix: ruby: - - "3.0" - - "3.1" - "3.2" - "3.3" - "3.4" + - "4.0" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: recursive @@ -40,14 +40,14 @@ jobs: ruby-version: ${{ matrix.ruby }} bundler-cache: true - - name: Tests V1 code samples + - name: Tests V2 code samples env: MINDEE_LOG_LEVEL: DEBUG run: | - ./spec/test_code_samples_v1.sh + ./spec/test_v2_code_samples.sh - - name: Tests V2 code samples + - name: Tests V1 code samples env: MINDEE_LOG_LEVEL: DEBUG run: | - ./spec/test_code_samples_v2.sh + ./spec/test_v1_code_samples.sh ${{ secrets.MINDEE_ACCOUNT_SE_TESTS }} ${{ secrets.MINDEE_ENDPOINT_SE_TESTS }} diff --git a/.github/workflows/_test-units-lite.yml b/.github/workflows/_test-units-lite.yml new file mode 100644 index 000000000..80277c9c0 --- /dev/null +++ b/.github/workflows/_test-units-lite.yml @@ -0,0 +1,40 @@ +# +# Run lite unit tests. +# +name: Unit Tests - Minimal Dependencies + +on: + workflow_call: + +env: + MINDEE_GEM_NAME: mindee-lite + +jobs: + tests: + name: Run Unit Tests + timeout-minutes: 30 + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: + - "ubuntu-24.04" + - "macos-latest" + ruby: + - "3.2" + - "4.0" + steps: + - uses: actions/checkout@v5 + with: + submodules: recursive + + - name: set up Ruby ${{ matrix.ruby }} + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + + - name: Run Rspec + env: + MINDEE_LOG_LEVEL: DEBUG + run: | + bundle exec rake spec diff --git a/.github/workflows/_test-units.yml b/.github/workflows/_test-units.yml index 1b3859e74..5769e6e13 100644 --- a/.github/workflows/_test-units.yml +++ b/.github/workflows/_test-units.yml @@ -1,7 +1,7 @@ # -# Run unit tests. +# Run full unit tests. # -name: Tests +name: Unit Tests - All Dependencies on: workflow_call: @@ -15,17 +15,14 @@ jobs: matrix: os: - "ubuntu-24.04" - - "ubuntu-22.04" - "macos-latest" ruby: - - "3.0" - - "3.1" - "3.2" - "3.3" - "3.4" - "4.0" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: recursive diff --git a/.github/workflows/cron.yml b/.github/workflows/cron.yml index e7f14660b..ee6755c89 100644 --- a/.github/workflows/cron.yml +++ b/.github/workflows/cron.yml @@ -5,6 +5,9 @@ on: - cron: '0 0 * * *' jobs: - test_code_samples: - uses: mindee/mindee-api-ruby/.github/workflows/_test-code-samples.yml@main + test-smoke: + uses: mindee/mindee-api-ruby/.github/workflows/_test-smoke.yml@main + secrets: inherit + test-cli: + uses: mindee/mindee-api-ruby/.github/workflows/_test-cli.yml@main secrets: inherit diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index a1178aeb3..d786c0e56 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -5,13 +5,13 @@ on: types: [ published ] jobs: - publish_docs: + publish-docs: uses: mindee/mindee-api-ruby/.github/workflows/_publish-docs.yml@main secrets: inherit - publish_guide: + publish-guide: uses: mindee/mindee-api-ruby/.github/workflows/_publish-guide.yml@main - needs: publish_docs + needs: publish-docs secrets: inherit - publish_code: + publish-code: uses: mindee/mindee-api-ruby/.github/workflows/_publish-code.yml@main secrets: inherit diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 6527968fb..5f5edf043 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -8,17 +8,29 @@ permissions: pull-requests: read jobs: - static_analysis: + static-analysis: uses: ./.github/workflows/_static-analysis.yml - test_units: + test-unit: uses: ./.github/workflows/_test-units.yml - needs: static_analysis + needs: static-analysis secrets: inherit - test_integrations: - uses: ./.github/workflows/_test-integrations.yml - needs: test_units + test-unit-lite: + uses: ./.github/workflows/_test-units.yml + needs: static-analysis + secrets: inherit + test-integration: + uses: ./.github/workflows/_test-integration.yml + needs: test-unit + secrets: inherit + test-integration-lite: + uses: ./.github/workflows/_test-integration-lite.yml + needs: test-unit-lite + secrets: inherit + test-smoke: + uses: ./.github/workflows/_test-smoke.yml + needs: test-unit secrets: inherit - test_code_samples: - uses: ./.github/workflows/_test-code-samples.yml - needs: test_units + test-cli: + uses: ./.github/workflows/_test-cli.yml + needs: test-unit secrets: inherit diff --git a/.github/workflows/push-main-branch.yml b/.github/workflows/push-main-branch.yml index 55ccabd55..812b14568 100644 --- a/.github/workflows/push-main-branch.yml +++ b/.github/workflows/push-main-branch.yml @@ -6,15 +6,15 @@ on: - main jobs: - static_analysis: + static-analysis: uses: mindee/mindee-api-ruby/.github/workflows/_static-analysis.yml@main - test_units: + test-units: uses: mindee/mindee-api-ruby/.github/workflows/_test-units.yml@main - needs: static_analysis + needs: static-analysis secrets: inherit tag: uses: mindee/client-lib-actions/.github/workflows/tag-version.yml@main - needs: test_units + needs: test-units release: uses: mindee/client-lib-actions/.github/workflows/create-release.yml@main needs: tag diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000..e013967a1 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,36 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + - id: check-merge-conflict + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - id: check-added-large-files + args: ["--maxkb=1024"] + + - repo: https://github.com/gitleaks/gitleaks + rev: v8.30.0 + hooks: + - id: gitleaks + exclude: ^(spec/data/|docs/code_samples/|local_test/) + + - repo: local + hooks: + - id: rubocop + name: RuboCop + entry: bundle exec rubocop --force-exclusion --no-server + language: system + pass_filenames: false + - id: steep + name: Steep + entry: bundle exec steep check + language: system + pass_filenames: false + stages: [pre-commit, pre-push] + - id: bundle-audit + name: Bundle Audit + entry: bundle exec bundle-audit check + language: system + pass_filenames: false + stages: [pre-commit, pre-push] diff --git a/.rubocop.yml b/.rubocop.yml index fbb91a84e..cee4fe23d 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -10,7 +10,7 @@ AllCops: - local_test/* - Steepfile - TargetRubyVersion: 3.0.0 + TargetRubyVersion: 3.2 SuggestExtensions: false Gemspec/DevelopmentDependencies: @@ -37,7 +37,8 @@ Metrics/MethodLength: Metrics/ClassLength: Max: 200 - +Metrics/ModuleLength: + Max: 200 Metrics/ParameterLists: Max: 8 diff --git a/CHANGELOG.md b/CHANGELOG.md index fc2cc9737..9e1e39735 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,46 @@ # Mindee Ruby API Library Changelog +## v5.0.0.alpha1 - 2026-04-03 +### ¡Breaking Changes! +* :boom: :recycle: update V1 & V2 syntaxes to match other SDKs + * :recycle: move V1 client to V1 module + * :recycle: move V2 client to V2 module + * :recycle: move legacy products to 'V1' module + * :recycle: add parsing and extraction to v1 namodule + * :recycle: move V1 HTTP to V1 module + * :recycle: move V2 HTTP module to V2 namespace + * :recycle: move data schema to extraction parameters namespace +* :arrow_up: :boom: drop support for ruby < 3.2 +* :recycle: :boom: change raw_http attribute in responses to be actual json strings +* :recycle: :boom: make logging configurable and default output to stderr +* :recycle: :boom: remove useless `PDFExtractor` module +* :recycle: :boom: change `Errors` module to `Error` +* :recycle: :boom: change Ocr modules and classes to OCR to keep consistency +* :boom: remove support for the following V1 products: + * :coffin: US Bank Check V1 + * :coffin: Bill of Lading V1 + * :coffin: Business Card V1 + * :coffin: FR Carte Grise V1 + * :coffin: Delivery Notes V1 + * :coffin: Driver License V1 + * :coffin: FR Energy Bill V1 + * :coffin: Nutrition Facts V1 + +### Changes +* :sparkles: :arrow_up: add support for mindee-lite gem +* :sparkles: add support for crop operation +* :sparkles: add support for split operation +* :sparkles: add support for model search +* :sparkles: add support for V2 CLI +* :wrench: :arrow_up: add better tooling and pre-commit hook +* :arrow_up: and bump all dependencies + +### Fixes +* :bug: fix webhook IDs not sending properly +* :bug: fix miscellaneous issues leading to saved `ExtractedPDF` instances having invalid names +* :recycle: fix miscellaneous typing issues relating to `ExtractedPDF` and `ExtractedImage` classes + + ## v4.13.0 - 2026-03-03 ### Changes * :sparkles: add support for V2 Classification product @@ -9,8 +50,8 @@ * :recycle: make polling follow API urls instead of re-constructing them * :sparkles: add support for generic product accessors in V2 * :recycle: add proper tests for ruby 4 -### Fixes -* :recycle: fix tests file paths +### Fixes +* :recycle: fix tests file paths ## v4.12.0 - 2026-02-25 @@ -58,7 +99,7 @@ ## v4.7.0 - 2025-09-18 -Including RC changes and fixes. +Including RC changes and fixes. ### Changes * :sparkles: add support for V2 Mindee API * :sparkles: add missing accessors for PDF fixing options in `LocalInputSource` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f52fa7744..776fa9dd0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -88,3 +88,20 @@ Examples: We keep our code base consistent and expect Ruby code to adhere to our Rubocop styleguide, see the `.rubocop` file. + +### Local Quality Checks + +We use [`pre-commit`](https://pre-commit.com/) hooks to run quality and security checks before +changes are pushed: + +1. Install `pre-commit`, either using `pip` or `brew`: + - `pip install pre-commit` + - `brew install pre-commit` +2. Install project hooks: + - `pre-commit install` + - `pre-commit install --hook-type pre-push` + +Run hooks manually: + +* `pre-commit run --all-files` +* `pre-commit run --all-files --hook-stage pre-push` diff --git a/Gemfile b/Gemfile index 122f66f43..e7cc339de 100644 --- a/Gemfile +++ b/Gemfile @@ -3,4 +3,12 @@ source 'https://rubygems.org' # Specify your gem's dependencies in mindee.gemspec -gemspec + +gemspec name: ENV.fetch('MINDEE_GEM_NAME', 'mindee') + +group :development, :test do + gem 'openssl', '~> 4.0' + gem 'prism', '~> 1.3' + gem 'rake', '~> 13.3' + gem 'rspec', '~> 3.13' +end diff --git a/README.md b/README.md index 0668e778a..627ff9761 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ https://app.mindee.com It uses **API version 2**. Consult the -**[V2 Documentation](https://docs.mindee.com/integrations/client-libraries-sdk)** +**V2 Documentation** ### V1 @@ -26,17 +26,17 @@ https://platform.mindee.com/ It uses **API version 1**. Consult the -[V1 Documentation](https://docs.mindee.com/v1/libraries/ruby-sdk) +V1 Documentation ## Additional Information -**[Source Code](https://github.com/mindee/mindee-api-ruby)** +**Source Code** -**[Reference Documentation](https://mindee.github.io/mindee-api-ruby/)** +**Reference Documentation** -**[Feedback](https://feedback.mindee.com/)** +**Feedback** ### License Copyright © Mindee -Available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). \ No newline at end of file +Available as open source under the terms of the MIT License. diff --git a/Rakefile b/Rakefile index d91990c61..6c296ccae 100644 --- a/Rakefile +++ b/Rakefile @@ -2,33 +2,39 @@ require 'rake' require 'rspec/core/rake_task' -require 'yard' + +is_lite_mode = ENV.fetch('MINDEE_GEM_NAME', 'mindee') == 'mindee-lite' begin require 'bundler/setup' - Bundler::GemHelper.install_tasks + require 'bundler/gem_helper' + Bundler::GemHelper.install_tasks(name: ENV.fetch('MINDEE_GEM_NAME', 'mindee')) rescue LoadError puts 'although not required, bundler is recommended for running the tests' end task default: :spec +exclusion_opts = is_lite_mode ? ['--tag', '~all_deps'] : [] +RSpec::Core::RakeTask.new(:spec) do |t| + t.rspec_opts = exclusion_opts +end +unless is_lite_mode + require 'yard' + desc 'Generate documentation' + YARD::Rake::YardocTask.new(:doc) do |task| + task.files = ['lib/**/*.rb'] + end -RSpec::Core::RakeTask.new(:spec) - -desc 'Generate documentation' -YARD::Rake::YardocTask.new(:doc) do |task| - task.files = ['lib/**/*.rb'] + Rake::Task[:doc].enhance do + FileUtils.cp_r( + File.join('docs', 'code_samples'), + File.join('docs', '_build') + ) + end end desc 'Run integration tests' RSpec::Core::RakeTask.new(:integration) do |t| t.pattern = 'spec/**/*_integration.rb' - t.rspec_opts = ['--require', 'integration_helper'] -end - -Rake::Task[:doc].enhance do - FileUtils.cp_r( - File.join('docs', 'code_samples'), - File.join('docs', '_build') - ) + t.rspec_opts = ['--require', 'integration_helper'] + exclusion_opts end diff --git a/Steepfile b/Steepfile index 73b80857a..d81fac414 100644 --- a/Steepfile +++ b/Steepfile @@ -28,4 +28,3 @@ target :lib do configure_code_diagnostics(D::Ruby.default) # `default` diagnostics setting (applies by default) end - diff --git a/bin/cli_products.rb b/bin/cli_products.rb deleted file mode 100644 index 41df18367..000000000 --- a/bin/cli_products.rb +++ /dev/null @@ -1,166 +0,0 @@ -# frozen_string_literal: true - -PRODUCTS = { - "universal" => { - description: "Universal document type from API builder", - doc_class: Mindee::Product::Universal::Universal, - sync: true, - async: true, - }, - "barcode-reader" => { - description: "Barcode Reader", - doc_class: Mindee::Product::BarcodeReader::BarcodeReaderV1, - sync: true, - async: false, - }, - "bill-of-lading" => { - description: "Bill of Lading", - doc_class: Mindee::Product::BillOfLading::BillOfLadingV1, - sync: false, - async: true, - }, - "business-card" => { - description: "Business Card", - doc_class: Mindee::Product::BusinessCard::BusinessCardV1, - sync: false, - async: true, - }, - "cropper" => { - description: "Cropper", - doc_class: Mindee::Product::Cropper::CropperV1, - sync: true, - async: false, - }, - "delivery-note" => { - description: "Delivery note", - doc_class: Mindee::Product::DeliveryNote::DeliveryNoteV1, - sync: false, - async: true, - }, - "driver-license" => { - description: "Driver License", - doc_class: Mindee::Product::DriverLicense::DriverLicenseV1, - sync: false, - async: true, - }, - "financial-document" => { - description: "Financial Document", - doc_class: Mindee::Product::FinancialDocument::FinancialDocumentV1, - sync: true, - async: true, - }, - "fr-bank-account-details" => { - description: "Bank Account Details", - doc_class: Mindee::Product::FR::BankAccountDetails::BankAccountDetailsV2, - sync: true, - async: false, - }, - "fr-bank-statement" => { - description: "Bank Statement", - doc_class: Mindee::Product::FR::BankStatement::BankStatementV2, - sync: false, - async: true, - }, - "fr-carte-grise" => { - description: "Carte Grise", - doc_class: Mindee::Product::FR::CarteGrise::CarteGriseV1, - sync: true, - async: false, - }, - "fr-energy-bill" => { - description: "Energy Bill", - doc_class: Mindee::Product::FR::EnergyBill::EnergyBillV1, - sync: false, - async: true, - }, - "fr-health-card" => { - description: "Health Card", - doc_class: Mindee::Product::FR::HealthCard::HealthCardV1, - sync: false, - async: true, - }, - "fr-carte-nationale-d-identite" => { - description: "Carte Nationale d'Identité", - doc_class: Mindee::Product::FR::IdCard::IdCardV2, - sync: true, - async: false, - }, - "fr-payslip" => { - description: "Payslip", - doc_class: Mindee::Product::FR::Payslip::PayslipV3, - sync: false, - async: true, - }, - "ind-passport-india" => { - description: "Passport - India", - doc_class: Mindee::Product::IND::IndianPassport::IndianPassportV1, - sync: false, - async: true, - }, - "international-id" => { - description: "International ID", - doc_class: Mindee::Product::InternationalId::InternationalIdV2, - sync: false, - async: true, - }, - "invoice" => { - description: "Invoice", - doc_class: Mindee::Product::Invoice::InvoiceV4, - sync: true, - async: true, - }, - "invoice-splitter" => { - description: "Invoice Splitter", - doc_class: Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, - sync: false, - async: true, - }, - "multi-receipts-detector" => { - description: "Multi Receipts Detector", - doc_class: Mindee::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1, - sync: true, - async: false, - }, - "nutrition-facts-label" => { - description: "Nutrition Facts Label", - doc_class: Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1, - sync: false, - async: true, - }, - "passport" => { - description: "Passport", - doc_class: Mindee::Product::Passport::PassportV1, - sync: true, - async: false, - }, - "receipt" => { - description: "Receipt", - doc_class: Mindee::Product::Receipt::ReceiptV5, - sync: true, - async: true, - }, - "resume" => { - description: "Resume", - doc_class: Mindee::Product::Resume::ResumeV1, - sync: false, - async: true, - }, - "us-bank-check" => { - description: "Bank Check", - doc_class: Mindee::Product::US::BankCheck::BankCheckV1, - sync: true, - async: false, - }, - "us-healthcare-card" => { - description: "Healthcare Card", - doc_class: Mindee::Product::US::HealthcareCard::HealthcareCardV1, - sync: false, - async: true, - }, - "us-us-mail" => { - description: "US Mail", - doc_class: Mindee::Product::US::UsMail::UsMailV3, - sync: false, - async: true, - }, -} diff --git a/bin/mindee.rb b/bin/mindee.rb index 6c303ef19..f6900dbed 100755 --- a/bin/mindee.rb +++ b/bin/mindee.rb @@ -3,127 +3,28 @@ require 'bundler/setup' require 'optparse' -require 'mindee' - -require_relative 'cli_products' - -options = {} - -# Initializes universal-specific options -# @param cli_parser [OptionParser] -def custom_subcommand(cli_parser, options) - cli_parser.on('-v [VERSION]', '--version [VERSION]', 'Model version for the API') do |v| - options[:endpoint_version] = v - end - cli_parser.on('-a ACCOUNT_NAME', '--account ACCOUNT_NAME', 'API account name for the endpoint') do |v| - options[:account_name] = v - end -end - -product_parser = {} -PRODUCTS.each do |doc_key, doc_value| - product_parser[doc_key] = OptionParser.new do |opts| - opts.on('-w', '--all-words', 'Include words in response') do |v| - options[:all_words] = v - end - opts.on('-c', '--cut-pages', "Cut document pages") do |v| - options[:cut_pages] = v - end - opts.on('-k [KEY]', '--key [KEY]', 'API key for the endpoint') do |v| - options[:api_key] = v - end - opts.on('-f', '--full', "Print the full data, including pages") do |v| - options[:print_full] = true - end - opts.on('-F', '--fix-pdf', "Attempts to fix broken PDF files before sending them to the server.") do |v| - options[:repair_pdf] = true - end - if doc_key != 'universal' - opts.banner = "#{doc_value[:description]}. \nUsage: \nmindee.rb universal [options] endpoint_name file\nor\nmindee.rb universal [options] endpoint_name file" - custom_subcommand(opts, options) - end - if doc_value[:async] - if doc_value[:sync] - opts.on("-A", "--async", "Call asynchronously") do |v| - options[:parse_async] = v - end - end - end +require_relative 'v1/parser' +require_relative 'v2/parser' + +def setup_main_parser + v1_parser = MindeeCLI::V1Parser.new(ARGV) + v2_parser = MindeeCLI::V2Parser.new(ARGV) + main_parser = OptionParser.new do |opts| + opts.banner = "Usage: mindee [command]" + opts.separator "Commands:" + opts.separator " v1 Use Version 1 of the Mindee API" + opts.separator " v2 Use Version 2 of the Mindee API" end -end - -global_parser = OptionParser.new do |opts| - opts.banner = "Usage: mindee.rb product [options] file" - opts.separator "Available products:" - opts.separator " #{PRODUCTS.keys.join("\n ")}" -end - -command = ARGV.shift -unless PRODUCTS.include?(command) - abort(global_parser.help) -end -doc_class = PRODUCTS[command][:doc_class] -product_parser[command].parse! + main_command = ARGV.shift -if command == 'universal' - if ARGV.length < 2 - $stderr.puts "The '#{command}' command requires both ENDPOINT_NAME and file arguments." - abort(product_parser[command].help) - end - endpoint_name = ARGV[0] - options[:file_path] = ARGV[1] -else - if ARGV.length < 1 - $stderr.puts "file missing" - abort(product_parser[command].help) - end - endpoint_name = nil - options[:file_path] = ARGV[0] -end - -mindee_client = Mindee::Client.new(api_key: options[:api_key]) -if options[:file_path].start_with?("https://") - input_source = mindee_client.source_from_url(options[:file_path]) -else - input_source = mindee_client.source_from_path(options[:file_path], repair_pdf: options[:repair_pdf]) -end - -if command == 'universal' - custom_endpoint = mindee_client.create_endpoint( - endpoint_name: endpoint_name, - account_name: options[:account_name], - version: options[:endpoint_version].nil? ? "1" : options[:endpoint_version] - ) -else - custom_endpoint = nil -end - -if options[:cut_pages].nil? || !options[:cut_pages].is_a?(Integer) || options[:cut_pages] < 0 - page_options = nil -else - page_options = Mindee::PageOptions.new(params: { - page_indexes: (0..options[:cut_pages].to_i).to_a, - operation: :KEEP_ONLY, - on_min_pages: 0, - }) -end - -if options[:parse_async].nil? - if !PRODUCTS[command][:sync] - options[:parse_async] = true + case main_command + when 'v1' + v1_parser.execute + when 'v2' + v2_parser.execute else - options[:parse_async] = false + abort(main_parser.help) end end -result = mindee_client.parse( - input_source, - doc_class, - options: { endpoint: custom_endpoint, - options: Mindee::ParseOptions.new(params: { page_options: page_options }), enqueue: options[:parse_async] } -) -if options[:print_full] - puts result.document -else - puts result.document.inference.prediction -end +setup_main_parser diff --git a/bin/v1/parser.rb b/bin/v1/parser.rb new file mode 100644 index 000000000..7d129aebd --- /dev/null +++ b/bin/v1/parser.rb @@ -0,0 +1,153 @@ +# frozen_string_literal: true + +require 'mindee' +require_relative 'products' + +module MindeeCLI + # Mindee Command Line Interface + # V1 CLI class. + class V1Parser + # @return [Array] + attr_reader :arguments + + # @return [OptionParser] + attr_reader :options_parser + + # @return [Parser] + attr_reader :product_parser + + def initialize(arguments) + @arguments = arguments + @options_parser = OptionParser.new do |opts| + opts.banner = 'Usage: mindee v1 product [options] file' + opts.separator 'Available products:' + opts.separator " #{V1_PRODUCTS.keys.join("\n ")}" + end + @product_parser = init_product_parser + end + + # @param cli_parser [OptionParser] + def custom_subcommand(cli_parser) + cli_parser.on('-v [VERSION]', '--version [VERSION]', 'Model version for the API') do |v| + @options[:endpoint_version] = v + end + cli_parser.on('-a ACCOUNT_NAME', '--account ACCOUNT_NAME', 'API account name for the endpoint') do |v| + @options[:account_name] = v + end + end + + # @return [Hash] + def init_product_parser + v1_product_parser = {} + V1_PRODUCTS.each do |doc_key, doc_value| + v1_product_parser[doc_key] = OptionParser.new do |options_parser| + options_parser.on('-w', '--all-words', 'Include words in response') { |v| @options[:all_words] = v } + options_parser.on('-k [KEY]', '--key [KEY]', 'API key for the endpoint') { |v| @options[:api_key] = v } + options_parser.on('-o FORMAT', '--output-format FORMAT', ['raw', 'full', 'summary'], + 'Format of the output (raw, full, summary). Default: summary') do |format| + @options[:output_format] = format + end + options_parser.on('-F', '--fix-pdf', 'Repair PDF') { @options[:repair_pdf] = true } + + if doc_key != 'universal' + options_parser.banner = "Usage: mindee v1 #{doc_key} [options] file" + custom_subcommand(options_parser) + end + + if doc_value[:async] && doc_value[:sync] + options_parser.on('-A', '--async', 'Call asynchronously') { |v| @options[:parse_async] = v } + end + end + end + v1_product_parser + end + + # @param product_command [String] + # @param endpoint_name [String, nil] + # @param options [Hash] + # @return [Mindee::V1::Parsing::Common::ApiResponse] + def send(product_command, endpoint_name, options) + mindee_client = Mindee::V1::Client.new(api_key: options[:api_key]) + doc_class = V1_PRODUCTS[product_command][:doc_class] + input_source = setup_input_source(mindee_client, options) + custom_endpoint = setup_endpoint(mindee_client, product_command, endpoint_name, options) + options[:parse_async] = !V1_PRODUCTS[product_command][:sync] if options[:parse_async].nil? + + mindee_client.parse( + input_source, + doc_class, + options: { endpoint: custom_endpoint, + enqueue: options[:parse_async] } + ) + end + + def print_result(result, output_format) + if output_format == :raw + puts JSON.pretty_generate(JSON.parse(result.raw_http)) + else + puts output_format == :full ? result.document : result.document.inference.prediction + end + end + + # @param product_command [String] + def execute + @options = { output_format: :summary } + product_command = @arguments.shift + + abort(@options_parser.help) unless V1_PRODUCTS.include?(product_command) + @product_parser[product_command].parse! + + if product_command == 'universal' + if @arguments.length < 2 + warn "The 'universal' command requires both ENDPOINT_NAME and file arguments." + abort(@product_parser[product_command].help) + end + endpoint_name = @arguments[0] + @options[:file_path] = @arguments[1] + else + if @arguments.empty? + warn 'file missing' + abort(@product_parser[product_command].help) + end + endpoint_name = nil + @options[:file_path] = @arguments[0] + end + + result = send(product_command, endpoint_name, @options) + print_result(result, output_format) + end + + private + + # @return [Symbol] + def output_format + @options[:output_format]&.to_sym || :summary + end + + # @param mindee_client [Mindee::V1::Client] + # @param options [Hash] + # @return [Hash] + def setup_input_source(mindee_client, options) + if options[:file_path].start_with?('https://') + mindee_client.source_from_url(options[:file_path]) + else + mindee_client.source_from_path(options[:file_path], repair_pdf: options[:repair_pdf]) + end + end + + # @param mindee_client [Mindee::V1::Client] + # @param product_command [String] + # @param endpoint_name [String, nil] + # @param options [Hash] + # @return [Mindee::HTTP::Endpoint, nil] + def setup_endpoint(mindee_client, product_command, endpoint_name, options) + return unless product_command == 'universal' + + mindee_client.create_endpoint( + endpoint_name: endpoint_name, + account_name: options[:account_name], + version: options[:endpoint_version] || '1' + ) + end + end +end diff --git a/bin/v1/products.rb b/bin/v1/products.rb new file mode 100644 index 000000000..e7133fc89 --- /dev/null +++ b/bin/v1/products.rb @@ -0,0 +1,88 @@ +# frozen_string_literal: true + +V1_PRODUCTS = { + 'universal' => { + description: 'Universal document type from API builder', + doc_class: Mindee::V1::Product::Universal::Universal, + sync: true, + async: true, + }, + 'barcode-reader' => { + description: 'Barcode Reader', + doc_class: Mindee::V1::Product::BarcodeReader::BarcodeReaderV1, + sync: true, + async: false, + }, + 'cropper' => { + description: 'Cropper', + doc_class: Mindee::V1::Product::Cropper::CropperV1, + sync: true, + async: false, + }, + 'financial-document' => { + description: 'Financial Document', + doc_class: Mindee::V1::Product::FinancialDocument::FinancialDocumentV1, + sync: true, + async: true, + }, + 'fr-bank-account-details' => { + description: 'Bank Account Details', + doc_class: Mindee::V1::Product::FR::BankAccountDetails::BankAccountDetailsV2, + sync: true, + async: false, + }, + 'fr-bank-statement' => { + description: 'Bank Statement', + doc_class: Mindee::V1::Product::FR::BankStatement::BankStatementV2, + sync: false, + async: true, + }, + 'fr-carte-nationale-d-identite' => { + description: "Carte Nationale d'Identité", + doc_class: Mindee::V1::Product::FR::IdCard::IdCardV2, + sync: true, + async: false, + }, + 'international-id' => { + description: 'International ID', + doc_class: Mindee::V1::Product::InternationalId::InternationalIdV2, + sync: false, + async: true, + }, + 'invoice' => { + description: 'Invoice', + doc_class: Mindee::V1::Product::Invoice::InvoiceV4, + sync: true, + async: true, + }, + 'invoice-splitter' => { + description: 'Invoice Splitter', + doc_class: Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, + sync: false, + async: true, + }, + 'multi-receipts-detector' => { + description: 'Multi Receipts Detector', + doc_class: Mindee::V1::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1, + sync: true, + async: false, + }, + 'passport' => { + description: 'Passport', + doc_class: Mindee::V1::Product::Passport::PassportV1, + sync: true, + async: false, + }, + 'receipt' => { + description: 'Receipt', + doc_class: Mindee::V1::Product::Receipt::ReceiptV5, + sync: true, + async: true, + }, + 'resume' => { + description: 'Resume', + doc_class: Mindee::V1::Product::Resume::ResumeV1, + sync: false, + async: true, + }, +}.freeze diff --git a/bin/v2/parser.rb b/bin/v2/parser.rb new file mode 100644 index 000000000..4f388d5b4 --- /dev/null +++ b/bin/v2/parser.rb @@ -0,0 +1,235 @@ +# frozen_string_literal: true + +require 'mindee' +require_relative 'products' + +module MindeeCLI + # Mindee Command Line Interface + # V2 CLI class. + class V2Parser + # @return [Array] + attr_reader :arguments + + # @return [OptionParser] + attr_reader :options_parser + + # @return [Parser] + attr_reader :product_parser + + # @return [Parser] + attr_reader :search_parser + + def initialize(arguments) + @arguments = arguments + @options_parser = OptionParser.new do |opts| + opts.banner = 'Usage: mindee v2 command [options]' + end + @product_parser = init_product_parser + @search_parser = init_search_parser + end + + # Summarize and print the result of the command. + # @param command [String] + def print_result(command) + if command == 'search-models' + @search_parser.parse!(@arguments) + result = search(@options) + summarized_result = output_format == :full ? result.to_s : result.models.to_s + else + @product_parser[command].parse!(@arguments) + @options[:file_path] = @arguments.shift + if @options[:file_path].nil? + warn 'file missing' + abort(@product_parser[command].help) + end + result = send(command, @options) + summarized_result = output_format == :full ? result.inference.to_s : result.inference.result.to_s + end + + if output_format == :raw + puts JSON.pretty_generate(raw_payload(result.raw_http)) + else + puts summarized_result + end + end + + # Executes the command. + # @return [void] + def execute + @options = { output_format: :summary } + command = @arguments.shift + + validate_command!(command) + print_result(command) + rescue OptionParser::InvalidOption, OptionParser::MissingArgument => e + if command == 'search-models' + abort("#{e.message}\n\n#{@search_parser.help}") + else + abort("#{e.message}\n\n#{@product_parser[command].help}") + end + end + + private + + def validate_command!(command) + return if V2_PRODUCTS.include?(command) || command == 'search-models' + + error_msg = "#{@options_parser.help}\nAvailable commands:\n" + error_msg += " #{'search-models'.ljust(50)}Search for available models for this API key\n" + + V2_PRODUCTS.each do |product_key, product_values| + error_msg += " #{product_key.to_s.ljust(50)}#{product_values[:description]}\n" + end + abort(error_msg) + end + + def init_search_parser + OptionParser.new do |options_parser| + options_parser.banner = 'Usage: mindee v2 search-models [options]' + init_common_options(options_parser) + options_parser.on('-n [NAME]', '--name [NAME]', + 'Search for partial matches in model name. Note: case insensitive') do |v| + @options[:model_name] = v + end + options_parser.on('-t [NAME]', '--type [NAME]', + 'Search for EXACT matches in model type. Note: case sensitive') do |v| + @options[:model_type] = v + end + end + end + + def setup_specific_options(options_parser, doc_value) + options_parser.on('-r', '--rag', 'Enable RAG') { @options[:rag] = true } if doc_value.key?(:rag) + if doc_value.key?(:raw_text) + options_parser.on('-R', '--raw-text', 'Enable Raw Text retrieval') do + @options[:raw_text] = true + end + end + if doc_value.key?(:confidence) + options_parser.on('-c', '--confidence', 'Enable confidence scores') do + @options[:confidence] = true + end + end + options_parser.on('-p', '--polygon', 'Enable polygons') { @options[:polygon] = true } if doc_value.key?(:polygon) + if doc_value.key?(:text_context) + options_parser.on('-t [TEXT CONTEXT]', '--text-context [TEXT CONTEXT]', 'Add Text Context') do |v| + @options[:text_context] = v + end + end + return unless doc_value.key?(:data_schema) + + options_parser.on('-d [DATA SCHEMA]', '--data-schema [DATA SCHEMA]', 'Add Data Schema') do |v| + @options[:data_schema] = v + end + end + + # Initialize common options for search and product commands. + # @param options_parser [OptionParser] + def init_common_options(options_parser) + options_parser.on('-k [KEY]', '--key [KEY]', 'API key for the endpoint') { |v| @options[:api_key] = v } + options_parser.on('-o FORMAT', '--output-format FORMAT', ['raw', 'full', 'summary'], + 'Format of the output (raw, full, summary). Default: summary') do |format| + @options[:output_format] = format + end + end + + # @return [Symbol] + def output_format + @options[:output_format]&.to_sym || :summary + end + + # Handles JSON payloads represented either as a string or an already-parsed hash. + # Also tolerates one extra JSON encoding layer. + # @param payload [String, Hash] + # @return [Hash, Array, String] + def raw_payload(payload) + parsed_payload = payload + 2.times do + break unless parsed_payload.is_a?(String) + + parsed_payload = JSON.parse(parsed_payload) + rescue JSON::ParserError + break + end + parsed_payload + end + + # @return [Hash] + def init_product_parser + v2_product_parser = {} + V2_PRODUCTS.each do |product_key, product_values| + v2_product_parser[product_key] = OptionParser.new do |options_parser| + options_parser.banner = "Usage: mindee v2 #{product_key} [options] file" + options_parser.on('-m MODEL_ID', '--model-id MODEL_ID', 'Model ID') { |v| @options[:model_id] = v } + options_parser.on('-a ALIAS', '--alias ALIAS', 'Add a file alias to the response') do |v| + @options[:alias] = v + end + init_common_options(options_parser) + options_parser.on('-F', '--fix-pdf', 'Attempt to repair PDF before enqueueing') do + @options[:repair_pdf] = true + end + setup_specific_options(options_parser, product_values) + end + end + v2_product_parser + end + + # @return [Hash] + def setup_product_params + params = { model_id: @options[:model_id] } + @options.each_pair do |key, value| + params[key] = value if V2_PRODUCTS['extraction'].include?(key) + end + params + end + + # @param product_command [String] + # @param options [Hash] + # @return [Mindee::V1::Parsing::Common::ApiResponse] + def send(product_command, options) + mindee_client = Mindee::V2::Client.new(api_key: options[:api_key]) + response_class = V2_PRODUCTS[product_command][:response_class] + input_source = setup_input_source(options) + params = setup_product_params + + mindee_client.enqueue_and_get_result( + response_class, + input_source, + params + ) + end + + # @param options [Hash] + # @return [Mindee::V2::Parsing::Search::SearchResponse] + def search(options) + mindee_client = Mindee::V2::Client.new(api_key: options[:api_key]) + mindee_client.search_models(options[:model_name], options[:model_type]) + end + + # @param options [Hash] + # @return [Mindee::Input::InputSource] + def setup_input_source(options) + if options[:file_path].start_with?('https://') + Mindee::Input::Source::URLInputSource.new(options[:file_path]) + else + Mindee::Input::Source::PathInputSource.new(options[:file_path], repair_pdf: options[:repair_pdf]) + end + end + + # @param options [Hash] + # @return [Hash, nil] + def setup_page_options(options) + if options[:cut_pages].nil? || !options[:cut_pages].is_a?(Integer) || + options[:cut_pages].negative? + nil + else + + { + page_indexes: (0..options[:cut_pages].to_i).to_a, + operation: :KEEP_ONLY, + on_min_pages: 0, + } + end + end + end +end diff --git a/bin/v2/products.rb b/bin/v2/products.rb new file mode 100644 index 000000000..d96a6acc6 --- /dev/null +++ b/bin/v2/products.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require 'mindee/v2/product' + +# NOTE: keep product names as string instead of symbols due to kebab-case. + +V2_PRODUCTS = { + 'classification' => { + description: 'Classification Utility', + response_class: Mindee::V2::Product::Classification::Classification, + }, + 'extraction' => { + description: 'Extraction Inference', + response_class: Mindee::V2::Product::Extraction::Extraction, + rag: true, + polygon: true, + confidence: true, + raw_text: true, + text_context: true, + data_schema: true, + }, + 'crop' => { + description: 'Crop Utility', + response_class: Mindee::V2::Product::Crop::Crop, + }, + 'ocr' => { + description: 'OCR Utility', + response_class: Mindee::V2::Product::OCR::OCR, + }, + 'split' => { + description: 'Split Utility', + response_class: Mindee::V2::Product::Split::Split, + }, +}.freeze diff --git a/docs/code_samples/bank_account_details_v1.txt b/docs/code_samples/bank_account_details_v1.txt index c237ef836..ce1d5994a 100644 --- a/docs/code_samples/bank_account_details_v1.txt +++ b/docs/code_samples/bank_account_details_v1.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::FR::BankAccountDetails::BankAccountDetailsV1 + Mindee::V1::Product::FR::BankAccountDetails::BankAccountDetailsV1 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/bank_account_details_v2.txt b/docs/code_samples/bank_account_details_v2.txt index 3ca5d422b..197bf18ed 100644 --- a/docs/code_samples/bank_account_details_v2.txt +++ b/docs/code_samples/bank_account_details_v2.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::FR::BankAccountDetails::BankAccountDetailsV2 + Mindee::V1::Product::FR::BankAccountDetails::BankAccountDetailsV2 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/bank_check_v1.txt b/docs/code_samples/bank_check_v1.txt deleted file mode 100644 index 142e152ed..000000000 --- a/docs/code_samples/bank_check_v1.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::US::BankCheck::BankCheckV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/bank_statement_fr_v2_async.txt b/docs/code_samples/bank_statement_fr_v2_async.txt index 570696194..8e484ba55 100644 --- a/docs/code_samples/bank_statement_fr_v2_async.txt +++ b/docs/code_samples/bank_statement_fr_v2_async.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::FR::BankStatement::BankStatementV2 + Mindee::V1::Product::FR::BankStatement::BankStatementV2 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/barcode_reader_v1.txt b/docs/code_samples/barcode_reader_v1.txt index 6e19e07f4..ca28409d0 100644 --- a/docs/code_samples/barcode_reader_v1.txt +++ b/docs/code_samples/barcode_reader_v1.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::BarcodeReader::BarcodeReaderV1 + Mindee::V1::Product::BarcodeReader::BarcodeReaderV1 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/bill_of_lading_v1_async.txt b/docs/code_samples/bill_of_lading_v1_async.txt deleted file mode 100644 index 2622f2961..000000000 --- a/docs/code_samples/bill_of_lading_v1_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::BillOfLading::BillOfLadingV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/business_card_v1_async.txt b/docs/code_samples/business_card_v1_async.txt deleted file mode 100644 index d7adfea08..000000000 --- a/docs/code_samples/business_card_v1_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::BusinessCard::BusinessCardV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/carte_grise_v1.txt b/docs/code_samples/carte_grise_v1.txt deleted file mode 100644 index 21e114998..000000000 --- a/docs/code_samples/carte_grise_v1.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::FR::CarteGrise::CarteGriseV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/cropper_v1.txt b/docs/code_samples/cropper_v1.txt index cd9693f4a..4b30cedf6 100644 --- a/docs/code_samples/cropper_v1.txt +++ b/docs/code_samples/cropper_v1.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::Cropper::CropperV1 + Mindee::V1::Product::Cropper::CropperV1 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/default.txt b/docs/code_samples/default.txt index c75db9d90..6d02fb3ac 100644 --- a/docs/code_samples/default.txt +++ b/docs/code_samples/default.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -21,7 +21,7 @@ custom_endpoint = mindee_client.create_endpoint( # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::Universal::Universal, + Mindee::V1::Product::Universal::Universal, endpoint: custom_endpoint, enqueue: false ) diff --git a/docs/code_samples/default_async.txt b/docs/code_samples/default_async.txt index e7ef3f445..3cc9af5f2 100644 --- a/docs/code_samples/default_async.txt +++ b/docs/code_samples/default_async.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -21,10 +21,9 @@ custom_endpoint = mindee_client.create_endpoint( # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::Universal::Universal, + Mindee::V1::Product::Universal::Universal, endpoint: custom_endpoint ) # Print a full summary of the parsed data in RST format puts result.document - diff --git a/docs/code_samples/delivery_notes_v1_async.txt b/docs/code_samples/delivery_notes_v1_async.txt deleted file mode 100644 index 895b3fc03..000000000 --- a/docs/code_samples/delivery_notes_v1_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::DeliveryNote::DeliveryNoteV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/driver_license_v1_async.txt b/docs/code_samples/driver_license_v1_async.txt deleted file mode 100644 index 700a4fe12..000000000 --- a/docs/code_samples/driver_license_v1_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::DriverLicense::DriverLicenseV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/energy_bill_fra_v1_async.txt b/docs/code_samples/energy_bill_fra_v1_async.txt deleted file mode 100644 index 6d20bfa59..000000000 --- a/docs/code_samples/energy_bill_fra_v1_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::FR::EnergyBill::EnergyBillV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/expense_receipts_v5.txt b/docs/code_samples/expense_receipts_v5.txt index 5eed04923..12f217d29 100644 --- a/docs/code_samples/expense_receipts_v5.txt +++ b/docs/code_samples/expense_receipts_v5.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::Receipt::ReceiptV5, + Mindee::V1::Product::Receipt::ReceiptV5, enqueue: false ) diff --git a/docs/code_samples/expense_receipts_v5_async.txt b/docs/code_samples/expense_receipts_v5_async.txt index 59420d7bc..5286db69b 100644 --- a/docs/code_samples/expense_receipts_v5_async.txt +++ b/docs/code_samples/expense_receipts_v5_async.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::Receipt::ReceiptV5 + Mindee::V1::Product::Receipt::ReceiptV5 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/financial_document_v1.txt b/docs/code_samples/financial_document_v1.txt index 61e9dbf18..bb9c656f8 100644 --- a/docs/code_samples/financial_document_v1.txt +++ b/docs/code_samples/financial_document_v1.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::FinancialDocument::FinancialDocumentV1, + Mindee::V1::Product::FinancialDocument::FinancialDocumentV1, enqueue: false ) diff --git a/docs/code_samples/financial_document_v1_async.txt b/docs/code_samples/financial_document_v1_async.txt index dc0e88428..f5d2b85d2 100644 --- a/docs/code_samples/financial_document_v1_async.txt +++ b/docs/code_samples/financial_document_v1_async.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::FinancialDocument::FinancialDocumentV1 + Mindee::V1::Product::FinancialDocument::FinancialDocumentV1 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/french_healthcard_v1_async.txt b/docs/code_samples/french_healthcard_v1_async.txt deleted file mode 100644 index 8f0ebd8da..000000000 --- a/docs/code_samples/french_healthcard_v1_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::FR::HealthCard::HealthCardV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/idcard_fr_v1.txt b/docs/code_samples/idcard_fr_v1.txt index caf4900df..7a88de63d 100644 --- a/docs/code_samples/idcard_fr_v1.txt +++ b/docs/code_samples/idcard_fr_v1.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::FR::IdCard::IdCardV1 + Mindee::V1::Product::FR::IdCard::IdCardV1 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/idcard_fr_v2.txt b/docs/code_samples/idcard_fr_v2.txt index 9ba3c71ab..b97375688 100644 --- a/docs/code_samples/idcard_fr_v2.txt +++ b/docs/code_samples/idcard_fr_v2.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::FR::IdCard::IdCardV2 + Mindee::V1::Product::FR::IdCard::IdCardV2 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/ind_passport_v1_async.txt b/docs/code_samples/ind_passport_v1_async.txt deleted file mode 100644 index af933cfc9..000000000 --- a/docs/code_samples/ind_passport_v1_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::IND::IndianPassport::IndianPassportV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/international_id_v2_async.txt b/docs/code_samples/international_id_v2_async.txt index e463ab3cd..6aa981ee1 100644 --- a/docs/code_samples/international_id_v2_async.txt +++ b/docs/code_samples/international_id_v2_async.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::InternationalId::InternationalIdV2 + Mindee::V1::Product::InternationalId::InternationalIdV2 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/invoice_splitter_v1_async.txt b/docs/code_samples/invoice_splitter_v1_async.txt index a89caf8a5..f602618b5 100644 --- a/docs/code_samples/invoice_splitter_v1_async.txt +++ b/docs/code_samples/invoice_splitter_v1_async.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::InvoiceSplitter::InvoiceSplitterV1 + Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/invoices_v4.txt b/docs/code_samples/invoices_v4.txt index 1844e9a34..b36beaf02 100644 --- a/docs/code_samples/invoices_v4.txt +++ b/docs/code_samples/invoices_v4.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::Invoice::InvoiceV4, + Mindee::V1::Product::Invoice::InvoiceV4, enqueue: false ) diff --git a/docs/code_samples/invoices_v4_async.txt b/docs/code_samples/invoices_v4_async.txt index eb0495bff..60f93eb3a 100644 --- a/docs/code_samples/invoices_v4_async.txt +++ b/docs/code_samples/invoices_v4_async.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::Invoice::InvoiceV4 + Mindee::V1::Product::Invoice::InvoiceV4 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/multi_receipts_detector_v1.txt b/docs/code_samples/multi_receipts_detector_v1.txt index 7827496c4..aa30eb140 100644 --- a/docs/code_samples/multi_receipts_detector_v1.txt +++ b/docs/code_samples/multi_receipts_detector_v1.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1 + Mindee::V1::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/nutrition_facts_v1_async.txt b/docs/code_samples/nutrition_facts_v1_async.txt deleted file mode 100644 index f3df60457..000000000 --- a/docs/code_samples/nutrition_facts_v1_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/passport_v1.txt b/docs/code_samples/passport_v1.txt index b5d94b615..842ec223a 100644 --- a/docs/code_samples/passport_v1.txt +++ b/docs/code_samples/passport_v1.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::Passport::PassportV1 + Mindee::V1::Product::Passport::PassportV1 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/payslip_fra_v3_async.txt b/docs/code_samples/payslip_fra_v3_async.txt deleted file mode 100644 index 52a074b02..000000000 --- a/docs/code_samples/payslip_fra_v3_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::FR::Payslip::PayslipV3 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/resume_v1_async.txt b/docs/code_samples/resume_v1_async.txt index 5439a462b..c042a33f9 100644 --- a/docs/code_samples/resume_v1_async.txt +++ b/docs/code_samples/resume_v1_async.txt @@ -6,7 +6,7 @@ require 'mindee' # Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') # Load a file from disk input_source = mindee_client.source_from_path('/path/to/the/file.ext') @@ -14,7 +14,7 @@ input_source = mindee_client.source_from_path('/path/to/the/file.ext') # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::Resume::ResumeV1 + Mindee::V1::Product::Resume::ResumeV1 ) # Print a full summary of the parsed data in RST format diff --git a/docs/code_samples/us_healthcare_cards_v1_async.txt b/docs/code_samples/us_healthcare_cards_v1_async.txt deleted file mode 100644 index 4b36ae963..000000000 --- a/docs/code_samples/us_healthcare_cards_v1_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::US::HealthcareCard::HealthcareCardV1 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/us_mail_v3_async.txt b/docs/code_samples/us_mail_v3_async.txt deleted file mode 100644 index b42c6affd..000000000 --- a/docs/code_samples/us_mail_v3_async.txt +++ /dev/null @@ -1,24 +0,0 @@ -# -# Install the Ruby client library by running: -# gem install mindee -# - -require 'mindee' - -# Init a new client -mindee_client = Mindee::Client.new(api_key: 'my-api-key') - -# Load a file from disk -input_source = mindee_client.source_from_path('/path/to/the/file.ext') - -# Parse the file -result = mindee_client.parse( - input_source, - Mindee::Product::US::UsMail::UsMailV3 -) - -# Print a full summary of the parsed data in RST format -puts result.document - -# Print the document-level parsed data -# puts result.document.inference.prediction diff --git a/docs/code_samples/v2_classification.txt b/docs/code_samples/v2_classification.txt index 12bcd4dca..455bba0f0 100644 --- a/docs/code_samples/v2_classification.txt +++ b/docs/code_samples/v2_classification.txt @@ -8,7 +8,7 @@ api_key = 'MY_API_KEY' model_id = 'MY_MODEL_ID' # Init a new client -mindee_client = Mindee::ClientV2.new(api_key: api_key) +mindee_client = Mindee::V2::Client.new(api_key: api_key) # Set inference parameters classification_params = { diff --git a/docs/code_samples/v2_crop.txt b/docs/code_samples/v2_crop.txt index bd4e6e576..e5760cfc7 100644 --- a/docs/code_samples/v2_crop.txt +++ b/docs/code_samples/v2_crop.txt @@ -8,7 +8,7 @@ api_key = 'MY_API_KEY' model_id = 'MY_MODEL_ID' # Init a new client -mindee_client = Mindee::ClientV2.new(api_key: api_key) +mindee_client = Mindee::V2::Client.new(api_key: api_key) # Set inference parameters crop_params = { @@ -27,4 +27,4 @@ response = mindee_client.enqueue_and_get_result( ) # Access the result crops -puts response.inference.result.crops \ No newline at end of file +puts response.inference.result.crops diff --git a/docs/code_samples/v2_extraction.txt b/docs/code_samples/v2_extraction.txt index 3c9d57e2c..079991440 100644 --- a/docs/code_samples/v2_extraction.txt +++ b/docs/code_samples/v2_extraction.txt @@ -8,10 +8,10 @@ api_key = 'MY_API_KEY' model_id = 'MY_MODEL_ID' # Init a new client -mindee_client = Mindee::ClientV2.new(api_key: api_key) +mindee_client = Mindee::V2::Client.new(api_key: api_key) # Set inference parameters -inference_params = { +extraction_params = { # ID of the model, required. model_id: model_id, @@ -35,7 +35,7 @@ input_source = Mindee::Input::Source::PathInputSource.new(input_path) response = mindee_client.enqueue_and_get_result( Mindee::V2::Product::Extraction::Extraction, input_source, - inference_params + extraction_params ) # Print a brief summary of the parsed data diff --git a/docs/code_samples/v2_extraction_webhook.txt b/docs/code_samples/v2_extraction_webhook.txt index a68f31eb7..9b5ddd28e 100644 --- a/docs/code_samples/v2_extraction_webhook.txt +++ b/docs/code_samples/v2_extraction_webhook.txt @@ -8,9 +8,9 @@ api_key = 'MY_API_KEY' model_id = 'MY_MODEL_ID' # Init a new client -mindee_client = Mindee::ClientV2.new(api_key: api_key) +mindee_client = Mindee::V2::Client.new(api_key: api_key) -inference_params = { +extraction_params = { # ID of the model, required. model_id: model_id, # Add any number of webhook IDs here. @@ -36,7 +36,7 @@ input_source = Mindee::Input::Source::PathInputSource.new(input_path) response = mindee_client.enqueue( Mindee::V2::Product::Extraction::Extraction, input_source, - inference_params + extraction_params ) # Print the job ID diff --git a/docs/code_samples/v2_ocr.txt b/docs/code_samples/v2_ocr.txt index 3a7d92508..db4f7b505 100644 --- a/docs/code_samples/v2_ocr.txt +++ b/docs/code_samples/v2_ocr.txt @@ -8,7 +8,7 @@ api_key = 'MY_API_KEY' model_id = 'MY_MODEL_ID' # Init a new client -mindee_client = Mindee::ClientV2.new(api_key: api_key) +mindee_client = Mindee::V2::Client.new(api_key: api_key) # Set inference parameters ocr_params = { @@ -21,7 +21,7 @@ input_source = Mindee::Input::Source::PathInputSource.new(input_path) # Send for processing response = mindee_client.enqueue_and_get_result( - Mindee::V2::Product::Ocr::Ocr, + Mindee::V2::Product::OCR::OCR, input_source, ocr_params ) diff --git a/docs/code_samples/v2_split.txt b/docs/code_samples/v2_split.txt index e599d927d..bc4b3ebb0 100644 --- a/docs/code_samples/v2_split.txt +++ b/docs/code_samples/v2_split.txt @@ -8,7 +8,7 @@ api_key = 'MY_API_KEY' model_id = 'MY_MODEL_ID' # Init a new client -mindee_client = Mindee::ClientV2.new(api_key: api_key) +mindee_client = Mindee::V2::Client.new(api_key: api_key) # Set inference parameters split_params = { diff --git a/docs/code_samples/workflow_execution.txt b/docs/code_samples/workflow_execution.txt index 86776a765..ac74b7330 100644 --- a/docs/code_samples/workflow_execution.txt +++ b/docs/code_samples/workflow_execution.txt @@ -8,7 +8,7 @@ require 'mindee' workflow_id = 'workflow-id' # Init a new client -mindee_client = Mindee::Client.new +mindee_client = Mindee::V1::Client.new # Load a file from disk input_source = mindee_client.source_from_path('path/to/my/file.ext') @@ -19,7 +19,7 @@ result = mindee_client.execute_workflow( workflow_id, # options: { # Optionally, you can provide the following parameters: # document_alias: 'my-document-alias', # Potential alias for the document -# priority: Mindee::Parsing::Common::ExecutionPriority::LOW, # Priority of the execution +# priority: Mindee::V1::Parsing::Common::ExecutionPriority::LOW, # Priority of the execution # rag: true # Whether to enable Retrieval-Augmented Generation # } ) diff --git a/docs/code_samples/workflow_polling.txt b/docs/code_samples/workflow_polling.txt index 3d0261ec9..20e20135e 100644 --- a/docs/code_samples/workflow_polling.txt +++ b/docs/code_samples/workflow_polling.txt @@ -8,7 +8,7 @@ require 'mindee' workflow_id = 'workflow-id' # Init a new client -mindee_client = Mindee::Client.new +mindee_client = Mindee::V1::Client.new # Load a file from disk input_source = mindee_client.source_from_path('path/to/my/file.ext') @@ -23,7 +23,7 @@ custom_endpoint = mindee_client.create_endpoint( # Parse the file result = mindee_client.parse( input_source, - Mindee::Product::Universal::Universal, + Mindee::V1::Product::Universal::Universal, endpoint: custom_endpoint, options: { rag: true, @@ -33,4 +33,3 @@ result = mindee_client.parse( # Print a full summary of the parsed data in RST format puts result.document - diff --git a/examples/auto_invoice_splitter_extraction.rb b/examples/auto_invoice_splitter_extraction.rb index b46530020..d82bc6011 100644 --- a/examples/auto_invoice_splitter_extraction.rb +++ b/examples/auto_invoice_splitter_extraction.rb @@ -3,10 +3,10 @@ require 'mindee' def invoice_splitter_auto_extraction(file_path) - mindee_client = Mindee::Client.new(api_key: 'my-api-key') + mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') input_source = mindee_client.source_from_path(file_path) - if input_source.pdf? && input_source.count_pages > 1 + if input_source.pdf? && input_source.page_count > 1 parse_multi_page(mindee_client, input_source) else parse_single_page(mindee_client, input_source) @@ -16,16 +16,16 @@ def invoice_splitter_auto_extraction(file_path) def parse_single_page(mindee_client, input_source) invoice_result = mindee_client.parse( input_source, - Mindee::Product::Invoice::InvoiceV4 + Mindee::V1::Product::Invoice::InvoiceV4 ) puts invoice_result.document end def parse_multi_page(mindee_client, input_source) - pdf_extractor = Mindee::PDF::PDFExtractor::PDFExtractor.new(input_source) + pdf_extractor = Mindee::PDF::PDFExtractor.new(input_source) invoice_splitter_response = mindee_client.parse( input_source, - Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, + Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, options: { close_file: false } ) page_groups = invoice_splitter_response.document.inference.prediction.invoice_page_groups @@ -37,7 +37,7 @@ def parse_multi_page(mindee_client, input_source) invoice_result = mindee_client.parse( extracted_pdf.as_input_source, - Mindee::Product::Invoice::InvoiceV4, + Mindee::V1::Product::Invoice::InvoiceV4, options: { close_file: false } ) puts invoice_result.document diff --git a/examples/auto_multi_receipts_detector_extraction.rb b/examples/auto_multi_receipts_detector_extraction.rb index 6280ecdef..6e4cda40c 100644 --- a/examples/auto_multi_receipts_detector_extraction.rb +++ b/examples/auto_multi_receipts_detector_extraction.rb @@ -2,24 +2,24 @@ require 'mindee' -mindee_client = Mindee::Client.new(api_key: 'my-api-key') +mindee_client = Mindee::V1::Client.new(api_key: 'my-api-key') def multi_receipts_detection(file_path, mindee_client) input_source = mindee_client.source_from_path(file_path) result_multi_receipts = mindee_client.parse( input_source, - Mindee::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1, + Mindee::V1::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1, options: { close_file: false } ) - images = Mindee::Extraction.extract_receipts(input_source, result_multi_receipts.document.inference) + images = Mindee::V1::Extraction.extract_receipts(input_source, result_multi_receipts.document.inference) images.each do |sub_image| # Optional: Save the files locally # sub_image.write_to_file("/path/to/my/extracted/file/folder") result_receipt = mindee_client.parse( sub_image.as_source, - Mindee::Product::Receipt::ReceiptV5, + Mindee::V1::Product::Receipt::ReceiptV5, options: { close_file: false } ) puts result_receipt.document diff --git a/lib/mindee.rb b/lib/mindee.rb index d05a94203..b6f6f969f 100644 --- a/lib/mindee.rb +++ b/lib/mindee.rb @@ -1,13 +1,17 @@ # frozen_string_literal: true -require 'mindee/client' -require 'mindee/client_v2' -require 'mindee/page_options' require 'mindee/logging' +require 'mindee/page_options' +require 'mindee/v1' +require 'mindee/v2' module Mindee + # Dependency management + module Dependency + end + # Mindee internal error module. - module Errors + module Error end # Custom extraction module @@ -43,25 +47,6 @@ module ImageCompressor module Logging end - # Parsing internals and fields. - module Parsing - # Common fields and functions. - module Common - end - - # Standard fields and functions. - module Standard - end - - # Universal fields and functions. - module Universal - end - - # V2-specific module. - module V2 - end - end - # Document input-related internals. module Input end @@ -85,11 +70,62 @@ module US end end + # V1-specific module. + module V1 + # HTTP module for V1. + module HTTP + end + + # Parsing internals and fields. + module Parsing + # Common fields and functions. + module Common + end + + # Standard fields and functions. + module Standard + end + + # Universal fields and functions. + module Universal + end + end + + # V1-specific products. + module Product + # French products. + module FR + end + end + end + # V2-specific module. module V2 + # Mindee internal http module. + module HTTP + end + + # File operations. + module FileOperation + # Crop operations. + module Crop + end + + # Split operations. + module Split + end + end + # Product-specific module. module Product end + + # V2 parsing module. + module Parsing + # V2 search module. + module Search + end + end end end diff --git a/lib/mindee/client.rb b/lib/mindee/client.rb deleted file mode 100644 index 39ef0dec8..000000000 --- a/lib/mindee/client.rb +++ /dev/null @@ -1,488 +0,0 @@ -# frozen_string_literal: true - -require_relative 'input' -require_relative 'http' -require_relative 'logging' -require_relative 'page_options' -require_relative 'parsing/common/api_response' -require_relative 'parsing/common/job' -require_relative 'parsing/common/workflow_response' -require_relative 'product' - -# Default owner for products. -OTS_OWNER = 'mindee' - -module Mindee - # Class for configuration options in parse calls. - # - # @!attribute all_words [bool] Whether to include the full text for each page. - # This performs a full OCR operation on the server and will increase response time. - # @!attribute full_text [bool] Whether to include the full OCR text response in compatible APIs. - # This performs a full OCR operation on the server and may increase response time. - # @!attribute close_file [bool] Whether to `close()` the file after parsing it. - # Set to false if you need to access the file after this operation. - # @!attribute page_options [PageOptions, Hash, nil] Page cutting/merge options: - # * `:page_indexes` Zero-based list of page indexes. - # * `:operation` Operation to apply on the document, given the specified page indexes: - # * `:KEEP_ONLY` - keep only the specified pages, and remove all others. - # * `:REMOVE` - remove the specified pages, and keep all others. - # * `:on_min_pages` Apply the operation only if the document has at least this many pages. - # @!attribute cropper [bool] Whether to include cropper results for each page. - # This performs a cropping operation on the server and will increase response time. - # @!attribute initial_delay_sec [Numeric] Initial delay before polling. Defaults to 2. - # @!attribute delay_sec [Numeric] Delay between polling attempts. Defaults to 1.5. - # @!attribute max_retries [Integer] Maximum number of retries. Defaults to 80. - class ParseOptions - attr_accessor :all_words, :full_text, :close_file, :page_options, :cropper, :rag, - :workflow_id, :initial_delay_sec, :delay_sec, :max_retries - - def initialize(params: {}) - params = params.transform_keys(&:to_sym) - @all_words = params.fetch(:all_words, false) - @full_text = params.fetch(:full_text, false) - @close_file = params.fetch(:close_file, true) - raw_page_options = params.fetch(:page_options, nil) - raw_page_options = PageOptions.new(params: raw_page_options) unless raw_page_options.is_a?(PageOptions) - @page_options = raw_page_options - @cropper = params.fetch(:cropper, false) - @rag = params.fetch(:rag, false) - @workflow_id = params.fetch(:workflow_id, nil) - @initial_delay_sec = params.fetch(:initial_delay_sec, 2) - @delay_sec = params.fetch(:delay_sec, 1.5) - @max_retries = params.fetch(:max_retries, 80) - end - end - - # Class for configuration options in workflow executions. - # - # @!attribute document_alias [String, nil] Alias to give to the document. - # @!attribute priority [Symbol, nil] Priority to give to the document. - # @!attribute full_text [bool] Whether to include the full OCR text response in compatible APIs. - # This performs a full OCR operation on the server and may increase response time. - # @!attribute public_url [String, nil] A unique, encrypted URL for accessing the document validation interface without - # requiring authentication. - # @!attribute rag [bool, nil] Whether to enable Retrieval-Augmented Generation. - # @!attribute page_options [PageOptions, Hash, nil] Page cutting/merge options: - # * `:page_indexes` Zero-based list of page indexes. - # * `:operation` Operation to apply on the document, given the specified page indexes: - # * `:KEEP_ONLY` - keep only the specified pages, and remove all others. - # * `:REMOVE` - remove the specified pages, and keep all others. - # * `:on_min_pages` Apply the operation only if the document has at least this many pages. - # @!attribute close_file [bool, nil] Whether to close the file after sending it. Defaults to true. - class WorkflowOptions - attr_accessor :document_alias, :priority, :full_text, :public_url, :page_options, :rag, :close_file - - def initialize(params: {}) - params = params.transform_keys(&:to_sym) - @document_alias = params.fetch(:document_alias, nil) - @priority = params.fetch(:priority, nil) - @full_text = params.fetch(:full_text, false) - @public_url = params.fetch(:public_url, nil) - @rag = params.fetch(:rag, nil) - raw_page_options = params.fetch(:page_options, nil) - raw_page_options = PageOptions.new(params: raw_page_options) unless raw_page_options.is_a?(PageOptions) - @page_options = raw_page_options - @close_file = params.fetch(:close_file, true) - end - end - - # Mindee API Client. - # See: https://developers.mindee.com/docs - class Client - # @param api_key [String] - def initialize(api_key: '') - @api_key = api_key - end - - # Enqueue a document for parsing and automatically try to retrieve it if needed. - # - # Accepts options either as a Hash or as a ParseOptions struct. - # - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param product_class [Mindee::Inference] The class of the product. - # @param endpoint [Mindee::HTTP::Endpoint, nil] Endpoint of the API. - # @param options [Hash] A hash of options to configure the parsing behavior. Possible keys: - # * `:all_words` [bool] Whether to extract all the words on each page. - # This performs a full OCR operation on the server and will increase response time. - # * `:full_text` [bool] Whether to include the full OCR text response in compatible APIs. - # This performs a full OCR operation on the server and may increase response time. - # * `:close_file` [bool] Whether to `close()` the file after parsing it. - # Set to false if you need to access the file after this operation. - # * `:page_options` [Hash, nil] Page cutting/merge options: - # - `:page_indexes` [Array] Zero-based list of page indexes. - # - `:operation` [Symbol] Operation to apply on the document, given the `page_indexes` specified: - # - `:KEEP_ONLY` - keep only the specified pages, and remove all others. - # - `:REMOVE` - remove the specified pages, and keep all others. - # - `:on_min_pages` [Integer] Apply the operation only if the document has at least this many pages. - # * `:cropper` [bool, nil] Whether to include cropper results for each page. - # This performs a cropping operation on the server and will increase response time. - # * `:initial_delay_sec` [Numeric] Initial delay before polling. Defaults to 2. - # * `:delay_sec` [Numeric] Delay between polling attempts. Defaults to 1.5. - # * `:max_retries` [Integer] Maximum number of retries. Defaults to 80. - # @param enqueue [bool] Whether to enqueue the file. - # @return [Mindee::Parsing::Common::ApiResponse] - def parse(input_source, product_class, endpoint: nil, options: {}, enqueue: true) - opts = normalize_parse_options(options) - process_pdf_if_required(input_source, opts) if input_source.is_a?(Input::Source::LocalInputSource) - endpoint ||= initialize_endpoint(product_class) - - if enqueue && product_class.has_async - enqueue_and_parse(input_source, product_class, endpoint, opts) - else - parse_sync(input_source, product_class, endpoint, opts) - end - end - - # Call prediction API on a document and parse the results. - # - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param product_class [Mindee::Inference] class of the product - # @param endpoint [Mindee::HTTP::Endpoint, nil] Endpoint of the API. - # @param options [Hash] A hash of options to configure the parsing behavior. Possible keys: - # * `:all_words` [bool] Whether to extract all the words on each page. - # This performs a full OCR operation on the server and will increase response time. - # * `:full_text` [bool] Whether to include the full OCR text response in compatible APIs. - # This performs a full OCR operation on the server and may increase response time. - # * `:close_file` [bool] Whether to `close()` the file after parsing it. - # Set to false if you need to access the file after this operation. - # * `:page_options` [Hash, nil] Page cutting/merge options: - # - `:page_indexes` [Array] Zero-based list of page indexes. - # - `:operation` [Symbol] Operation to apply on the document, given the `page_indexes` specified: - # - `:KEEP_ONLY` - keep only the specified pages, and remove all others. - # - `:REMOVE` - remove the specified pages, and keep all others. - # - `:on_min_pages` [Integer] Apply the operation only if the document has at least this many pages. - # * `:cropper` [bool, nil] Whether to include cropper results for each page. - # This performs a cropping operation on the server and will increase response time. - # @return [Mindee::Parsing::Common::ApiResponse] - def parse_sync(input_source, product_class, endpoint, options) - logger.debug("Parsing document as '#{endpoint.url_root}'") - - prediction, raw_http = endpoint.predict( - input_source, - options - ) - - Mindee::Parsing::Common::ApiResponse.new(product_class, prediction, raw_http.to_s) - end - - # Enqueue a document for async parsing - # - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # The source of the input document (local file or URL). - # @param product_class [Mindee::Inference] The class of the product. - # @param options [Hash] A hash of options to configure the enqueue behavior. Possible keys: - # * `:endpoint` [HTTP::Endpoint, nil] Endpoint of the API. - # Doesn't need to be set in the case of OTS APIs. - # * `:all_words` [bool] Whether to extract all the words on each page. - # This performs a full OCR operation on the server and will increase response time. - # * `:full_text` [bool] Whether to include the full OCR text response in compatible APIs. - # This performs a full OCR operation on the server and may increase response time. - # * `:close_file` [bool] Whether to `close()` the file after parsing it. - # Set to false if you need to access the file after this operation. - # * `:page_options` [Hash, nil] Page cutting/merge options: - # - `:page_indexes` [Array] Zero-based list of page indexes. - # - `:operation` [Symbol] Operation to apply on the document, given the `page_indexes` specified: - # - `:KEEP_ONLY` - keep only the specified pages, and remove all others. - # - `:REMOVE` - remove the specified pages, and keep all others. - # - `:on_min_pages` [Integer] Apply the operation only if the document has at least this many pages. - # * `:cropper` [bool] Whether to include cropper results for each page. - # This performs a cropping operation on the server and will increase response time. - # * `:rag` [bool] Whether to enable Retrieval-Augmented Generation. Only works if a Workflow ID is provided. - # * `:workflow_id` [String, nil] ID of the workflow to use. - # @param endpoint [Mindee::HTTP::Endpoint] Endpoint of the API. - # @return [Mindee::Parsing::Common::ApiResponse] - def enqueue(input_source, product_class, endpoint: nil, options: {}) - opts = normalize_parse_options(options) - endpoint ||= initialize_endpoint(product_class) - logger.debug("Enqueueing document as '#{endpoint.url_root}'") - - prediction, raw_http = endpoint.predict_async( - input_source, - opts - ) - Mindee::Parsing::Common::ApiResponse.new(product_class, prediction, raw_http.to_json) - end - - # Parses a queued document - # - # @param job_id [String] ID of the job (queue) to poll from - # @param product_class [Mindee::Inference] class of the product - # @param endpoint [HTTP::Endpoint, nil] Endpoint of the API - # Doesn't need to be set in the case of OTS APIs. - # - # @return [Mindee::Parsing::Common::ApiResponse] - def parse_queued(job_id, product_class, endpoint: nil) - endpoint = initialize_endpoint(product_class) if endpoint.nil? - logger.debug("Fetching queued document as '#{endpoint.url_root}'") - prediction, raw_http = endpoint.parse_async(job_id) - Mindee::Parsing::Common::ApiResponse.new(product_class, prediction, raw_http.to_json) - end - - # Enqueue a document for async parsing and automatically try to retrieve it - # - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # The source of the input document (local file or URL). - # @param product_class [Mindee::Inference] The class of the product. - # @param options [Hash] A hash of options to configure the parsing behavior. Possible keys: - # * `:endpoint` [HTTP::Endpoint, nil] Endpoint of the API. - # Doesn't need to be set in the case of OTS APIs. - # * `:all_words` [bool] Whether to extract all the words on each page. - # This performs a full OCR operation on the server and will increase response time. - # * `:full_text` [bool] Whether to include the full OCR text response in compatible APIs. - # This performs a full OCR operation on the server and may increase response time. - # * `:close_file` [bool] Whether to `close()` the file after parsing it. - # Set to false if you need to access the file after this operation. - # * `:page_options` [Hash, nil] Page cutting/merge options: - # - `:page_indexes` [Array] Zero-based list of page indexes. - # - `:operation` [Symbol] Operation to apply on the document, given the `page_indexes` specified: - # - `:KEEP_ONLY` - keep only the specified pages, and remove all others. - # - `:REMOVE` - remove the specified pages, and keep all others. - # - `:on_min_pages` [Integer] Apply the operation only if the document has at least this many pages. - # * `:cropper` [bool, nil] Whether to include cropper results for each page. - # This performs a cropping operation on the server and will increase response time. - # * `:rag` [bool] Whether to enable Retrieval-Augmented Generation. Only works if a Workflow ID is provided. - # * `:workflow_id` [String, nil] ID of the workflow to use. - # * `:initial_delay_sec` [Numeric] Initial delay before polling. Defaults to 2. - # * `:delay_sec` [Numeric] Delay between polling attempts. Defaults to 1.5. - # * `:max_retries` [Integer] Maximum number of retries. Defaults to 80. - # @param endpoint [Mindee::HTTP::Endpoint] Endpoint of the API. - # @return [Mindee::Parsing::Common::ApiResponse] - def enqueue_and_parse(input_source, product_class, endpoint, options) - validate_async_params(options.initial_delay_sec, options.delay_sec, options.max_retries) - enqueue_res = enqueue(input_source, product_class, endpoint: endpoint, options: options) - job = enqueue_res.job or raise Errors::MindeeAPIError, 'Expected job to be present' - job_id = job.id - - sleep(options.initial_delay_sec) - polling_attempts = 1 - logger.debug("Successfully enqueued document with job id: '#{job_id}'") - queue_res = parse_queued(job_id, product_class, endpoint: endpoint) - queue_res_job = queue_res.job or raise Errors::MindeeAPIError, 'Expected job to be present' - valid_statuses = [ - Mindee::Parsing::Common::JobStatus::WAITING, - Mindee::Parsing::Common::JobStatus::PROCESSING, - ] - # @type var valid_statuses: Array[(:waiting | :processing | :completed | :failed)] - while valid_statuses.include?(queue_res_job.status) && polling_attempts < options.max_retries - logger.debug("Polling server for parsing result with job id: '#{job_id}'. Attempt #{polling_attempts}") - sleep(options.delay_sec) - queue_res = parse_queued(job_id, product_class, endpoint: endpoint) - queue_res_job = queue_res.job or raise Errors::MindeeAPIError, 'Expected job to be present' - polling_attempts += 1 - end - - if queue_res_job.status != Mindee::Parsing::Common::JobStatus::COMPLETED - elapsed = options.initial_delay_sec + (polling_attempts * options.delay_sec.to_f) - raise Errors::MindeeAPIError, - "Asynchronous parsing request timed out after #{elapsed} seconds (#{polling_attempts} tries)" - end - - queue_res - end - - # Sends a document to a workflow. - # - # Accepts options either as a Hash or as a WorkflowOptions struct. - # - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param workflow_id [String] - # @param options [Hash, WorkflowOptions] Options to configure workflow behavior. Possible keys: - # * `document_alias` [String, nil] Alias to give to the document. - # * `priority` [Symbol, nil] Priority to give to the document. - # * `full_text` [bool] Whether to include the full OCR text response in compatible APIs. - # * `rag` [bool, nil] Whether to enable Retrieval-Augmented Generation. - # - # * `public_url` [String, nil] A unique, encrypted URL for accessing the document validation interface without - # requiring authentication. - # * `page_options` [Hash, nil] Page cutting/merge options: - # * `:page_indexes` Zero-based list of page indexes. - # * `:operation` Operation to apply on the document, given the `page_indexes specified: - # * `:KEEP_ONLY` - keep only the specified pages, and remove all others. - # * `:REMOVE` - remove the specified pages, and keep all others. - # * `:on_min_pages` Apply the operation only if document has at least this many pages. - # @return [Mindee::Parsing::Common::WorkflowResponse] - def execute_workflow(input_source, workflow_id, options: {}) - opts = options.is_a?(WorkflowOptions) ? options : WorkflowOptions.new(params: options) - if opts.respond_to?(:page_options) && input_source.is_a?(Input::Source::LocalInputSource) - process_pdf_if_required(input_source, opts) - end - - workflow_endpoint = Mindee::HTTP::WorkflowEndpoint.new(workflow_id, api_key: @api_key.to_s) - logger.debug("Sending document to workflow '#{workflow_id}'") - - prediction, raw_http = workflow_endpoint.execute_workflow( - input_source, - opts - ) - - Mindee::Parsing::Common::WorkflowResponse.new(Product::Universal::Universal, prediction, raw_http) - end - - # Load a prediction. - # - # @param product_class [Mindee::Inference] class of the product - # @param local_response [Mindee::Input::LocalResponse] - # @return [Mindee::Parsing::Common::ApiResponse] - def load_prediction(product_class, local_response) - raise Errors::MindeeAPIError, 'Expected LocalResponse to not be nil.' if local_response.nil? - - response_hash = local_response.as_hash || {} - raise Errors::MindeeAPIError, 'Expected LocalResponse#as_hash to return a hash.' if response_hash.nil? - - Mindee::Parsing::Common::ApiResponse.new(product_class, response_hash, response_hash.to_json) - rescue KeyError, Errors::MindeeAPIError - raise Errors::MindeeInputError, 'No prediction found in local response.' - end - - # Load a document from an absolute path, as a string. - # @param input_path [String] Path of file to open - # @param repair_pdf [bool] Attempts to fix broken pdf if true - # @return [Mindee::Input::Source::PathInputSource] - def source_from_path(input_path, repair_pdf: false) - Input::Source::PathInputSource.new(input_path, repair_pdf: repair_pdf) - end - - # Load a document from raw bytes. - # @param input_bytes [String] Encoding::BINARY byte input - # @param filename [String] The name of the file (without the path) - # @param repair_pdf [bool] Attempts to fix broken pdf if true - # @return [Mindee::Input::Source::BytesInputSource] - def source_from_bytes(input_bytes, filename, repair_pdf: false) - Input::Source::BytesInputSource.new(input_bytes, filename, repair_pdf: repair_pdf) - end - - # Load a document from a base64 encoded string. - # @param base64_string [String] Input to parse as base64 string - # @param filename [String] The name of the file (without the path) - # @param repair_pdf [bool] Attempts to fix broken pdf if true - # @return [Mindee::Input::Source::Base64InputSource] - def source_from_b64string(base64_string, filename, repair_pdf: false) - Input::Source::Base64InputSource.new(base64_string, filename, repair_pdf: repair_pdf) - end - - # Load a document from a normal Ruby `File`. - # @param input_file [File] Input file handle - # @param filename [String] The name of the file (without the path) - # @param repair_pdf [bool] Attempts to fix broken pdf if true - # @return [Mindee::Input::Source::FileInputSource] - def source_from_file(input_file, filename, repair_pdf: false) - Input::Source::FileInputSource.new(input_file, filename, repair_pdf: repair_pdf) - end - - # Load a document from a secure remote source (HTTPS). - # @param url [String] URL of the file - # @return [Mindee::Input::Source::URLInputSource] - def source_from_url(url) - Input::Source::URLInputSource.new(url) - end - - # Creates a custom endpoint with the given values. - # Do not set for standard (off the shelf) endpoints. - # - # @param endpoint_name [String] For custom endpoints, the "API name" field in the "Settings" page of the - # API Builder. Do not set for standard (off the shelf) endpoints. - # - # @param account_name [String] For custom endpoints, your account or organization username on the API Builder. - # This is normally not required unless you have a custom endpoint which has the same name as a - # standard (off the shelf) endpoint. - # @param version [String] For custom endpoints, version of the product - # @return [Mindee::HTTP::Endpoint] - def create_endpoint(endpoint_name: '', account_name: '', version: '') - initialize_endpoint( - Mindee::Product::Universal::Universal, - endpoint_name: endpoint_name, - account_name: account_name, - version: version - ) - end - - # Validates the parameters for async auto-polling - # @param initial_delay_sec [Numeric] initial delay before polling - # @param delay_sec [Numeric] delay between polling attempts - # @param max_retries [Integer, nil] maximum amount of retries. - def validate_async_params(initial_delay_sec, delay_sec, max_retries) - min_delay_sec = 1 - min_initial_delay_sec = 1 - min_retries = 2 - - if delay_sec < min_delay_sec - raise ArgumentError, - "Cannot set auto-poll delay to less than #{min_delay_sec} second(s)" - end - if initial_delay_sec < min_initial_delay_sec - raise ArgumentError, - "Cannot set initial parsing delay to less than #{min_initial_delay_sec} second(s)" - end - raise ArgumentError, "Cannot set auto-poll retries to less than #{min_retries}" if max_retries < min_retries - end - - # Creates an endpoint with the given values. Raises an error if the endpoint is invalid. - # @param product_class [Mindee::Parsing::Common::Inference] class of the product - # - # @param endpoint_name [String] For custom endpoints, the "API name" field in the "Settings" page of the - # API Builder. Do not set for standard (off the shelf) endpoints. - # - # @param account_name [String] For custom endpoints, your account or organization username on the API Builder. - # This is normally not required unless you have a custom endpoint which has the same name as a - # standard (off the shelf) endpoint. - # @param version [String] For custom endpoints, version of the product. - # @return [Mindee::HTTP::Endpoint] - def initialize_endpoint(product_class, endpoint_name: '', account_name: '', version: '') - if (endpoint_name.nil? || endpoint_name.empty?) && product_class == Mindee::Product::Universal::Universal - raise Mindee::Errors::MindeeConfigurationError, 'Missing argument endpoint_name when using custom class' - end - - endpoint_name = fix_endpoint_name(product_class, endpoint_name) - account_name = fix_account_name(account_name) - version = fix_version(product_class, version) - - HTTP::Endpoint.new(account_name, endpoint_name, version, api_key: @api_key.to_s) - end - - def fix_endpoint_name(product_class, endpoint_name) - endpoint_name.nil? || endpoint_name.empty? ? product_class.endpoint_name.to_s : endpoint_name.to_s - end - - def fix_account_name(account_name) - if account_name.nil? || account_name.empty? - logger.info("No account name provided, #{OTS_OWNER} will be used by default.") - return OTS_OWNER - end - - account_name - end - - def fix_version(product_class, version) - return version unless version.nil? || version.empty? - - if product_class.endpoint_version.nil? || product_class.endpoint_version.to_s.empty? - logger.debug('No version provided for a custom build, will attempt to poll version 1 by default.') - return '1' - end - product_class.endpoint_version || '' - end - - # If needed, converts the parsing options provided as a hash into a proper ParseOptions object. - # @param options [Hash, ParseOptions] Options. - # @return [ParseOptions] - def normalize_parse_options(options) - return options if options.is_a?(ParseOptions) - - ParseOptions.new(params: options) - end - - # Processes a PDF if parameters were provided. - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param opts [ParseOptions] - def process_pdf_if_required(input_source, opts) - return unless input_source.is_a?(Mindee::Input::Source::LocalInputSource) && - opts.page_options.on_min_pages && - input_source.pdf? - - input_source.process_pdf(opts.page_options) - end - - private :parse_sync, :validate_async_params, :initialize_endpoint, :fix_endpoint_name, :fix_version, - :fix_account_name, :process_pdf_if_required, :normalize_parse_options - end -end diff --git a/lib/mindee/client_v2.rb b/lib/mindee/client_v2.rb deleted file mode 100644 index 39def57cc..000000000 --- a/lib/mindee/client_v2.rb +++ /dev/null @@ -1,161 +0,0 @@ -# frozen_string_literal: true - -require_relative 'input' -require_relative 'http' -require_relative 'product' -require_relative 'parsing/common/api_response' -require_relative 'parsing/common/job' -require_relative 'parsing/common/workflow_response' -require_relative 'logging' - -module Mindee - # Mindee V2 API Client. - class ClientV2 - # @return [HTTP::MindeeApiV2] - private attr_reader :mindee_api - - # @param api_key [String] - def initialize(api_key: '') - @mindee_api = Mindee::HTTP::MindeeApiV2.new(api_key: api_key) - end - - # Retrieves an inference. - # @param inference_id [String] - # @return [Mindee::Parsing::V2::InferenceResponse] - def get_inference(inference_id) - @mindee_api.req_get_inference(inference_id) - end - - # Retrieves a result from a given queue or URL to the result. - # @param product [Class] The return class. - # @param resource [String] ID of the inference or URL to the result. - # @return [Mindee::Parsing::V2::BaseResponse] - def get_result(product, resource) - @mindee_api.req_get_result(product, resource) - end - - # Retrieves an inference from a given queue or URL to the job. - # @param job_id [String] ID of the job. - # @return [Mindee::Parsing::V2::JobResponse] - def get_job(job_id) - @mindee_api.req_get_job(job_id) - end - - # Enqueue a document for async parsing. - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # The source of the input document (local file or URL). - # @param params [Hash, InferenceParameters] - # @return [Mindee::Parsing::V2::JobResponse] - def enqueue_inference(input_source, params, disable_redundant_warnings: false) - unless disable_redundant_warnings - warn '[DEPRECATION] `enqueue_inference` is deprecated; use `enqueue` instead.', uplevel: 1 - end - normalized_params = normalize_parameters(Input::InferenceParameters, params) - enqueue(Mindee::Parsing::V2::Inference, input_source, normalized_params) - end - - # Enqueue a document for async parsing. - # @param product [Class] The return class. - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # The source of the input document (local file or URL). - # @param params [Hash, InferenceParameters] Parameters for the inference. - # @return [Mindee::Parsing::V2::JobResponse] - def enqueue( - product, - input_source, - params - ) - normalized_params = normalize_parameters(product.params_type, params) - normalized_params.validate_async_params - logger.debug("Enqueueing document to model '#{normalized_params.model_id}'.") - - @mindee_api.req_post_enqueue(input_source, normalized_params) - end - - # Enqueues to an asynchronous endpoint and automatically polls for a response. - # - # @param product [Class] The return class. - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # The source of the input document (local file or URL). - # @param params [Hash, InferenceParameters] Parameters for the inference. - # @return [Mindee::Parsing::Common::ApiResponse] - def enqueue_and_get_result( - product, - input_source, - params - ) - enqueue_response = enqueue(product, input_source, params) - normalized_params = normalize_parameters(product.params_type, params) - normalized_params.validate_async_params - - if enqueue_response.job.id.nil? || enqueue_response.job.id.empty? - logger.error("Failed enqueueing:\n#{enqueue_response.raw_http}") - raise Mindee::Errors::MindeeError, 'Enqueueing of the document failed.' - end - - job_id = enqueue_response.job.id - logger.debug("Successfully enqueued document with job id: #{job_id}.") - - sleep(normalized_params.polling_options.initial_delay_sec) - retry_counter = 1 - poll_results = get_job(job_id) - - while retry_counter < normalized_params.polling_options.max_retries - if poll_results.job.status == 'Failed' - break - elsif !poll_results.job.result_url.nil? - return get_result(product, poll_results.job.result_url) - end - - logger.debug( - "Successfully enqueued inference with job id: #{job_id}.\n" \ - "Attempt n°#{retry_counter}/#{normalized_params.polling_options.max_retries}.\n" \ - "Job status: #{poll_results.job.status}." - ) - - sleep(normalized_params.polling_options.delay_sec) - poll_results = get_job(job_id) - retry_counter += 1 - end - - error = poll_results.job.error - unless error.nil? - err_to_raise = Mindee::Errors::MindeeHTTPErrorV2.new(error) - # NOTE: purposefully decoupled from the line above, otherwise rubocop thinks `error` is a `message` param. - raise err_to_raise - end - - sec_count = normalized_params.polling_options.delay_sec * retry_counter - raise Mindee::Errors::MindeeError, - "Asynchronous parsing request timed out after #{sec_count} seconds" - end - - # Enqueue a document for async parsing and automatically try to retrieve it. - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # The source of the input document (local file or URL). - # @param params [Hash, InferenceParameters] Parameters for the inference. - # @return [Mindee::Parsing::V2::InferenceResponse] - def enqueue_and_get_inference(input_source, params, disable_redundant_warnings: false) - unless disable_redundant_warnings - warn '[DEPRECATION] `enqueue_and_get_inference` is deprecated; use `enqueue_and_get_result` instead.', - uplevel: 1 - end - - response = enqueue_and_get_result(Mindee::Parsing::V2::Inference, input_source, params) - unless response.is_a?(Mindee::Parsing::V2::InferenceResponse) - raise TypeError, "Invalid response type \"#{response.class}\"" - end - - response - end - - # If needed, converts the parsing options provided as a hash into a proper InferenceParameters object. - # @param params [Hash, Class] Params. - # @return [BaseParameters] - def normalize_parameters(param_class, params) - return param_class.from_hash(params: params) if params.is_a?(Hash) - - params - end - end -end diff --git a/lib/mindee/dependency.rb b/lib/mindee/dependency.rb new file mode 100644 index 000000000..6b3ce528b --- /dev/null +++ b/lib/mindee/dependency.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +module Mindee + # Centralized check for optional heavy dependencies + module Dependency + def self.check_all_dependencies + require 'origami' + require 'mini_magick' + require 'pdf-reader' + true + rescue LoadError + false + end + + @all_deps_available = check_all_dependencies + + def self.all_deps_available? + check_all_dependencies + end + + def self.require_all_deps! + raise LoadError, MINDEE_DEPENDENCIES_LOAD_ERROR unless all_deps_available? + end + + MINDEE_DEPENDENCIES_LOAD_ERROR = 'Attempted to load Mindee PDF/Image tools without required dependencies. ' \ + "If you need to process local files, please replace the 'mindee-lite' gem " \ + "with the standard 'mindee' gem in your Gemfile." + end +end diff --git a/lib/mindee/error.rb b/lib/mindee/error.rb new file mode 100644 index 000000000..e6c9b9e6e --- /dev/null +++ b/lib/mindee/error.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +require_relative 'error/mindee_error' +require_relative 'error/mindee_http_error' +require_relative 'error/mindee_http_error_v2' +require_relative 'error/mindee_input_error' diff --git a/lib/mindee/errors/mindee_error.rb b/lib/mindee/error/mindee_error.rb similarity index 96% rename from lib/mindee/errors/mindee_error.rb rename to lib/mindee/error/mindee_error.rb index 0f0cee391..1d8aa63f4 100644 --- a/lib/mindee/errors/mindee_error.rb +++ b/lib/mindee/error/mindee_error.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module Mindee - module Errors + module Error # Base class for all custom mindee errors. class MindeeError < StandardError; end diff --git a/lib/mindee/errors/mindee_http_error.rb b/lib/mindee/error/mindee_http_error.rb similarity index 98% rename from lib/mindee/errors/mindee_http_error.rb rename to lib/mindee/error/mindee_http_error.rb index 1694ef2c6..60868305f 100644 --- a/lib/mindee/errors/mindee_http_error.rb +++ b/lib/mindee/error/mindee_http_error.rb @@ -3,7 +3,7 @@ require_relative 'mindee_error' module Mindee - module Errors + module Error # API HttpError class MindeeHTTPError < MindeeError # @return [String] diff --git a/lib/mindee/errors/mindee_http_error_v2.rb b/lib/mindee/error/mindee_http_error_v2.rb similarity index 85% rename from lib/mindee/errors/mindee_http_error_v2.rb rename to lib/mindee/error/mindee_http_error_v2.rb index 90af794ab..44d331ec0 100644 --- a/lib/mindee/errors/mindee_http_error_v2.rb +++ b/lib/mindee/error/mindee_http_error_v2.rb @@ -1,10 +1,10 @@ # frozen_string_literal: true require_relative 'mindee_error' -require_relative '../parsing/v2/error_item' +require_relative '../v2/parsing/error_item' module Mindee - module Errors + module Error # API V2 HttpError class MindeeHTTPErrorV2 < MindeeError # @return [Integer] The HTTP status code returned by the server. @@ -18,9 +18,9 @@ class MindeeHTTPErrorV2 < MindeeError # @return [Array] A list of explicit error details. attr_reader :errors - # @param http_error [Hash, Mindee::Parsing::V2::ErrorResponse] + # @param http_error [Hash, Mindee::V2::Parsing::ErrorResponse] def initialize(http_error) - if http_error.is_a?(Parsing::V2::ErrorResponse) + if http_error.is_a?(V2::Parsing::ErrorResponse) http_error = { 'detail' => http_error.detail, 'status' => http_error.status, 'title' => http_error.title, @@ -33,7 +33,7 @@ def initialize(http_error) @code = http_error['code'] @errors = if http_error.key?('errors') http_error['errors'].map do |error| - Mindee::Parsing::V2::ErrorItem.new(error) + Mindee::V2::Parsing::ErrorItem.new(error) end else [] diff --git a/lib/mindee/errors/mindee_http_unknown_error_v2.rb b/lib/mindee/error/mindee_http_unknown_error_v2.rb similarity index 96% rename from lib/mindee/errors/mindee_http_unknown_error_v2.rb rename to lib/mindee/error/mindee_http_unknown_error_v2.rb index 5f2a9ebec..214264524 100644 --- a/lib/mindee/errors/mindee_http_unknown_error_v2.rb +++ b/lib/mindee/error/mindee_http_unknown_error_v2.rb @@ -3,7 +3,7 @@ require_relative 'mindee_error' module Mindee - module Errors + module Error # Unknown HTTP error for the V2 API. class MindeeHTTPUnknownErrorV2 < MindeeHTTPErrorV2 def initialize(http_error) diff --git a/lib/mindee/errors/mindee_input_error.rb b/lib/mindee/error/mindee_input_error.rb similarity index 92% rename from lib/mindee/errors/mindee_input_error.rb rename to lib/mindee/error/mindee_input_error.rb index 6554198c4..015d92510 100644 --- a/lib/mindee/errors/mindee_input_error.rb +++ b/lib/mindee/error/mindee_input_error.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module Mindee - module Errors - # Base class for errors relating to input documents. + module Error + # Base class for error relating to input documents. class MindeeInputError < MindeeError; end # Errors relating to sources (documents) handling. diff --git a/lib/mindee/errors.rb b/lib/mindee/errors.rb deleted file mode 100644 index 3c403704f..000000000 --- a/lib/mindee/errors.rb +++ /dev/null @@ -1,6 +0,0 @@ -# frozen_string_literal: true - -require_relative 'errors/mindee_error' -require_relative 'errors/mindee_http_error' -require_relative 'errors/mindee_http_error_v2' -require_relative 'errors/mindee_input_error' diff --git a/lib/mindee/extraction/multi_receipts_extractor.rb b/lib/mindee/extraction/multi_receipts_extractor.rb deleted file mode 100644 index 188a0fd05..000000000 --- a/lib/mindee/extraction/multi_receipts_extractor.rb +++ /dev/null @@ -1,30 +0,0 @@ -# frozen_string_literal: true - -module Mindee - # Custom extraction module - module Extraction - # Multi-receipts extraction - # Extracts individual receipts from multi-receipts documents. - # - # @param input_source [LocalInputSource] Local Input Source to extract sub-receipts from. - # @param inference [Inference] Results of the inference. - # @return [Array] Individual extracted receipts as an array of ExtractedMultiReceiptsImage. - def self.extract_receipts(input_source, inference) - images = [] - unless inference.prediction.receipts - raise Errors::MindeeInputError, - 'No possible receipts candidates found for Multi-Receipts extraction.' - end - - (0...input_source.count_pages).each do |page_id| - receipt_positions = inference.pages[page_id].prediction.receipts.map(&:bounding_box) - images.concat( - Mindee::Image::ImageExtractor.extract_multiple_images_from_source(input_source, page_id + 1, - receipt_positions) - ) - end - - images - end - end -end diff --git a/lib/mindee/geometry/polygon.rb b/lib/mindee/geometry/polygon.rb index e2e2b1ad5..9d99a729a 100644 --- a/lib/mindee/geometry/polygon.rb +++ b/lib/mindee/geometry/polygon.rb @@ -7,7 +7,7 @@ module Geometry class Polygon < Array # @param server_response [Hash] Raw server response hash. def initialize(server_response) - points = [] + points = [] # @type var points: Array[Mindee::Geometry::Point] server_response.map do |point| points << Point.new(point[0], point[1]) end @@ -30,7 +30,7 @@ def point_in_y?(point) # @return [String] Polygon as a string. def to_s - "(#{map(&:to_s).join(', ')})" + "(#{join(', ')})" end end end diff --git a/lib/mindee/http.rb b/lib/mindee/http.rb index 9f0e041be..5e45e2e81 100644 --- a/lib/mindee/http.rb +++ b/lib/mindee/http.rb @@ -1,7 +1,3 @@ # frozen_string_literal: true -require_relative 'http/api_settings_v2' -require_relative 'http/endpoint' require_relative 'http/http_error_handler' -require_relative 'http/mindee_api_v2' -require_relative 'http/workflow_endpoint' diff --git a/lib/mindee/http/.rubocop.yml b/lib/mindee/http/.rubocop.yml index edbfc9a92..fa1e6d506 100644 --- a/lib/mindee/http/.rubocop.yml +++ b/lib/mindee/http/.rubocop.yml @@ -5,4 +5,3 @@ Metrics/CyclomaticComplexity: Metrics/PerceivedComplexity: Max: 10 - diff --git a/lib/mindee/http/api_settings_v2.rb b/lib/mindee/http/api_settings_v2.rb deleted file mode 100644 index 2ae2dcc08..000000000 --- a/lib/mindee/http/api_settings_v2.rb +++ /dev/null @@ -1,63 +0,0 @@ -# frozen_string_literal: true - -require_relative '../version' - -module Mindee - module HTTP - # API client for version 2. - class ApiSettingsV2 - # V2 API key's default environment key name. - MINDEE_V2_API_KEY_ENV_NAME = 'MINDEE_V2_API_KEY' - # V2 API key's default value. - MINDEE_V2_API_KEY_DEFAULT = nil - - # V2 base URL default environment key name. - MINDEE_V2_BASE_URL_ENV_NAME = 'MINDEE_V2_BASE_URL' - # V2 base URL default value. - MINDEE_V2_BASE_URL_DEFAULT = 'https://api-v2.mindee.net/v2' - - # HTTP request timeout default environment key name. - MINDEE_V2_REQUEST_TIMEOUT_ENV_NAME = 'MINDEE_V2_REQUEST_TIMEOUT' - # HTTP request timeout default value. - MINDEE_V2_TIMEOUT_DEFAULT = 120 - - # Default value for the user agent (same as V1). - USER_AGENT = "mindee-api-ruby@v#{Mindee::VERSION} ruby-v#{RUBY_VERSION} #{Mindee::PLATFORM}".freeze - - # @return [String] - attr_reader :api_key - # @return [Integer] - attr_reader :request_timeout - # @return [String] - attr_reader :base_url - # @return [String] - attr_reader :user_agent - - def initialize(api_key: nil) - @request_timeout = ENV.fetch(MINDEE_V2_REQUEST_TIMEOUT_ENV_NAME, MINDEE_V2_TIMEOUT_DEFAULT).to_i - if api_key.nil? && !ENV.fetch(MINDEE_V2_API_KEY_ENV_NAME, MINDEE_V2_API_KEY_DEFAULT).to_s.empty? - logger.debug('API key set from environment') - end - @api_key = if api_key.nil? || api_key.empty? - ENV.fetch(MINDEE_V2_API_KEY_ENV_NAME, - MINDEE_V2_API_KEY_DEFAULT) - else - api_key - end - @base_url = ENV.fetch(MINDEE_V2_BASE_URL_ENV_NAME, MINDEE_V2_BASE_URL_DEFAULT).chomp('/') - @user_agent = USER_AGENT - end - - # Checks API key for a value. - # @return - # @raise [Errors::MindeeAPIError] Raises if the api key is empty or nil. - def check_api_key - return unless @api_key.nil? || @api_key.to_s.empty? - - raise Errors::MindeeAPIError, - "Missing API key. check your Client Configuration.\nYou can set this using the " \ - "'#{MINDEE_V2_API_KEY_ENV_NAME}' environment variable." - end - end - end -end diff --git a/lib/mindee/http/endpoint.rb b/lib/mindee/http/endpoint.rb deleted file mode 100644 index 3e8ffd46f..000000000 --- a/lib/mindee/http/endpoint.rb +++ /dev/null @@ -1,219 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'net/http' -require_relative 'http_error_handler' -require_relative '../version' -require_relative 'response_validation' - -module Mindee - # Mindee internal HTTP module. - module HTTP - # API key's default environment key name. - API_KEY_ENV_NAME = 'MINDEE_API_KEY' - # API key's default value. - API_KEY_DEFAULT = nil - - # Base URL default environment key name. - BASE_URL_ENV_NAME = 'MINDEE_BASE_URL' - # Base URL's default value. - BASE_URL_DEFAULT = 'https://api.mindee.net/v1' - - # HTTP request timeout default environment key name. - REQUEST_TIMEOUT_ENV_NAME = 'MINDEE_REQUEST_TIMEOUT' - # HTTP request timeout default value. - TIMEOUT_DEFAULT = 120 - - # Default value for the user agent. - USER_AGENT = "mindee-api-ruby@v#{Mindee::VERSION} ruby-v#{RUBY_VERSION} #{Mindee::PLATFORM}".freeze - - # Generic API endpoint for a product. - class Endpoint - # @return [String] - attr_reader :api_key - # @return [Integer] - attr_reader :request_timeout - # @return [String] - attr_reader :url_root - # @return [String] - attr_reader :base_url - - def initialize(owner, url_name, version, api_key: '') - @owner = owner - @url_name = url_name - @version = version - @request_timeout = ENV.fetch(REQUEST_TIMEOUT_ENV_NAME, TIMEOUT_DEFAULT).to_i - if api_key.nil? && !ENV.fetch(API_KEY_ENV_NAME, API_KEY_DEFAULT).to_s.empty? - logger.debug('API key set from environment') - end - @api_key = api_key.nil? || api_key.empty? ? ENV.fetch(API_KEY_ENV_NAME, API_KEY_DEFAULT) : api_key - @base_url = ENV.fetch(BASE_URL_ENV_NAME, BASE_URL_DEFAULT).chomp('/') - @url_root = "#{@base_url}/products/#{@owner}/#{@url_name}/v#{@version}" - end - - # Call the prediction API. - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param opts [ParseOptions] Parse options. - # @return [Array] - def predict(input_source, opts) - check_api_key - response = predict_req_post( - input_source, - opts - ) - if !response.nil? && response.respond_to?(:body) - hashed_response = JSON.parse(response.body, object_class: Hash) - return [hashed_response, response.body] if ResponseValidation.valid_sync_response?(response) - - ResponseValidation.clean_request!(response) - end - - raise Errors::MindeeError, 'Could not resolve server response.' if response.nil? - - error = ErrorHandler.handle_error(@url_name, response) - raise error - end - - # Call the prediction API. - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param opts [ParseOptions, Hash] Parse options. - # @return [Array] - def predict_async(input_source, opts) - check_api_key - response = document_queue_req_post(input_source, opts) - if !response.nil? && response.respond_to?(:body) - hashed_response = JSON.parse(response.body, object_class: Hash) - return [hashed_response, response.body] if ResponseValidation.valid_async_response?(response) - - ResponseValidation.clean_request!(response) - end - - raise Errors::MindeeError, 'Could not resolve server response.' if response.nil? - - raise ErrorHandler.handle_error(@url_name, response) - end - - # Calls the parsed async doc. - # @param job_id [String] - # @return [Array] - def parse_async(job_id) - check_api_key - response = document_queue_req_get(job_id) - hashed_response = JSON.parse(response.body, object_class: Hash) - return [hashed_response, response.body] if ResponseValidation.valid_async_response?(response) - - ResponseValidation.clean_request!(response) - error = ErrorHandler.handle_error(@url_name, response) - raise error - end - - private - - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param opts [ParseOptions] Parse options. - # @return [Net::HTTPResponse, nil] - def predict_req_post(input_source, opts) - uri = URI("#{@url_root}/predict") - - params = {} # : Hash[String | Symbol, untyped] - params[:cropper] = 'true' if opts.cropper - params[:full_text_ocr] = 'true' if opts.full_text - uri.query = URI.encode_www_form(params) - - headers = { - 'Authorization' => "Token #{@api_key}", - 'User-Agent' => USER_AGENT, - } - req = Net::HTTP::Post.new(uri, headers) - form_data = if input_source.is_a?(Mindee::Input::Source::URLInputSource) - [['document', input_source.url]] # : Array[untyped] - else - [['document', *input_source.read_contents(close: opts.close_file)]] # : Array[untyped] - end - form_data.push ['include_mvision', 'true'] if opts.all_words - - req.set_form(form_data, 'multipart/form-data') - req['Transfer-Encoding'] = 'chunked' - - Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @request_timeout) do |http| - return http.request(req) - end - raise Mindee::Errors::MindeeError, 'Could not resolve server response.' - end - - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param opts [ParseOptions] Parse options. - # @return [Net::HTTPResponse] - def document_queue_req_post(input_source, opts) - uri = if opts.workflow_id - URI("#{@base_url}/workflows/#{opts.workflow_id}/predict_async") - else - URI("#{@url_root}/predict_async") - end - - params = {} # : Hash[String | Symbol, untyped] - params[:cropper] = 'true' if opts.cropper - params[:full_text_ocr] = 'true' if opts.full_text - params[:rag] = 'true' if opts.rag - uri.query = URI.encode_www_form(params) - - headers = { - 'Authorization' => "Token #{@api_key}", - 'User-Agent' => USER_AGENT, - } - req = Net::HTTP::Post.new(uri, headers) - form_data = if input_source.is_a?(Mindee::Input::Source::URLInputSource) - [['document', input_source.url]] # : Array[untyped] - else - [['document', *input_source.read_contents(close: opts.close_file)]] # : Array[untyped] - end - form_data.push ['include_mvision', 'true'] if opts.all_words - - req.set_form(form_data, 'multipart/form-data') - req['Transfer-Encoding'] = 'chunked' - - Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @request_timeout) do |http| - return http.request(req) - end - raise Mindee::Errors::MindeeError, 'Could not resolve server response.' - end - - # @param job_id [String] - # @return [Net::HTTPResponse, nil] - def document_queue_req_get(job_id) - uri = URI("#{@url_root}/documents/queue/#{job_id}") - - headers = { - 'Authorization' => "Token #{@api_key}", - 'User-Agent' => USER_AGENT, - } - - req = Net::HTTP::Get.new(uri, headers) - - response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @request_timeout) do |http| - http.request(req) - end - - raise Errors::MindeeError, 'Could not resolve server response.' if response.nil? - - if response.code.to_i > 299 && response.code.to_i < 400 - req = Net::HTTP::Get.new(response['location'], headers) - Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @request_timeout) do |http| - response = http.request(req) - end - end - response - end - - # Checks API key - def check_api_key - return unless @api_key.nil? || @api_key.empty? - - raise Errors::MindeeAPIError, - "Missing API key for product \"'#{@url_name}' v#{@version}\" (belonging to \"#{@owner}\"), " \ - "check your Client Configuration.\nYou can set this using the " \ - "'#{HTTP::API_KEY_ENV_NAME}' environment variable." - end - end - end -end diff --git a/lib/mindee/http/http_error_handler.rb b/lib/mindee/http/http_error_handler.rb index 8785aabef..b559d9c8a 100644 --- a/lib/mindee/http/http_error_handler.rb +++ b/lib/mindee/http/http_error_handler.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'json' -require_relative '../errors/mindee_http_error' +require_relative '../error/mindee_http_error' module Mindee module HTTP @@ -81,11 +81,11 @@ def handle_error(url, response) error_obj = create_error_obj(parsed_hash) case code when 400..499 - Errors::MindeeHTTPClientError.new(error_obj || {}, url, code) + Error::MindeeHTTPClientError.new(error_obj || {}, url, code) when 500..599 - Errors::MindeeHTTPServerError.new(error_obj || {}, url, code) + Error::MindeeHTTPServerError.new(error_obj || {}, url, code) else - Errors::MindeeHTTPError.new(error_obj || {}, url, code) + Error::MindeeHTTPError.new(error_obj || {}, url, code) end end @@ -94,11 +94,11 @@ def handle_error(url, response) def generate_v2_error(hashed_response) code = hashed_response[:code].to_i if hashed_response.key?(:status) - Errors::MindeeHTTPErrorV2.new(hashed_response.transform_keys(&:to_s)) + Error::MindeeHTTPErrorV2.new(hashed_response.transform_keys(&:to_s)) elsif code < 200 || code > 399 - Errors::MindeeHTTPErrorV2.new({ 'status' => code, 'detail' => 'No details available.' }) + Error::MindeeHTTPErrorV2.new({ 'status' => code, 'detail' => 'No details available.' }) else - Errors::MindeeHTTPErrorV2.new({ 'status' => -1, 'detail' => 'Unknown Error.' }) + Error::MindeeHTTPErrorV2.new({ 'status' => -1, 'detail' => 'Unknown Error.' }) end end end diff --git a/lib/mindee/http/mindee_api_v2.rb b/lib/mindee/http/mindee_api_v2.rb deleted file mode 100644 index 1c1d4b7ef..000000000 --- a/lib/mindee/http/mindee_api_v2.rb +++ /dev/null @@ -1,215 +0,0 @@ -# frozen_string_literal: true - -require_relative 'api_settings_v2' -require_relative '../input' -require_relative '../errors' -require_relative '../parsing/v2' - -module Mindee - module HTTP - # API client for version 2. - class MindeeApiV2 - # @return [ApiSettingsV2] - attr_reader :settings - - # @param api_key [String, nil] - def initialize(api_key: nil) - @settings = ApiSettingsV2.new(api_key: api_key) - end - - # Sends a file to the inference queue. - # - # @param input_source [Input::Source::LocalInputSource, Input::Source::URLInputSource] - # @param params [Input::BaseParameters] - # @return [Mindee::Parsing::V2::JobResponse] - # @raise [Mindee::Errors::MindeeHttpErrorV2] - def req_post_enqueue(input_source, params) - @settings.check_api_key - response = enqueue( - input_source, - params - ) - Mindee::Parsing::V2::JobResponse.new(process_response(response)) - end - - # Retrieves a queued inference. - # - # @param inference_id [String] - # @return [Mindee::Parsing::V2::InferenceResponse] - def req_get_inference(inference_id) - req_get_result(Parsing::V2::Inference, inference_id) - end - - # Retrieves a result from a given queue. - # @param product [Class] The return class. - # @param resource [String] ID of the inference or URL to the result. - # @return [Mindee::Parsing::V2::BaseResponse] - def req_get_result(product, resource) - return req_get_result_url(product.response_type, resource) if uri?(resource) - - @settings.check_api_key - response = result_req_get( - resource, - product - ) - product.response_type.new(process_response(response)) - end - - # Retrieves a queued job. - # - # @param job_id [String] ID of the job or URL to the job. - # @return [Mindee::Parsing::V2::JobResponse] - def req_get_job(job_id) - @settings.check_api_key - response = inference_job_req_get( - job_id - ) - Mindee::Parsing::V2::JobResponse.new(process_response(response)) - end - - private - - # Retrieves a queued job. - # - # @param url [String] - # @return [Mindee::Parsing::V2::JobResponse] - def req_get_job_url(url) - @settings.check_api_key - response = poll(url) - Mindee::Parsing::V2::JobResponse.new(process_response(response)) - end - - # Retrieves a queued job. - # - # @param result_class [Mindee::V2::Parsing::BaseResponse] - # @param url [String] - # @return [Mindee::Parsing::V2::JobResponse] - def req_get_result_url(result_class, url) - @settings.check_api_key - response = poll(url) - result_class.new(process_response(response)) - end - - # @param resource [String] Resource to check. - # @return [Boolean] - def uri?(resource) - uri = URI.parse(resource) - throw Mindee::Errors::MindeeError, 'HTTP is not supported.' if uri.scheme == 'http' - uri.scheme == 'https' - rescue URI::BadURIError, URI::InvalidURIError - false - end - - # Converts an HTTP response to a parsed response object. - # - # @param response [Net::HTTPResponse, nil] - # @return [Hash] - # @raise Throws if the server returned an error. - def process_response(response) - if !response.nil? && response.respond_to?(:body) && ResponseValidation.valid_v2_response?(response) - return JSON.parse(response.body, object_class: Hash) - end - - response_body = if response.nil? || !response.respond_to?(:body) - '{ "status": -1, - "detail": "Empty server response." }' - else - response.body - end - raise ErrorHandler.generate_v2_error(JSON.parse(response_body).transform_keys(&:to_sym)) - end - - # Polls a queue for either a result or a job. - # @param url [String] URL, passed as a string. - # @return [Net::HTTPResponse] - def poll(url) - uri = URI(url) - headers = { - 'Authorization' => @settings.api_key, - 'User-Agent' => @settings.user_agent, - } - req = Net::HTTP::Get.new(uri, headers) - req['Transfer-Encoding'] = 'chunked' - - Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @settings.request_timeout) do |http| - return http.request(req) - end - raise Mindee::Errors::MindeeError, 'Could not resolve server response.' - end - - # Polls the API for the status of a job. - # - # @param job_id [String] ID of the job. - # @return [Net::HTTPResponse] - def inference_job_req_get(job_id) - poll("#{@settings.base_url}/jobs/#{job_id}") - end - - # Polls the API for the result of an inference. - # - # @param queue_id [String] ID of the queue. - # @return [Net::HTTPResponse] - def inference_result_req_get(queue_id) - poll("#{@settings.base_url}/inferences/#{queue_id}") - end - - # Polls the API for the result of an inference. - # - # @param queue_id [String] ID of the queue. - # @param product [Class] The return class. - # @return [Net::HTTPResponse] - def result_req_get(queue_id, product) - poll("#{@settings.base_url}/products/#{product.slug}/results/#{queue_id}") - end - - # Handle parameters for the enqueue form - # @param form_data [Array] Array of form fields - # @param params [Input::InferenceParameters] Inference options. - def enqueue_form_options(form_data, params) - # deal with optional features - form_data.push(['rag', params.rag.to_s]) unless params.rag.nil? - form_data.push(['raw_text', params.raw_text.to_s]) unless params.raw_text.nil? - form_data.push(['polygon', params.polygon.to_s]) unless params.polygon.nil? - form_data.push(['confidence', params.confidence.to_s]) unless params.confidence.nil? - form_data.push ['file_alias', params.file_alias] if params.file_alias - form_data.push ['text_context', params.text_context] if params.text_context - form_data.push ['data_schema', params.data_schema.to_s] if params.data_schema - unless params.webhook_ids.nil? || params.webhook_ids.empty? - form_data.push ['webhook_ids', params.webhook_ids.join(',')] - end - form_data - end - - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param params [Input::BaseParameters] Inference options. - # @return [Net::HTTPResponse, nil] - def enqueue(input_source, params) - uri = URI("#{@settings.base_url}/products/#{params.slug}/enqueue") - - form_data = if input_source.is_a?(Mindee::Input::Source::URLInputSource) - [['url', input_source.url]] # : Array[untyped] - else - file_data, file_metadata = input_source.read_contents(close: params.close_file) - [['file', file_data, file_metadata]] # : Array[untyped] - end - form_data.push(['model_id', params.model_id]) - - form_data = params.append_form_data(form_data) - - headers = { - 'Authorization' => @settings.api_key, - 'User-Agent' => @settings.user_agent, - } - req = Net::HTTP::Post.new(uri, headers) - - req.set_form(form_data, 'multipart/form-data') - req['Transfer-Encoding'] = 'chunked' - - Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @settings.request_timeout) do |http| - return http.request(req) - end - raise Mindee::Errors::MindeeError, 'Could not resolve server response.' - end - end - end -end diff --git a/lib/mindee/http/response_validation.rb b/lib/mindee/http/response_validation.rb index 05d883208..e4551a39f 100644 --- a/lib/mindee/http/response_validation.rb +++ b/lib/mindee/http/response_validation.rb @@ -51,7 +51,7 @@ def self.valid_async_response?(response) hashed_response = JSON.parse(response.body, object_class: Hash) - return false if hashed_response.dig('job', 'status') == Mindee::Parsing::Common::JobStatus::FAILURE + return false if hashed_response.dig('job', 'status') == Mindee::V1::Parsing::Common::JobStatus::FAILURE return false if hashed_response.dig('job', 'error') && !hashed_response.dig('job', 'error').empty? @@ -71,7 +71,8 @@ def self.clean_request!(response) end return if !hashed_response.dig('job', 'error').empty? && - (hashed_response.dig('job', 'status').downcase != Mindee::Parsing::Common::JobStatus::FAILURE.to_s) + (hashed_response.dig('job', + 'status').downcase != Mindee::V1::Parsing::Common::JobStatus::FAILURE.to_s) response.instance_variable_set(:@code, '500') end diff --git a/lib/mindee/http/workflow_endpoint.rb b/lib/mindee/http/workflow_endpoint.rb deleted file mode 100644 index 2175793e6..000000000 --- a/lib/mindee/http/workflow_endpoint.rb +++ /dev/null @@ -1,91 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'net/http' -require_relative 'http_error_handler' - -module Mindee - module HTTP - # Handles the routing for workflow calls. - class WorkflowEndpoint - # @return [String] - attr_reader :api_key - # @return [Integer] - attr_reader :request_timeout - # @return [String] - attr_reader :url - - def initialize(workflow_id, api_key: '') - @request_timeout = ENV.fetch(REQUEST_TIMEOUT_ENV_NAME, TIMEOUT_DEFAULT).to_i - @api_key = api_key.nil? || api_key.empty? ? ENV.fetch(API_KEY_ENV_NAME, API_KEY_DEFAULT) : api_key - base_url = ENV.fetch(BASE_URL_ENV_NAME, BASE_URL_DEFAULT) - @url = "#{base_url.chomp('/')}/workflows/#{workflow_id}/executions" - end - - # Sends a document to the workflow. - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param opts [WorkflowOptions] Options to configure workflow execution behavior. - # @return [Array] - def execute_workflow(input_source, opts) - check_api_key - response = workflow_execution_req_post(input_source, opts) - if response.nil? - raise Mindee::Errors::MindeeHTTPError.new( - { code: 0, details: 'Server response was nil.', message: 'Unknown error.' }, @url, 0 - ) - end - - hashed_response = JSON.parse(response.body, object_class: Hash) - return [hashed_response, response.body] if ResponseValidation.valid_async_response?(response) - - ResponseValidation.clean_request!(response) - error = Mindee::HTTP::ErrorHandler.handle_error(@url_name, response) - raise error - end - - # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] - # @param opts [WorkflowOptions] Options to configure workflow execution behavior. - # @return [Net::HTTPResponse, nil] - def workflow_execution_req_post(input_source, opts) - uri = URI(@url) - params = {} # : Hash[String | Symbol, untyped] - params[:full_text_ocr] = 'true' if opts.full_text - params[:rag] = 'true' if opts.rag - uri.query = URI.encode_www_form(params) if params.any? - - headers = { - 'Authorization' => "Token #{@api_key}", - 'User-Agent' => USER_AGENT, - } - req = Net::HTTP::Post.new(uri, headers) - form_data = [] # : Array[untyped] - if input_source.is_a?(Mindee::Input::Source::URLInputSource) - form_data.push ['document', input_source.url] - else - form_data.push ['document', *input_source.read_contents(close: opts.close_file)] - end - form_data.push ['alias', opts.document_alias] if opts.document_alias - form_data.push ['public_url', opts.public_url] if opts.public_url - form_data.push ['priority', opts.priority.to_s] if opts.priority - - req.set_form(form_data, 'multipart/form-data') - req['Transfer-Encoding'] = 'chunked' - - response = nil - Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @request_timeout) do |http| - response = http.request(req) - end - response - end - - # Checks API key - def check_api_key - return unless @api_key.nil? || @api_key.empty? - - raise Errors::MindeeConfigurationError, "Missing API key. Check your Client Configuration.\n" \ - "You can set this using the '#{HTTP::API_KEY_ENV_NAME}'" \ - 'environment variable.' - end - end - end -end diff --git a/lib/mindee/image/extracted_image.rb b/lib/mindee/image/extracted_image.rb index 71d525455..afd3f5864 100644 --- a/lib/mindee/image/extracted_image.rb +++ b/lib/mindee/image/extracted_image.rb @@ -18,23 +18,29 @@ class ExtractedImage attr_reader :buffer # Internal name for the file. - attr_reader :internal_file_name + attr_reader :filename # Initializes the ExtractedImage with a buffer and an internal file name. # - # @param input_source [LocalInputSource] Local source for input. + # @param input_source [LocalInputSource, BytesInputSource] Local source for input. # @param page_id [Integer] ID of the page the element was found on. # @param element_id [Integer, nil] ID of the element in a page. - def initialize(input_source, page_id, element_id) + # @param preserve_input_filename [Boolean] If true, keep the input source filename as-is. + def initialize(input_source, page_id, element_id, preserve_input_filename: false) @buffer = StringIO.new(input_source.io_stream.read.to_s) @buffer.rewind - extension = if input_source.pdf? - '.jpg' + + @filename = if preserve_input_filename + input_source.filename.to_s else - File.extname(input_source.filename) + extension = if input_source.pdf? + '.jpg' + else + File.extname(input_source.filename) + end + base_name = File.basename(input_source.filename, File.extname(input_source.filename)) + "#{base_name}_p#{page_id}_#{element_id}#{extension}" end - base_name = File.basename(input_source.filename, File.extname(input_source.filename)) - @internal_file_name = "#{base_name}_p#{page_id}_#{element_id}#{extension}" @page_id = page_id @element_id = element_id.nil? ? 0 : element_id end @@ -48,7 +54,7 @@ def initialize(input_source, page_id, element_id) def write_to_file(output_path, file_format = nil) resolved_path = Pathname.new(File.expand_path(output_path)) if file_format.nil? - raise Errors::MindeeImageError, 'Invalid file format.' if resolved_path.extname.delete('.').empty? + raise Error::MindeeImageError, 'Invalid file format.' if resolved_path.extname.delete('.').empty? file_format = resolved_path.extname.delete('.').upcase end @@ -59,8 +65,8 @@ def write_to_file(output_path, file_format = nil) image.write resolved_path.to_s logger.info("File saved successfully to '#{resolved_path}'") rescue StandardError - raise Errors::MindeeImageError, "Could not save file '#{output_path}'. " \ - 'Is the provided file path valid?.' + raise Error::MindeeImageError, "Could not save file '#{output_path}'. " \ + 'Is the provided file path valid?.' end end @@ -69,7 +75,14 @@ def write_to_file(output_path, file_format = nil) # @return [FileInputSource] A BufferInput source. def as_source @buffer.rewind - Mindee::Input::Source::BytesInputSource.new(@buffer.read || '', @internal_file_name) + Mindee::Input::Source::BytesInputSource.new(@buffer.read || '', @filename) + end + + # Return the file as a Mindee-compatible BufferInput source. + # + # @return [FileInputSource] A BufferInput source. + def as_input_source + as_source end end end diff --git a/lib/mindee/image/image_extractor.rb b/lib/mindee/image/image_extractor.rb index 685178553..e8231a360 100644 --- a/lib/mindee/image/image_extractor.rb +++ b/lib/mindee/image/image_extractor.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +Mindee::Dependency.require_all_deps! require 'mini_magick' require 'origami' require 'stringio' @@ -47,7 +48,7 @@ def self.extract_multiple_images_from_source(input_source, page_id, polygons) # @param [Array] polygons # @return [Array] Extracted Images. def self.extract_images_from_polygons(input_source, pdf_stream, page_id, polygons) - extracted_elements = [] + extracted_elements = [] # @type var extracted_elements: Array[Image::ExtractedImage] polygons.each_with_index do |polygon, element_id| polygon = ImageUtils.normalize_polygon(polygon) @@ -94,7 +95,8 @@ def self.create_extracted_image(buffer, file_name, page_id, element_id) ExtractedImage.new( Input::Source::BytesInputSource.new(buffer.read.to_s, file_name), page_id, - element_id + element_id, + preserve_input_filename: true ) end diff --git a/lib/mindee/image/image_utils.rb b/lib/mindee/image/image_utils.rb index 5accd8f1b..a9f3bd694 100644 --- a/lib/mindee/image/image_utils.rb +++ b/lib/mindee/image/image_utils.rb @@ -37,7 +37,7 @@ def self.to_image(image) MiniMagick::Image.read(image) else img_class = image.class ? image.class.to_s : 'unknown format' - raise Errors::MindeeImageError, "Expected an I/O object or a MiniMagick::Image. '#{img_class}' given instead." + raise Error::MindeeImageError, "Expected an I/O object or a MiniMagick::Image. '#{img_class}' given instead." end end @@ -60,7 +60,7 @@ def self.image_to_stringio(image, format = 'JPEG') # @param max_width [Integer] Maximum width. If not specified, the horizontal ratio will remain the same. # @param max_height [Integer] Maximum height. If not specified, the vertical ratio will remain the same. def self.calculate_new_dimensions(original, max_width: nil, max_height: nil) - raise Errors::MindeeImageError, 'Provided image could not be processed for resizing.' if original.nil? + raise Error::MindeeImageError, 'Provided image could not be processed for resizing.' if original.nil? return [original.width, original.height] if max_width.nil? && max_height.nil? @@ -111,7 +111,7 @@ def self.normalize_polygon(polygon) elsif polygon.is_a?(Mindee::Geometry::Quadrilateral) polygon else - raise Errors::MindeeGeometryError, 'Provided polygon has an invalid type.' + raise Error::MindeeGeometryError, 'Provided polygon has an invalid type.' end end diff --git a/lib/mindee/input.rb b/lib/mindee/input.rb index 9bbf38a87..7c651f670 100644 --- a/lib/mindee/input.rb +++ b/lib/mindee/input.rb @@ -1,6 +1,4 @@ # frozen_string_literal: true -require_relative 'input/data_schema' -require_relative 'input/inference_parameters' require_relative 'input/polling_options' require_relative 'input/sources' diff --git a/lib/mindee/input/base_parameters.rb b/lib/mindee/input/base_parameters.rb index 680353e5e..0651f2c75 100644 --- a/lib/mindee/input/base_parameters.rb +++ b/lib/mindee/input/base_parameters.rb @@ -31,7 +31,7 @@ def initialize( polling_options: nil, close_file: true ) - raise Errors::MindeeInputError, 'Model ID is required.' if model_id.empty? || model_id.nil? + raise Error::MindeeInputError, 'Model ID is required.' if model_id.empty? || model_id.nil? @model_id = model_id @file_alias = file_alias @@ -54,6 +54,9 @@ def slug self.class.slug end + # Load from a hash + # @param [Hash] params Parameters to provide as a hash. + # @return [BaseParameters] def self.from_hash(params: {}) load_from_hash(params: params) new( @@ -72,7 +75,7 @@ def self.load_from_hash(params: {}) params.transform_keys!(&:to_sym) if params.empty? || params[:model_id].nil? || params[:model_id].empty? - raise Errors::MindeeInputError, 'Model ID is required.' + raise Error::MindeeInputError, 'Model ID is required.' end polling_options_input = params.fetch(:page_options, PollingOptions.new) diff --git a/lib/mindee/input/data_schema.rb b/lib/mindee/input/data_schema.rb deleted file mode 100644 index 1aca73a99..000000000 --- a/lib/mindee/input/data_schema.rb +++ /dev/null @@ -1,126 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Input - # Data Schema Field. - class DataSchemaField - # @return [String] Display name for the field, also impacts inference results. - attr_reader :title - # @return [String] Name of the field in the data schema. - attr_reader :name - # @return [Boolean] Whether this field can contain multiple values. - attr_reader :is_array - # @return [String] Data type of the field. - attr_reader :type - # @return [Array, nil] Allowed values when type is `classification`. Leave empty for other types. - attr_reader :classification_values - # @return [Boolean, nil] Whether to remove duplicate values in the array. - # Only applicable if `is_array` is True. - attr_reader :unique_values - # @return [String, nil] Detailed description of what this field represents. - attr_reader :description - # @return [String, nil] Optional extraction guidelines. - attr_reader :guidelines - # @return [Array, nil] Nested fields. - attr_reader :nested_fields - - # @param field [Hash] - def initialize(field) - field.transform_keys!(&:to_sym) - @name = field[:name] - @title = field[:title] - @is_array = field[:is_array] - @type = field[:type] - @classification_values = field[:classification_values] - @unique_values = field[:unique_values] - @description = field[:description] - @guidelines = field[:guidelines] - @nested_fields = field[:nested_fields] - end - - # @return [Hash] - def to_hash - out = { - name: @name, - title: @title, - is_array: @is_array, - type: @type, - } # @type var out: Hash[Symbol, untyped] - out[:classification_values] = @classification_values unless @classification_values.nil? - out[:unique_values] = @unique_values unless @unique_values.nil? - out[:description] = @description unless @description.nil? - out[:guidelines] = @guidelines unless @guidelines.nil? - out[:nested_fields] = @nested_fields unless @nested_fields.nil? - out - end - - # @return [String] - def to_s - to_hash.to_json - end - end - - # The structure to completely replace the data schema of the model. - class DataSchemaReplace - # @return [Array] Subfields when type is `nested_object`. Leave empty for other types. - attr_reader :fields - - # @param data_schema_replace [Hash] - def initialize(data_schema_replace) - data_schema_replace.transform_keys!(&:to_sym) - fields_list = data_schema_replace[:fields] - raise Mindee::Errors::MindeeError, 'Invalid Data Schema provided.' if fields_list.nil? - raise TypeError, 'Data Schema replacement fields cannot be empty.' if fields_list.empty? - - @fields = fields_list.map { |field| DataSchemaField.new(field) } - end - - # @return [Hash] - def to_hash - { fields: @fields.map(&:to_hash) } - end - - # @return [String] - def to_s - to_hash.to_json - end - end - - # Modify the Data Schema. - class DataSchema - # @return [Mindee::Input::DataSchemaReplace] - attr_reader :replace - - # @param data_schema [Hash, String] - def initialize(data_schema) - case data_schema - when String - parsed = JSON.parse(data_schema.to_s, object_class: Hash) - parsed.transform_keys!(&:to_sym) - @replace = DataSchemaReplace.new(parsed[:replace]) - when Hash - data_schema.transform_keys!(&:to_sym) - @replace = if data_schema[:replace].is_a?(DataSchemaReplace) - data_schema[:replace] - else - DataSchemaReplace.new(data_schema[:replace]) - end - when DataSchema - @replace = data_schema.replace - else - raise TypeError, 'Invalid Data Schema provided.' - end - end - - # @return [Hash] - def to_hash - { replace: @replace.to_hash } - end - - # @return [String] - def to_s - to_hash.to_json - end - end - end -end diff --git a/lib/mindee/input/inference_parameters.rb b/lib/mindee/input/inference_parameters.rb deleted file mode 100644 index a377d052c..000000000 --- a/lib/mindee/input/inference_parameters.rb +++ /dev/null @@ -1,119 +0,0 @@ -# frozen_string_literal: true - -require_relative 'data_schema' -require_relative '../input/base_parameters' - -module Mindee - module Input - # Parameters to set when sending a file for inference. - class InferenceParameters < Mindee::Input::BaseParameters - # @return [Boolean, nil] Enhance extraction accuracy with Retrieval-Augmented Generation. - attr_reader :rag - - # @return [Boolean, nil] Extract the full text content from the document as strings, - # and fill the raw_text` attribute. - attr_reader :raw_text - - # @return [Boolean, nil] Calculate bounding box polygons for all fields, - # and fill their `locations` attribute. - attr_reader :polygon - - # @return [Boolean, nil] Boost the precision and accuracy of all extractions. - # Calculate confidence scores for all fields, and fill their confidence attribute. - attr_reader :confidence - - # @return [String, nil] Additional text context used by the model during inference. - # Not recommended, for specific use only. - attr_reader :text_context - - # @return [DataSchemaField] - attr_reader :data_schema - - # @return [String] Slug for the endpoint. - def self.slug - 'extraction' - end - - # rubocop:disable Metrics/ParameterLists - # @param [String] model_id ID of the model - # @param [Boolean, nil] rag Whether to enable RAG. - # @param [Boolean, nil] raw_text Whether to enable rax text. - # @param [Boolean, nil] polygon Whether to enable polygons. - # @param [Boolean, nil] confidence Whether to enable confidence scores. - # @param [String, nil] file_alias File alias, if applicable. - # @param [Array, nil] webhook_ids - # @param [String, nil] text_context - # @param [Hash, nil] polling_options - # @param [Boolean, nil] close_file - # @param [DataSchemaField, String, Hash nil] data_schema - def initialize( - model_id, - rag: nil, - raw_text: nil, - polygon: nil, - confidence: nil, - file_alias: nil, - webhook_ids: nil, - text_context: nil, - polling_options: nil, - close_file: true, - data_schema: nil - ) - super( - model_id, - file_alias: file_alias, - webhook_ids: webhook_ids, - polling_options: polling_options, - close_file: close_file - ) - - @rag = rag - @raw_text = raw_text - @polygon = polygon - @confidence = confidence - @text_context = text_context - @data_schema = DataSchema.new(data_schema) unless data_schema.nil? - # rubocop:enable Metrics/ParameterLists - end - - # Appends inference-specific form data to the provided array. - # @param [Array] form_data Array of form fields - # @return [Array] - def append_form_data(form_data) - new_form_data = super - - new_form_data.push(['rag', @rag.to_s]) unless @rag.nil? - new_form_data.push(['raw_text', @raw_text.to_s]) unless @raw_text.nil? - new_form_data.push(['polygon', @polygon.to_s]) unless @polygon.nil? - new_form_data.push(['confidence', @confidence.to_s]) unless @confidence.nil? - new_form_data.push(['text_context', @text_context]) if @text_context - new_form_data.push(['data_schema', @data_schema.to_s]) if @data_schema - - new_form_data - end - - # Loads a prediction from a Hash. - # @param [Hash] params Parameters to provide as a hash. - # @return [InferenceParameters] - def self.from_hash(params: {}) - rag = params.fetch(:rag, nil) - raw_text = params.fetch(:raw_text, nil) - polygon = params.fetch(:polygon, nil) - confidence = params.fetch(:confidence, nil) - base_params = load_from_hash(params: params) - new_params = base_params.merge(rag: rag, raw_text: raw_text, polygon: polygon, confidence: confidence) - model_id = new_params.fetch(:model_id) - - InferenceParameters.new( - model_id, rag: rag, - raw_text: raw_text, - polygon: polygon, - confidence: confidence, - file_alias: params.fetch(:file_alias, nil), - webhook_ids: params.fetch(:webhook_ids, nil), - close_file: params.fetch(:close_file, true) - ) - end - end - end -end diff --git a/lib/mindee/input/local_response.rb b/lib/mindee/input/local_response.rb index 5e6c14400..211953a0a 100644 --- a/lib/mindee/input/local_response.rb +++ b/lib/mindee/input/local_response.rb @@ -27,7 +27,7 @@ def initialize(input_file) end @file.rewind else - raise Errors::MindeeInputError, "Incompatible type for input '#{input_file.class}'." + raise Error::MindeeInputError, "Incompatible type for input '#{input_file.class}'." end end @@ -38,7 +38,7 @@ def as_hash file_str = @file.read or raise 'File could not be read' JSON.parse(file_str, object_class: Hash) rescue JSON::ParserError - raise Errors::MindeeInputError, "File is not a valid dict. #{file_str}" + raise Error::MindeeInputError, "File is not a valid dict. #{file_str}" end # Processes the secret key @@ -57,7 +57,7 @@ def get_hmac_signature(secret_key) mac = OpenSSL::HMAC.hexdigest(algorithm, self.class.process_secret_key(secret_key), @file.read || raise('File could not be read')) rescue StandardError - raise Errors::MindeeInputError, 'Could not get HMAC signature from payload.' + raise Error::MindeeInputError, 'Could not get HMAC signature from payload.' end mac end @@ -70,12 +70,10 @@ def valid_hmac_signature?(secret_key, signature) end # Deserializes a loaded response - # @param response_class [Parsing::V2::CommonResponse] class to return. - # @return [Parsing::V2::JobResponse, Mindee::V2::Parsing::CommonResponse] + # @param response_class [Class] class to return. + # @return [V2::Parsing::JobResponse, Mindee::V2::Parsing::BaseResponse] def deserialize_response(response_class) - response_class.new(as_hash) # : Mindee::Parsing::V2::JobResponse | Mindee::Parsing::V2::InferenceResponse - rescue StandardError - raise Errors::MindeeInputError, 'Invalid response provided.' + response_class.new(as_hash) # : Mindee::V2::Parsing::JobResponse | Mindee::V2::Parsing::BaseResponse end end end diff --git a/lib/mindee/input/sources/local_input_source.rb b/lib/mindee/input/sources/local_input_source.rb index 45e1116b5..ebaabf1b8 100644 --- a/lib/mindee/input/sources/local_input_source.rb +++ b/lib/mindee/input/sources/local_input_source.rb @@ -4,8 +4,9 @@ require 'marcel' require 'fileutils' -require_relative '../../pdf' -require_relative '../../image' +require_relative '../../dependency' +require_relative '../../pdf' if Mindee::Dependency.all_deps_available? +require_relative '../../image' if Mindee::Dependency.all_deps_available? module Mindee module Input @@ -53,7 +54,7 @@ def initialize(io_stream, filename, repair_pdf: false) return if ALLOWED_MIME_TYPES.include? @file_mimetype end - raise Errors::MindeeMimeTypeError, @file_mimetype.to_s + raise Error::MindeeMimeTypeError, @file_mimetype.to_s end # @deprecated See {#fix_pdf!} or {#self.fix_pdf} instead. @@ -69,7 +70,7 @@ def pdf? # Attempts to fix the PDF data in the file. # @param maximum_offset [Integer] Maximum offset to look for the PDF header. # @return [void] - # @raise [Mindee::Errors::MindeePDFError] + # @raise [Mindee::Error::MindeePDFError] def fix_pdf!(maximum_offset: 500) @io_stream = LocalInputSource.fix_pdf(@io_stream, maximum_offset: maximum_offset) @io_stream.rewind @@ -80,11 +81,11 @@ def fix_pdf!(maximum_offset: 500) # @param stream [StringIO] The stream to fix. # @param maximum_offset [Integer] Maximum offset to look for the PDF header. # @return [StringIO] The fixed stream. - # @raise [Mindee::Errors::MindeePDFError] + # @raise [Mindee::Error::MindeePDFError] def self.fix_pdf(stream, maximum_offset: 500) out_stream = StringIO.new stream.gets('%PDF-') - raise Errors::MindeePDFError if stream.eof? || stream.pos > maximum_offset + raise Error::MindeePDFError if stream.eof? || stream.pos > maximum_offset stream.pos = stream.pos - 5 out_stream << stream.read @@ -142,6 +143,9 @@ def write_to_file(path) # Defaults to one for images. # @return [Integer] def page_count + unless Mindee::Dependency.all_deps_available? + raise NotImplementedError, Mindee::Dependency::MINDEE_DEPENDENCIES_LOAD_ERROR + end return 1 unless pdf? @io_stream.seek(0) @@ -149,14 +153,6 @@ def page_count pdf_processor.pages.size end - # Returns the page count for a document. - # Defaults to one for images. - # @return [Integer] - # @deprecated Use {#page_count} instead. - def count_pages - page_count - end - # Compresses the file, according to the provided info. # @param [Integer] quality Quality of the output file. # @param [Integer, nil] max_width Maximum width (Ignored for PDFs). @@ -167,6 +163,10 @@ def count_pages # @param [bool] disable_source_text If the PDF has source text, whether to re-apply it to the original or # not. Needs force_source_text to work. def compress!(quality: 85, max_width: nil, max_height: nil, force_source_text: false, disable_source_text: true) + unless Mindee::Dependency.all_deps_available? + raise NotImplementedError, Mindee::Dependency::MINDEE_DEPENDENCIES_LOAD_ERROR + end + buffer = if pdf? Mindee::PDF::PDFCompressor.compress_pdf( @io_stream, @@ -189,6 +189,10 @@ def compress!(quality: 85, max_width: nil, max_height: nil, force_source_text: f # Checks whether the file has source text if it is a pdf. `false` otherwise # @return [bool] `true` if the file is a PDF and has source text. def source_text? + unless Mindee::Dependency.all_deps_available? + raise NotImplementedError, Mindee::Dependency::MINDEE_DEPENDENCIES_LOAD_ERROR + end + Mindee::PDF::PDFTools.source_text?(@io_stream) end end diff --git a/lib/mindee/input/sources/path_input_source.rb b/lib/mindee/input/sources/path_input_source.rb index 2902de7e9..da9b08c4e 100644 --- a/lib/mindee/input/sources/path_input_source.rb +++ b/lib/mindee/input/sources/path_input_source.rb @@ -11,7 +11,7 @@ class PathInputSource < LocalInputSource # @param filepath [String] # @param repair_pdf [bool] def initialize(filepath, repair_pdf: false) - io_stream = File.open(filepath, 'rb') + io_stream = File.new(filepath, 'rb') super(io_stream, File.basename(filepath), repair_pdf: repair_pdf) end end diff --git a/lib/mindee/input/sources/url_input_source.rb b/lib/mindee/input/sources/url_input_source.rb index e344fe5b1..3947c7233 100644 --- a/lib/mindee/input/sources/url_input_source.rb +++ b/lib/mindee/input/sources/url_input_source.rb @@ -14,7 +14,7 @@ class URLInputSource attr_reader :url def initialize(url) - raise Errors::MindeeInputError, 'URL must be HTTPS' unless url.start_with? 'https://' + raise Error::MindeeInputError, 'URL must be HTTPS' unless url.start_with? 'https://' logger.debug("URL input: #{url}") @@ -75,9 +75,9 @@ def fetch_file_content(username: nil, password: nil, token: nil, max_redirects: response = make_request(uri, request, max_redirects) if response.code.to_i > 299 - raise Errors::MindeeAPIError, "Failed to download file: HTTP status code #{response.code}" + raise Error::MindeeAPIError, "Failed to download file: HTTP status code #{response.code}" elsif response.code.to_i < 200 - raise Errors::MindeeAPIError, "Failed to download file: Invalid response code #{response.code}." + raise Error::MindeeAPIError, "Failed to download file: Invalid response code #{response.code}." end response.body @@ -103,7 +103,7 @@ def make_request(uri, request, max_redirects) response = http.request(request) if response.is_a?(Net::HTTPRedirection) && max_redirects.positive? location = response['location'] - raise Errors::MindeeInputError, 'No location in redirection header.' if location.nil? + raise Error::MindeeInputError, 'No location in redirection header.' if location.nil? new_uri = URI.parse(location) request = Net::HTTP::Get.new(new_uri) diff --git a/lib/mindee/logging/logger.rb b/lib/mindee/logging/logger.rb index ec60b5eb6..2bc2c62d3 100644 --- a/lib/mindee/logging/logger.rb +++ b/lib/mindee/logging/logger.rb @@ -5,8 +5,16 @@ module Mindee # Mindee logging module. module Logging - @logger = Logger.new($stdout) log_level = ENV.fetch('MINDEE_LOG_LEVEL', 'WARN') + log_output = ENV.fetch('MINDEE_LOG_OUTPUT', 'stderr') + @logger = if log_output == 'stderr' + Logger.new($stderr) + elsif log_output == 'stdout' + Logger.new($stdout) + else + warn "Invalid MINDEE_LOG_OUTPUT='#{log_output}', defaulting to 'stderr'" + Logger.new($stderr) + end @logger.level = Logger.const_get(log_level) class << self diff --git a/lib/mindee/page_options.rb b/lib/mindee/page_options.rb index ad8f93aec..58bc4cb6b 100644 --- a/lib/mindee/page_options.rb +++ b/lib/mindee/page_options.rb @@ -11,7 +11,7 @@ class PageOptions attr_accessor :page_indexes, :operation, :on_min_pages def initialize(params: {}) - params ||= {} + params ||= {} # : Hash[Symbol, untyped] params = params.transform_keys(&:to_sym) @page_indexes = params.fetch( :page_indexes, diff --git a/lib/mindee/parsing/common/api_request.rb b/lib/mindee/parsing/common/api_request.rb deleted file mode 100644 index 131d8cf4e..000000000 --- a/lib/mindee/parsing/common/api_request.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Common - # HTTP request response. - class ApiRequest - # @return [Hash] - attr_reader :error - # @return [Array] - attr_reader :resources - # @return [RequestStatus, Symbol] - attr_reader :status - # @return [Integer] - attr_reader :status_code - # @return [String] - attr_reader :url - - def initialize(server_response) - @error = server_response['error'] - @resources = server_response['resources'] - - @status = if server_response['status'] == 'failure' - RequestStatus::FAILURE - elsif server_response['status'] == 'success' - RequestStatus::SUCCESS - else - server_response['status']&.to_sym - end - @status_code = server_response['status_code'] - @url = server_response['url'] - end - end - end - end -end diff --git a/lib/mindee/parsing/common/api_response.rb b/lib/mindee/parsing/common/api_response.rb deleted file mode 100644 index 7e9f47349..000000000 --- a/lib/mindee/parsing/common/api_response.rb +++ /dev/null @@ -1,61 +0,0 @@ -# frozen_string_literal: true - -require_relative 'document' -require_relative '../../logging' - -module Mindee - module Parsing - module Common - # Potential values for queue in asynchronous calls. - module JobStatus - # Job is waiting. - WAITING = :waiting - # Job is processing. - PROCESSING = :processing - # Job is done. - COMPLETED = :completed - # Job failed. - FAILURE = :failed - end - - # Potential values for requests. - module RequestStatus - # Failed. - FAILURE = :failure - # Success. - SUCCESS = :success - end - - # Wrapper class for all predictions (synchronous and asynchronous) - class ApiResponse - # @return [Mindee::Parsing::Common::Document, nil] - attr_reader :document - # @return [Mindee::Parsing::Common::Job, nil] - attr_reader :job - # @return [Mindee::Parsing::Common::ApiRequest] - attr_reader :api_request - # @return [String] - attr_reader :raw_http - - # @param product_class [Mindee::Inference] - # @param http_response [Hash] - # @param raw_http [Hash] - def initialize(product_class, http_response, raw_http) - logger.debug('Handling API response') - @raw_http = raw_http.to_s - raise Errors::MindeeAPIError, 'Invalid response format.' unless http_response.key?('api_request') - - @api_request = Mindee::Parsing::Common::ApiRequest.new(http_response['api_request']) - - if http_response.key?('document') && - (!http_response.key?('job') || - http_response['job']['status'] == 'completed') && - @api_request.status == RequestStatus::SUCCESS - @document = Mindee::Parsing::Common::Document.new(product_class, http_response['document']) - end - @job = Mindee::Parsing::Common::Job.new(http_response['job']) if http_response.key?('job') - end - end - end - end -end diff --git a/lib/mindee/parsing/common/document.rb b/lib/mindee/parsing/common/document.rb deleted file mode 100644 index bf7bfd5a0..000000000 --- a/lib/mindee/parsing/common/document.rb +++ /dev/null @@ -1,84 +0,0 @@ -# frozen_string_literal: true - -require_relative 'inference' -require_relative 'extras' - -module Mindee - module Parsing - module Common - # Stores all response attributes. - class Document - # @return [Mindee::Inference] - attr_reader :inference - # @return [String] Filename sent to the API - attr_reader :name - # @return [String] Mindee ID of the document - attr_reader :id - # @return [Mindee::Parsing::Common::Extras::Extras] Potential Extras fields sent back along the prediction. - attr_reader :extras - # @return [Mindee::Parsing::Common::OCR::OCR, nil] OCR text results (limited availability) - attr_reader :ocr - # @return [Integer] Amount of pages of the document - attr_reader :n_pages - - # Loads the MVision OCR response. - # @param http_response [Hash] Full HTTP contents of the response. - # @return [Mindee::Parsing::Common::OCR::OCR] - def self.load_ocr(http_response) - ocr_prediction = http_response.fetch('ocr', nil) - return nil if ocr_prediction.nil? || ocr_prediction.fetch('mvision-v1', nil).nil? - - OCR::OCR.new(ocr_prediction) - end - - # Loads extras into the document prediction. - # @param http_response [Hash] Full HTTP contents of the response. - # @return [Mindee::Parsing::Common::OCR::OCR] - def self.extract_extras(http_response) - extras_prediction = http_response['inference'].fetch('extras', nil) - return nil if extras_prediction.nil? || extras_prediction.fetch('mvision-v1', nil).nil? - - Mindee::Parsing::Common::Extras::Extras.new(extras_prediction) - end - - # @param product_class [Mindee::Inference] - # @param http_response [Hash] - def initialize(product_class, http_response) - @id = http_response['id'] - @name = http_response['name'] - @inference = product_class.new(http_response['inference']) - @ocr = self.class.load_ocr(http_response) - @extras = self.class.extract_extras(http_response) - inject_full_text_ocr(http_response) - @n_pages = http_response['n_pages'] - end - - # @return [String] - def to_s - out_str = String.new - out_str << "########\nDocument\n########" - out_str << "\n:Mindee ID: #{@id}" - out_str << "\n:Filename: #{@name}" - out_str << "\n\n#{@inference}" - end - - private - - def inject_full_text_ocr(raw_prediction) - return unless raw_prediction.dig('inference', 'pages', 0, 'extras', 'full_text_ocr') - - full_text_ocr = String.new - raw_prediction.dig('inference', 'pages').each do |page| - full_text_ocr << page['extras']['full_text_ocr']['content'] - end - artificial_text_obj = { 'content' => full_text_ocr } - if @extras.nil? || @extras.empty? - @extras = Mindee::Parsing::Common::Extras::Extras.new({ 'full_text_ocr' => artificial_text_obj }) - else - @extras.add_artificial_extra({ 'full_text_ocr' => artificial_text_obj }) - end - end - end - end - end -end diff --git a/lib/mindee/parsing/common/execution.rb b/lib/mindee/parsing/common/execution.rb deleted file mode 100644 index f2175d4c8..000000000 --- a/lib/mindee/parsing/common/execution.rb +++ /dev/null @@ -1,75 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Common - # Identifier for the batch to which the execution belongs. - class Execution - # Identifier for the batch to which the execution belongs. - # @return [String] - attr_reader :batch_name - # The time at which the execution started. - # @return [Time, nil] - attr_reader :created_at - # File representation within a workflow execution. - # @return [ExecutionFile] - attr_reader :file - # Identifier for the execution. - # @return [String] - attr_reader :id - # Deserialized inference object. - # @return [Mindee::Inference] - attr_reader :inference - # Priority of the execution. - # @return [ExecutionPriority, Symbol, nil] - attr_reader :priority - # The time at which the file was tagged as reviewed. - # @return [Time, nil] - attr_reader :reviewed_at - # The time at which the file was uploaded to a workflow. - # @return [Time, nil] - attr_reader :available_at - # Reviewed fields and values. - # @return [Mindee::Product::Universal::UniversalDocument] - attr_reader :reviewed_prediction - # Execution Status. - # @return [String] - attr_reader :status - # Execution type. - # @return [String] - attr_reader :type - # The time at which the file was uploaded to a workflow. - # @return [Time, nil] - attr_reader :uploaded_at - # Identifier for the workflow. - # @return [String] - attr_reader :workflow_id - - # rubocop:disable Metrics/CyclomaticComplexity - - # @param product_class [Mindee::Inference] - # @param http_response [Hash] - def initialize(product_class, http_response) - @batch_name = http_response['batch_name'] - @created_at = Time.iso8601(http_response['created_at']) if http_response['created_at'] - @file = ExecutionFile.new(http_response['file']) if http_response['file'] - @id = http_response['id'] - @inference = product_class.new(http_response['inference']) if http_response['inference'] - @priority = Mindee::Parsing::Common::ExecutionPriority.to_priority(http_response['priority']) - @reviewed_at = Time.iso8601(http_response['reviewed_at']) if http_response['reviewed_at'] - @available_at = Time.iso8601(http_response['available_at']) if http_response['available_at'] - if http_response['reviewed_prediction'] - @reviewed_prediction = Mindee::Product::Universal::UniversalDocument.new( - http_response['reviewed_prediction'] - ) - end - @status = http_response['status'] - @type = http_response['type'] - @uploaded_at = Time.iso8601(http_response['uploaded_at']) if http_response['uploaded_at'] - @workflow_id = http_response['workflow_id'] - end - # rubocop:enable Metrics/CyclomaticComplexity - end - end - end -end diff --git a/lib/mindee/parsing/common/execution_file.rb b/lib/mindee/parsing/common/execution_file.rb deleted file mode 100644 index 582538ee4..000000000 --- a/lib/mindee/parsing/common/execution_file.rb +++ /dev/null @@ -1,24 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Common - # Representation of a workflow execution's file data. - class ExecutionFile - # File name. - # @return [String] - attr_reader :name - - # Optional alias for the file. - # @return [String] - attr_reader :alias - - # @param http_response [Hash] - def initialize(http_response) - @name = http_response['name'] - @alias = http_response['alias'] - end - end - end - end -end diff --git a/lib/mindee/parsing/common/execution_priority.rb b/lib/mindee/parsing/common/execution_priority.rb deleted file mode 100644 index 5d3876f8d..000000000 --- a/lib/mindee/parsing/common/execution_priority.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Common - # Execution policy priority values. - module ExecutionPriority - # Low priority execution. - # @return [Symbol] :low - LOW = :low - # Medium priority execution. - # @return [Symbol] :low - MEDIUM = :medium - # High priority execution. - # @return [Symbol] :low - HIGH = :high - - # Sets the priority to one of its possibly values, defaults to nil otherwise. - # @param [String, nil] priority_str - # @return [Symbol, nil] - def self.to_priority(priority_str) - return nil if priority_str.nil? - - case priority_str.downcase - when 'low' - :low - when 'high' - :high - else - :medium - end - end - end - end - end -end diff --git a/lib/mindee/parsing/common/extras/cropper_extra.rb b/lib/mindee/parsing/common/extras/cropper_extra.rb deleted file mode 100644 index 1e5c4976a..000000000 --- a/lib/mindee/parsing/common/extras/cropper_extra.rb +++ /dev/null @@ -1,30 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../standard/position_field' - -module Mindee - module Parsing - module Common - module Extras - # Contains information on the cropping of a prediction. - class CropperExtra - # Cropper extra initialization. - # @return [Array] - attr_reader :croppings - - def initialize(raw_prediction, page_id = nil) - @croppings = [] # : Array[Mindee::Parsing::Standard::PositionField] - raw_prediction['cropping']&.each do |crop| - @croppings.push(Mindee::Parsing::Standard::PositionField.new(crop, page_id)) - end - end - - # @return [String] - def to_s - @croppings.map(&:to_s).join("\n ") - end - end - end - end - end -end diff --git a/lib/mindee/parsing/common/extras/extras.rb b/lib/mindee/parsing/common/extras/extras.rb deleted file mode 100644 index d593b9821..000000000 --- a/lib/mindee/parsing/common/extras/extras.rb +++ /dev/null @@ -1,58 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../standard/position_field' - -module Mindee - module Parsing - module Common - # Extras namespace. - module Extras - # Extra information added to the prediction. - class Extras - # @return [CropperExtra, nil] - attr_reader :cropper - # @return [Mindee::Parsing::Common::Extras::FullTextOCRExtra] - attr_reader :full_text_ocr - # @return [RAGExtra, nil] - attr_reader :rag - - def initialize(raw_prediction) - if raw_prediction['cropper'] - @cropper = Mindee::Parsing::Common::Extras::CropperExtra.new(raw_prediction['cropper']) - end - if raw_prediction['full_text_ocr'] - @full_text_ocr = Mindee::Parsing::Common::Extras::FullTextOCRExtra.new(raw_prediction['full_text_ocr']) - end - @rag = Mindee::Parsing::Common::Extras::RAGExtra.new(raw_prediction['rag']) if raw_prediction['rag'] - - raw_prediction.each do |key, value| - instance_variable_set("@#{key}", value) unless ['cropper', 'full_text_ocr', 'rag'].include?(key.to_s) - end - end - - # @return [String] - def to_s - out_str = String.new - instance_variables.each do |var| - out_str << "#{var}: #{instance_variable_get(var)}" - end - out_str - end - - # Adds artificial extra data for reconstructed extras. Currently only used for full_text_ocr. - # - # @param [Hash] raw_prediction Raw prediction used by the document. - def add_artificial_extra(raw_prediction) - return unless raw_prediction['full_text_ocr'] - - @full_text_ocr << Mindee::Parsing::Common::Extras::FullTextOCRExtra.new(raw_prediction) - end - end - - def empty? - instance_variables.all? { |var| instance_variable_get(var).nil? } - end - end - end - end -end diff --git a/lib/mindee/parsing/common/extras/full_text_ocr_extra.rb b/lib/mindee/parsing/common/extras/full_text_ocr_extra.rb deleted file mode 100644 index 55fe243d7..000000000 --- a/lib/mindee/parsing/common/extras/full_text_ocr_extra.rb +++ /dev/null @@ -1,33 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../standard/position_field' - -module Mindee - module Parsing - module Common - module Extras - # Full Text OCR result. - class FullTextOCRExtra - # Contents of the full text OCR result. - # @return [String, nil] - attr_reader :contents - # Language used on the page. - # @return [String, nil] - attr_reader :language - - def initialize(raw_prediction) - @contents = raw_prediction['content'] if raw_prediction['content'] - return unless raw_prediction['language'] - - @language = raw_prediction['language'] - end - - # @return [String] - def to_s - @contents || '' - end - end - end - end - end -end diff --git a/lib/mindee/parsing/common/extras/rag_extra.rb b/lib/mindee/parsing/common/extras/rag_extra.rb deleted file mode 100644 index 55c016b36..000000000 --- a/lib/mindee/parsing/common/extras/rag_extra.rb +++ /dev/null @@ -1,26 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Common - module Extras - # Retrieval-Augmented Generation extra. - class RAGExtra - # ID of the matching document - # @return [String, nil] - attr_reader :matching_document_id - - def initialize(raw_prediction) - @matching_document_id = raw_prediction['matching_document_id'] if raw_prediction['matching_document_id'] - end - - # String representation. - # @return [String] - def to_s - @matching_document_id || '' - end - end - end - end - end -end diff --git a/lib/mindee/parsing/common/inference.rb b/lib/mindee/parsing/common/inference.rb deleted file mode 100644 index a248ba30e..000000000 --- a/lib/mindee/parsing/common/inference.rb +++ /dev/null @@ -1,67 +0,0 @@ -# frozen_string_literal: true - -require_relative 'product' - -module Mindee - module Parsing - # Common fields used for most documents. - module Common - # Abstract class for prediction Inferences - # Holds prediction for a page or entire document. - class Inference - # @return [bool] - attr_reader :is_rotation_applied - # @return [Array] - attr_reader :pages - # @return [Mindee::Parsing::Common::Prediction] - attr_reader :prediction - # @return [Mindee::Parsing::Common::Product] - attr_reader :product - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - # @return [Mindee::Parsing::Common::Extras::Extras] Potential Extras fields sent back along the prediction. - attr_reader :extras - - @endpoint_name = nil - @endpoint_version = nil - @has_async = false - @has_sync = false - - # @param raw_prediction [Hash] - def initialize(raw_prediction) - @is_rotation_applied = raw_prediction['is_rotation_applied'] - @product = Product.new(raw_prediction['product']) - @pages = [] # : Array[Page] - @extras = Extras::Extras.new(raw_prediction['extras']) if raw_prediction.include?('extras') - end - - # @return [String] - def to_s - is_rotation_applied = @is_rotation_applied ? 'Yes' : 'No' - out_str = String.new - out_str << "Inference\n#########" - out_str << "\n:Product: #{@product.name} v#{@product.version}" - out_str << "\n:Rotation applied: #{is_rotation_applied}" - out_str << "\n\nPrediction\n==========" - out_str << "\n#{"#{@prediction}\n" if @prediction.to_s.size.positive?}" - if @pages.any? { |page| !page.prediction.nil? } - out_str << "\nPage Predictions\n================\n\n" - out_str << @pages.map(&:to_s).join("\n\n") - end - out_str.rstrip! - out_str - end - end - end - end -end diff --git a/lib/mindee/parsing/common/job.rb b/lib/mindee/parsing/common/job.rb deleted file mode 100644 index a48dad19e..000000000 --- a/lib/mindee/parsing/common/job.rb +++ /dev/null @@ -1,46 +0,0 @@ -# frozen_string_literal: true - -require 'time' - -module Mindee - module Parsing - module Common - # Job (queue) information on async parsing. - class Job - # @return [String] Mindee ID of the document - attr_reader :id - # @return [Time] - attr_reader :issued_at - # @return [Time, nil] - attr_reader :available_at - # @return [JobStatus, Symbol] - attr_reader :status - # @return [Integer, nil] - attr_reader :millisecs_taken - # @return [Hash, nil] - attr_reader :error - - # @param http_response [Hash] - def initialize(http_response) - @id = http_response['id'] - @error = http_response['error'] - @issued_at = Time.iso8601(http_response['issued_at']) - if http_response.key?('available_at') && !http_response['available_at'].nil? - @available_at = Time.iso8601(http_response['available_at']) - @millisecs_taken = (1000 * (@available_at.to_time - @issued_at.to_time).to_f).to_i - end - @status = case http_response['status'] - when 'waiting' - JobStatus::WAITING - when 'processing' - JobStatus::PROCESSING - when 'completed' - JobStatus::COMPLETED - else - http_response['status']&.to_sym - end - end - end - end - end -end diff --git a/lib/mindee/parsing/common/ocr/mvision_v1.rb b/lib/mindee/parsing/common/ocr/mvision_v1.rb deleted file mode 100644 index 69f05e2b8..000000000 --- a/lib/mindee/parsing/common/ocr/mvision_v1.rb +++ /dev/null @@ -1,50 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Common - module OCR - # Mindee Vision V1. - class MVisionV1 - # List of pages. - # @return [Array] - attr_reader :pages - - # @param prediction [Hash] - def initialize(prediction) - @pages = [] # : Array[Mindee::Parsing::Common::OCR::OCRPage] - prediction['pages'].each do |page_prediction| - @pages.push(OCRPage.new(page_prediction)) - end - end - - # @return [String] - def to_s - out_str = String.new - @pages.map do |page| - out_str << "\n" - out_str << page.to_s - end - out_str.strip - end - - # Constructs a line from a column, located underneath given coordinates - # @param coordinates [Array] Polygon or bounding box where the reconstruction should - # start. - # @param page_id [Integer] ID of the page to start at - # @param x_margin [Float] Margin of misalignment for the x coordinate. - # @return [Mindee::Parsing::Common::OCR::OCRLine] - def reconstruct_vertically(coordinates, page_id, x_margin) - line_arr = OCRLine.new([]) - @pages[page_id].all_lines.each do |line| - line.each do |word| - line_arr.push(word) if Geometry.below?(word.polygon, coordinates, x_margin / 2, x_margin * 2) - end - end - line_arr - end - end - end - end - end -end diff --git a/lib/mindee/parsing/common/ocr/ocr.rb b/lib/mindee/parsing/common/ocr/ocr.rb deleted file mode 100644 index b7c898908..000000000 --- a/lib/mindee/parsing/common/ocr/ocr.rb +++ /dev/null @@ -1,178 +0,0 @@ -# frozen_string_literal: true - -require_relative 'mvision_v1' - -module Mindee - module Parsing - module Common - # Ocr-specific parsing fields and options - module OCR - # A single word. - class OCRWord - # The confidence score, value will be between 0.0 and 1.0 - # @return [Float] - attr_reader :confidence - # @return [String] - attr_reader :text - # @return [Mindee::Geometry::Quadrilateral] - attr_reader :bounding_box - # @return [Mindee::Geometry::Polygon] - attr_reader :polygon - - # @param prediction [Hash] - def initialize(prediction) - @text = prediction['text'] - @confidence = prediction['confidence'] - @polygon = Mindee::Geometry::Polygon.new(prediction['polygon']) - @bounding_box = Geometry.get_bounding_box(@polygon) unless @polygon.nil? || @polygon.empty? - end - - # @return [String] - def to_s - @text.to_s - end - end - - # A list of words which are on the same line. - class OCRLine < Array - # @param prediction [Hash, nil] - # @param from_array [Array, nil] - def initialize(prediction = nil, from_array = nil) - if !prediction.nil? - super(prediction.map { |word_prediction| OCRWord.new(word_prediction) }) - elsif !from_array.nil? - super(from_array) - end - end - - # Sort the words on the line from left to right. - # @return [OCRLine] - def sort_on_x - from_array = sort_by { |word| Geometry.get_min_max_x(word.polygon).min } - OCRLine.new(nil, from_array) - end - - # @return [String] - def to_s - each(&:to_s).join(' ') - end - end - - # OCR extraction for a single page. - class OCRPage - # All the words on the page, in semi-random order. - # @return [Array] - attr_reader :all_words - # @return [Array] - attr_reader :lines - - # @param prediction [Hash] - def initialize(prediction) - @lines = [] # : Array[Mindee::Parsing::Common::OCR::OCRLine] - @all_words = [] # : Array[Mindee::Parsing::Common::OCR::OCRWord] - prediction['all_words'].each do |word_prediction| - @all_words.push(OCRWord.new(word_prediction)) - end - end - - # All the words on the page, ordered in lines. - # @return [Array] - def all_lines - @lines = to_lines if @lines.empty? - @lines - end - - # @return [String] - def to_s - lines = all_lines - return '' if lines.empty? - - out_str = String.new - lines.map do |line| - out_str << "#{line}\n" unless line.to_s.strip.empty? - end - out_str.strip - end - - private - - # Helper function that iterates through all the words and compares them to a candidate - # @param sorted_words [Array] - # @param current [OCRWord] - # @param indexes [Array] - # @param lines [Array] - def parse_one(sorted_words, current, indexes, lines) - line = OCRLine.new(nil, []) - sorted_words.each_with_index do |word, idx| - next if indexes.include?(idx) - - if current.nil? - current = word - indexes.push(idx) - line = OCRLine.new([]) - line.push(word) - elsif words_on_same_line?(current, word) - line.push(word) - indexes.push(idx) - end - end - lines.push(line.sort_on_x) if line.any? - end - - # Order all the words on the page into lines. - # @return [Array] - def to_lines - current = nil - indexes = [] # : Array[Integer] - lines = [] # : Array[Mindee::Parsing::Common::OCR::OCRLine] - - # make sure words are sorted from top to bottom - all_words = @all_words.sort_by { |word| Geometry.get_min_max_y(word.polygon).min } - all_words.each do - parse_one(all_words, current, indexes, lines) - current = nil - end - lines - end - - # Determine if two words are on the same line. - # @param current_word [Mindee::Parsing::Common::OCR::OCRWord] - # @param next_word [Mindee::Parsing::Common::OCR::OCRWord] - # @return [bool] - def words_on_same_line?(current_word, next_word) - current_in_next = current_word.polygon.point_in_y?(next_word.polygon.centroid) - next_in_current = next_word.polygon.point_in_y?(current_word.polygon.centroid) unless current_word.nil? - current_in_next || next_in_current - end - end - - # OCR extraction from the entire document. - class OCR - # Mindee Vision v1 results. - # @return [Mindee::Parsing::Common::OCR::MVisionV1] - attr_reader :mvision_v1 - - # @param prediction [Hash] - def initialize(prediction) - @mvision_v1 = Mindee::Parsing::Common::OCR::MVisionV1.new(prediction['mvision-v1']) - end - - # @return [String] - def to_s - @mvision_v1.to_s - end - - # Constructs a line from a column, located underneath given coordinates - # @param coordinates [Array] Polygon or bounding box where the reconstruction should - # start - # @param page_id [Integer] ID of the page to start at - # @param x_margin [Float] Margin of misalignment for the x coordinate (default 10%) - # @return [Mindee::Parsing::Common::OCR::OCRLine] - def reconstruct_vertically(coordinates, page_id, x_margin = 0.05) - @mvision_v1.reconstruct_vertically(coordinates, page_id, x_margin) - end - end - end - end - end -end diff --git a/lib/mindee/parsing/common/orientation.rb b/lib/mindee/parsing/common/orientation.rb deleted file mode 100644 index 9d4876a81..000000000 --- a/lib/mindee/parsing/common/orientation.rb +++ /dev/null @@ -1,26 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Common - # Page orientation - class Orientation - # @return [Integer, nil] - attr_reader :page_id - # A prediction among these 3 possible outputs: - # * 0 degrees: the page is already upright - # * 90 degrees: the page must be rotated clockwise to be upright - # * 270 degrees: the page must be rotated counterclockwise to be upright - # @return [Integer, nil] - attr_reader :value - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - @value = prediction['value'] - @page_id = page_id - end - end - end - end -end diff --git a/lib/mindee/parsing/common/page.rb b/lib/mindee/parsing/common/page.rb deleted file mode 100644 index a3fc2ae72..000000000 --- a/lib/mindee/parsing/common/page.rb +++ /dev/null @@ -1,47 +0,0 @@ -# frozen_string_literal: true - -require_relative 'product' -require_relative 'extras' - -module Mindee - module Parsing - # Common fields used for most documents. - module Common - # Abstract wrapper class for prediction Pages - # Holds prediction for a page as well as it's orientation and id. - class Page - # ID of the page (as given by the API). - # @return [Integer] - attr_reader :page_id - # Orientation of the page. - # @return [Mindee::Parsing::Common::Orientation] - attr_reader :orientation - # Page prediction - # @return [Mindee::Parsing::Common::Prediction] - attr_reader :prediction - # Additional page-level information. - # @return [Mindee::Parsing::Common::Extras::Extras] - attr_reader :extras - - # @param raw_prediction [Hash] - def initialize(raw_prediction) - @page_id = raw_prediction['id'] - @orientation = Mindee::Parsing::Common::Orientation.new(raw_prediction['orientation'], @page_id) - return if raw_prediction['extras'].nil? - - @extras = Mindee::Parsing::Common::Extras::Extras.new(raw_prediction['extras']) - end - - # @return [String] - def to_s - out_str = String.new - title = "Page #{@page_id}" - out_str << "#{title}\n" - out_str << ('-' * title.size) - out_str << @prediction.to_s - out_str - end - end - end - end -end diff --git a/lib/mindee/parsing/common/prediction.rb b/lib/mindee/parsing/common/prediction.rb deleted file mode 100644 index 3f455ebd4..000000000 --- a/lib/mindee/parsing/common/prediction.rb +++ /dev/null @@ -1,17 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Common - # Abstract class for all predictions - class Prediction - # @return [String] - def to_s - '' - end - - def initialize(_ = nil, _ = nil); end - end - end - end -end diff --git a/lib/mindee/parsing/common/product.rb b/lib/mindee/parsing/common/product.rb deleted file mode 100644 index e3f4bcd4e..000000000 --- a/lib/mindee/parsing/common/product.rb +++ /dev/null @@ -1,24 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Common - # Product information - class Product - # @return [String] Name of the product. - attr_reader :name - # @return [String?] Type of product. - attr_reader :type - # @return [String] Product version. - attr_reader :version - - # @param prediction [Hash] - def initialize(prediction) - @name = prediction['name'] - @type = prediction['type'] - @version = prediction['version'] - end - end - end - end -end diff --git a/lib/mindee/parsing/common/workflow_response.rb b/lib/mindee/parsing/common/workflow_response.rb deleted file mode 100644 index 5becd8949..000000000 --- a/lib/mindee/parsing/common/workflow_response.rb +++ /dev/null @@ -1,28 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Common - # Represents the server response after a document is sent to a workflow. - class WorkflowResponse - # Set the prediction model used to parse the document. - # The response object will be instantiated based on this parameter. - # @return [Mindee::Parsing::Common::Execution] - attr_reader :execution - # @return [Mindee::Parsing::Common::ApiRequest] - attr_reader :api_request - # @return [String] - attr_reader :raw_http - - # @param http_response [Hash] - # @param product_class [Mindee::Inference] - def initialize(product_class, http_response, raw_http) - @raw_http = raw_http.to_s - @api_request = Mindee::Parsing::Common::ApiRequest.new(http_response['api_request']) - product_class ||= Mindee::Product::Universal::Universal - @execution = Mindee::Parsing::Common::Execution.new(product_class, http_response['execution']) - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/abstract_field.rb b/lib/mindee/parsing/standard/abstract_field.rb deleted file mode 100644 index 65f2c62be..000000000 --- a/lib/mindee/parsing/standard/abstract_field.rb +++ /dev/null @@ -1,72 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../geometry' - -module Mindee - module Parsing - module Standard - # Base BaseField object, upon which fields and feature fields are built - class AbstractField - # @return [Mindee::Geometry::Quadrilateral, nil] - attr_reader :bounding_box - # @return [Mindee::Geometry::Polygon, nil] - attr_reader :polygon - # @return [Integer, nil] - attr_reader :page_id - # The confidence score, value will be between 0.0 and 1.0 - # @return [Float, nil] - attr_accessor :confidence - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - @confidence = prediction['confidence'] if prediction.key?('confidence') - @polygon = Mindee::Geometry::Polygon.new(prediction['polygon']) if prediction.key?('polygon') - @bounding_box = Geometry.get_bounding_box(@polygon) unless @polygon.nil? || @polygon.empty? - @page_id = page_id || prediction['page_id'] - end - - # @return [String] - def to_s - @value ? @value.to_s : '' - end - - # Multiply all the Mindee::Parsing::Standard::BaseField confidences in the array. - # @return [Float] - def self.array_confidence(field_array) - product = 1 - field_array.each do |field| - return 0.0 if field.confidence.nil? - - product *= field.confidence - end - product.to_f - end - - # Add all the Mindee::Parsing::Standard::BaseField values in the array. - # @return [Float] - def self.array_sum(field_array) - arr_sum = 0 - field_array.each do |field| - return 0.0 if field.value.nil? - - arr_sum += field.value - end - arr_sum.to_f - end - - # @param value [Float] - # @param min_precision [Integer] - # @return [String] - def self.float_to_string(value, min_precision = 2) - return String.new if value.nil? - - precision = value.to_f.to_s.split('.')[1].size - precision = [precision, min_precision].max - format_string = "%.#{precision}f" - format(format_string, value) - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/address_field.rb b/lib/mindee/parsing/standard/address_field.rb deleted file mode 100644 index c33f90e39..000000000 --- a/lib/mindee/parsing/standard/address_field.rb +++ /dev/null @@ -1,49 +0,0 @@ -# frozen_string_literal: true - -require_relative 'string_field' - -module Mindee - module Parsing - module Standard - # Represents physical-address information. - class AddressField < Mindee::Parsing::Standard::StringField - # Street number - # @return [String, nil] - attr_reader :street_number - # Street name - # @return [String, nil] - attr_reader :street_name - # PO Box number - # @return [String, nil] - attr_reader :po_box - # Address complement - # @return [String, nil] - attr_reader :address_complement - # City name. - # @return [String, nil] - attr_reader :city - # Postal or ZIP code. - # @return [String, nil] - attr_reader :postal_code - # State, province or region. - # @return [String, nil] - attr_reader :state - # Country. - # @return [String, nil] - attr_reader :country - - def initialize(prediction, page_id = nil, reconstructed: false) - super - @street_number = prediction['street_number'] - @street_name = prediction['street_name'] - @po_box = prediction['po_box'] - @address_complement = prediction['address_complement'] - @city = prediction['city'] - @postal_code = prediction['postal_code'] - @state = prediction['state'] - @country = prediction['country'] - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/amount_field.rb b/lib/mindee/parsing/standard/amount_field.rb deleted file mode 100644 index 465a97d49..000000000 --- a/lib/mindee/parsing/standard/amount_field.rb +++ /dev/null @@ -1,26 +0,0 @@ -# frozen_string_literal: true - -require_relative 'base_field' - -module Mindee - module Parsing - module Standard - # Represents tax information. - class AmountField < BaseField - # Amount value as 3 decimal float - # @return [Float, nil] - attr_reader :value - - def initialize(prediction, page_id, reconstructed: false) - super - @value = @value.to_f.round(3).to_f unless @value.to_s.empty? - end - - # @return [String] - def to_s - @value.nil? ? '' : BaseField.float_to_string(@value.to_f) - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/base_field.rb b/lib/mindee/parsing/standard/base_field.rb deleted file mode 100644 index caf01aa65..000000000 --- a/lib/mindee/parsing/standard/base_field.rb +++ /dev/null @@ -1,28 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../geometry' -require_relative 'abstract_field' - -module Mindee - module Parsing - module Standard - # Base field object. - class BaseField < Mindee::Parsing::Standard::AbstractField - # @return [String, Float, Integer, bool] - attr_reader :value - # true if the field was reconstructed or computed using other fields. - # @return [bool] - attr_reader :reconstructed - - # @param prediction [Hash] - # @param page_id [Integer, nil] - # @param reconstructed [bool] - def initialize(prediction, page_id, reconstructed: false) - super(prediction, page_id) - @value = prediction['value'] - @reconstructed = reconstructed - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/boolean_field.rb b/lib/mindee/parsing/standard/boolean_field.rb deleted file mode 100644 index 28e368e28..000000000 --- a/lib/mindee/parsing/standard/boolean_field.rb +++ /dev/null @@ -1,27 +0,0 @@ -# frozen_string_literal: true - -require_relative 'base_field' - -module Mindee - module Parsing - module Standard - # Represents basic text information. - class BooleanField < BaseField - # Value as bool - # @return [bool, nil] - attr_reader :value - - def initialize(prediction, page_id = nil, reconstructed: false) - super - end - - # @return [String] - def to_s - return '' if value.nil? - - value ? 'True' : 'False' - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/classification_field.rb b/lib/mindee/parsing/standard/classification_field.rb deleted file mode 100644 index 5cacac821..000000000 --- a/lib/mindee/parsing/standard/classification_field.rb +++ /dev/null @@ -1,16 +0,0 @@ -# frozen_string_literal: true - -require_relative 'base_field' - -module Mindee - module Parsing - module Standard - # Represents a classifier value. - class ClassificationField < BaseField - # Value as String - # @return [String] - attr_reader :value - end - end - end -end diff --git a/lib/mindee/parsing/standard/company_registration_field.rb b/lib/mindee/parsing/standard/company_registration_field.rb deleted file mode 100644 index e08983de3..000000000 --- a/lib/mindee/parsing/standard/company_registration_field.rb +++ /dev/null @@ -1,43 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Standard - # Company registration number or code, and its type. - class CompanyRegistrationField < BaseField - # @return [String] - attr_reader :type - - # @param prediction [Hash] - # @param page_id [Integer, nil] - # @param reconstructed [bool] - def initialize(prediction, page_id, reconstructed: false) - super - @type = prediction['type'] - end - - # Table line representation of the values. - # @return [String] The formatted table line, as a string. - def to_table_line - printable = printable_values - format('| %-15s | %-20s ', type: printable['type'], value: printable['value']) - end - - # @return [String] - def to_s - printable = printable_values - format('Type: %s, Value: %s', type: printable['type'], value: printable['value']) - end - - # Hashed representation of the values. - # @return [Hash] Hash of the values. - def printable_values - printable = {} - printable['type'] = type - printable['value'] = value - printable - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/date_field.rb b/lib/mindee/parsing/standard/date_field.rb deleted file mode 100644 index 73e0a5c7c..000000000 --- a/lib/mindee/parsing/standard/date_field.rb +++ /dev/null @@ -1,38 +0,0 @@ -# frozen_string_literal: true - -require 'date' - -require_relative 'base_field' - -module Mindee - module Parsing - module Standard - # Represents a date. - class DateField < BaseField - # The date as a standard Ruby `Date` object. - # @return [Date, nil] - attr_reader :date_object - # The ISO 8601 representation of the date, regardless of the `raw` contents. - # @return [String, nil] - attr_reader :value - # The textual representation of the date as found on the document. - # @return [String, nil] - attr_reader :raw - # Whether the field was computed or retrieved directly from the document. - # @return [bool, nil] - attr_reader :is_computed - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @is_computed = prediction['is_computed'] - return unless @value - - @date_object = Date.parse(@value) - @raw = prediction['raw'] - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/feature_field.rb b/lib/mindee/parsing/standard/feature_field.rb deleted file mode 100644 index ecd658fcd..000000000 --- a/lib/mindee/parsing/standard/feature_field.rb +++ /dev/null @@ -1,24 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Standard - # Feature field object wrapper for specialized methods. - class FeatureField < AbstractField - # Format strings for display by shortening long strings and assigning empty ones. - # @param in_str [String, bool, nil] - # @param max_col_size [int, nil] - # @return [String] - def format_for_display(in_str, max_col_size = nil) - return 'True' if in_str == true - return 'False' if in_str == false - return '' if in_str.nil? - return in_str.to_s if max_col_size.nil? - - in_str = in_str.to_s.gsub(%r{[\n\r\t]}, "\n" => '\\n', "\r" => '\\r', "\t" => '\\t') - in_str.to_s.length <= max_col_size.to_i ? in_str.to_s : "#{in_str[0..(max_col_size.to_i - 4)]}..." - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/locale_field.rb b/lib/mindee/parsing/standard/locale_field.rb deleted file mode 100644 index 59836e2f2..000000000 --- a/lib/mindee/parsing/standard/locale_field.rb +++ /dev/null @@ -1,50 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Standard - # Represents locale information - class LocaleField - # The confidence score, value will be between 0.0 and 1.0 - # @return [Float] - attr_reader :confidence - # Language code in ISO 639-1 format. - # @return [String] - attr_reader :language - # Country code in ISO 3166-1 alpha-2 format. - # @return [String, nil] - attr_reader :country - # Currency code in ISO 4217 format. - # @return [String] - attr_reader :currency - # Language code, with country code when available. - # @return [String] - attr_reader :value - - # @param prediction [Hash] - def initialize(prediction, _page_id = nil) - value_key = if !prediction.include?('value') || prediction['value'].nil? - 'language' - else - 'value' - end - @confidence = prediction['confidence'] - @value = prediction[value_key] - @language = prediction['language'] - @country = prediction['country'] - @currency = prediction['currency'] - end - - # @return [String] - def to_s - out_str = String.new - out_str << "#{@value}; " unless @value.nil? - out_str << "#{@language}; " if @language - out_str << "#{@country}; " if @country - out_str << "#{@currency}; " if @currency - out_str.strip - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/payment_details_field.rb b/lib/mindee/parsing/standard/payment_details_field.rb deleted file mode 100644 index 772e50a4c..000000000 --- a/lib/mindee/parsing/standard/payment_details_field.rb +++ /dev/null @@ -1,42 +0,0 @@ -# frozen_string_literal: true - -require_relative 'base_field' - -module Mindee - module Parsing - module Standard - # Represents payment details for invoices and receipts - class PaymentDetailsField < BaseField - # @return [String, nil] - attr_reader :account_number - # @return [String, nil] - attr_reader :iban - # @return [String, nil] - attr_reader :routing_number - # @return [String, nil] - attr_reader :swift - - # @param prediction [Hash] - # @param page_id [Integer, nil] - # @param reconstructed [bool] - def initialize(prediction, page_id, reconstructed: false) - super - @account_number = prediction['account_number'] - @iban = prediction['iban'] - @routing_number = prediction['routing_number'] - @swift = prediction['swift'] - end - - # @return [String] - def to_s - out_str = String.new - out_str << "#{@account_number}; " if @account_number - out_str << "#{@iban}; " if @iban - out_str << "#{@routing_number}; " if @routing_number - out_str << "#{@swift}; " if @swift - out_str.strip - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/position_field.rb b/lib/mindee/parsing/standard/position_field.rb deleted file mode 100644 index c0e2c3b63..000000000 --- a/lib/mindee/parsing/standard/position_field.rb +++ /dev/null @@ -1,59 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Parsing - module Standard - # An element's position on the image - class PositionField - # @return [Mindee::Geometry::Polygon] - attr_reader :polygon - # @return [Mindee::Geometry::Polygon] - attr_reader :value - # @return [Mindee::Geometry::Quadrilateral] - attr_reader :quadrangle - # @return [Mindee::Geometry::Quadrilateral] - attr_reader :rectangle - # @return [Mindee::Geometry::Quadrilateral] - attr_reader :bounding_box - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - unless prediction['polygon'].nil? || prediction['polygon'].empty? - @polygon = Mindee::Geometry::Polygon.new(prediction['polygon']) - end - @quadrangle = to_quadrilateral(prediction, 'quadrangle') - @rectangle = to_quadrilateral(prediction, 'rectangle') - @bounding_box = to_quadrilateral(prediction, 'bounding_box') - @page_id = page_id || prediction['page_id'] - @value = @polygon - end - - # rubocop:disable Metrics/CyclomaticComplexity - # rubocop:disable Metrics/PerceivedComplexity - - # String representation. - # @return [String] - def to_s - return "Polygon with #{@polygon.size} points." if @polygon&.size&.positive? - return "Polygon with #{@bounding_box.size} points." if @bounding_box&.size&.positive? - return "Polygon with #{@rectangle.size} points." if @rectangle&.size&.positive? - return "Polygon with #{@quadrangle.size} points." if @quadrangle&.size&.positive? - - '' - end - - # rubocop:enable Metrics/CyclomaticComplexity - # rubocop:enable Metrics/PerceivedComplexity - - private - - def to_quadrilateral(prediction, key) - return if prediction[key].nil? || prediction[key].empty? - - Mindee::Geometry.quadrilateral_from_prediction(prediction[key]) - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/string_field.rb b/lib/mindee/parsing/standard/string_field.rb deleted file mode 100644 index af575ba03..000000000 --- a/lib/mindee/parsing/standard/string_field.rb +++ /dev/null @@ -1,24 +0,0 @@ -# frozen_string_literal: true - -require_relative 'base_field' - -module Mindee - module Parsing - module Standard - # Represents basic text information. - class StringField < Mindee::Parsing::Standard::BaseField - # Value as String - # @return [String, nil] - attr_reader :value - # Value as String - # @return [String, nil] - attr_reader :raw_value - - def initialize(prediction, page_id = nil, reconstructed: false) - super - @raw_value = prediction['raw_value'] - end - end - end - end -end diff --git a/lib/mindee/parsing/standard/tax_field.rb b/lib/mindee/parsing/standard/tax_field.rb deleted file mode 100644 index 045e180fb..000000000 --- a/lib/mindee/parsing/standard/tax_field.rb +++ /dev/null @@ -1,108 +0,0 @@ -# frozen_string_literal: true - -require_relative 'base_field' - -module Mindee - module Parsing - module Standard - # Represents tax information. - class TaxField < BaseField - # Tax value as 3 decimal float - # @return [Float, nil] - attr_reader :value - # Tax rate percentage - # @return [Float] - attr_reader :rate - # Tax code - # @return [String] - attr_reader :code - # Tax base - # @return [Float] - attr_reader :base - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @value = prediction['value']&.round(3) - @rate = prediction['rate'].to_f unless prediction['rate'].nil? - @base = prediction['base'].to_f unless prediction['base'].nil? - @code = prediction['code'] unless prediction['code'] == 'None' - end - - # @param value [Float] - def print_float(value) - format('%.2f', value) - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "Base: #{printable[:base]}" - out_str << ", Code: #{printable[:code]}" - out_str << ", Rate (%): #{printable[:rate]}" - out_str << ", Amount: #{printable[:value]}" - out_str.strip - end - - # @return [Hash] - def printable_values - out_h = {} - out_h[:code] = @code.nil? ? '' : @code - out_h[:base] = @base.nil? ? '' : print_float(@base) - out_h[:rate] = @rate.nil? ? '' : print_float(@rate).to_s - out_h[:value] = @value.to_s.empty? ? '' : print_float(@value.to_f).to_s - out_h - end - - # @return [String] - def to_table_line - printable = printable_values - out_str = String.new - out_str << "| #{printable[:base].ljust(13, ' ')}" - out_str << " | #{printable[:code].ljust(6, ' ')}" - out_str << " | #{printable[:rate].ljust(8, ' ')}" - out_str << " | #{printable[:value].ljust(13, ' ')} |" - out_str.strip - end - end - - # Represents tax information, grouped as an array. - class Taxes < Array - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super(prediction.map { |entry| TaxField.new(entry, page_id) }) - end - - # @param char [String] - # @return [String] - def line_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 15}" - out_str << "+#{char * 8}" - out_str << "+#{char * 10}" - out_str << "+#{char * 15}" - out_str << '+' - out_str - end - - # @return [String] - def to_s - return '' if nil? || empty? - - out_str = String.new - out_str << "\n#{line_separator('-')}" - out_str << "\n | Base | Code | Rate (%) | Amount |" - out_str << "\n#{line_separator('=')}" - each do |entry| - out_str << "\n #{entry.to_table_line}\n#{line_separator('-')}" - end - out_str - end - end - end - end -end diff --git a/lib/mindee/parsing/universal/universal_list_field.rb b/lib/mindee/parsing/universal/universal_list_field.rb deleted file mode 100644 index 2602ae357..000000000 --- a/lib/mindee/parsing/universal/universal_list_field.rb +++ /dev/null @@ -1,58 +0,0 @@ -# frozen_string_literal: true - -require_relative 'universal_object_field' - -module Mindee - module Parsing - module Universal - # A list of values or objects, used in universal APIs. - class UniversalListField - include Mindee::Parsing::Standard - include Mindee::Parsing::Universal - - # ID of the page (as given by the API). - # @return [Integer] - attr_reader :page_id - - # List of word values - # @return [Array] - attr_reader :values - - # ID of the page the object was found on. - # List of word values. - - def initialize(raw_prediction, page_id = nil) - @values = [] # : Array[UniversalObjectField | Parsing::Standard::StringField] - - raw_prediction.each do |value| - page_id = value['page_id'] if value.key?('page_id') && !value['page_id'].nil? - - if Universal.universal_object?(value) - @values.push(Mindee::Parsing::Universal::UniversalObjectField.new(value, page_id)) - else - value_str = value.dup - value_str['value'] = value_str['value'].to_s if value_str.key?('value') && !value_str['value'].nil? - @values.push(Mindee::Parsing::Standard::StringField.new(value_str, page_id)) - end - end - end - - # Return an Array of the contents of all values. - # @return [Array] - def contents_list - @values.map(&:to_s) - end - - # Return a string representation of all values. - def contents_string(separator = ' ') - @values.map(&:to_s).join(separator) - end - - # String representation - def to_s - contents_string - end - end - end - end -end diff --git a/lib/mindee/parsing/universal/universal_object_field.rb b/lib/mindee/parsing/universal/universal_object_field.rb deleted file mode 100644 index 43b0f53bc..000000000 --- a/lib/mindee/parsing/universal/universal_object_field.rb +++ /dev/null @@ -1,121 +0,0 @@ -# frozen_string_literal: true - -require_relative '../common' - -module Mindee - module Parsing - # Universal fields and functions. - module Universal - # A JSON-like object, with miscellaneous values. - class UniversalObjectField - # ID of the page (as given by the API). - # @return [Integer] - attr_reader :page_id - # The confidence score, value will be between 0.0 and 1.0 - # @return [Float] - attr_reader :confidence - # Value as String - # @return [String] - attr_reader :raw_value - # All values - # @return [Hash] - attr_reader :all_values - - # ID of the page the object was found on. - # Confidence with which the value was assessed. - # Raw unprocessed value, as it was sent by the server. - - def initialize(raw_prediction, page_id = nil) - @all_values = {} # : Hash[String | Symbol, untyped] - item_page_id = nil - raw_prediction.each do |name, value| - case name - when 'page_id' - item_page_id = value - when 'polygon', 'rectangle', 'quadrangle', 'bounding_box' - handle_position_field(name, value, item_page_id) - when 'confidence' - @confidence = value - when 'raw_value' - @raw_value = value - else - handle_default_field(name, value) - end - @page_id = page_id || item_page_id - end - end - - # String representation that takes into account the level of indentation. - def str_level(level = 0) - indent = " #{' ' * level}" - out_str = '' - @all_values.each do |attr, value| - str_value = value.nil? ? '' : value.to_s - out_str += "\n#{indent}:#{attr}: #{str_value}".rstrip - end - "\n#{indent}#{out_str.strip}" - end - - # Necessary overload of the method_missing method to allow for direct access to dynamic attributes without - # changing the user usage too much. - # Returns the corresponding attribute when asked. - # - # Otherwise, raises a NoMethodError. - # - # @param method_name [Symbol] The name of the method being called. - # @param _args [Array] Arguments passed to the method. - # @return [Object] The value associated with the method name in @all_values. - def method_missing(method_name, *_args) - super unless @all_values.key?(method_name.to_s) - @all_values[method_name.to_s] - end - - # Necessary overload of the respond_to_missing? method to allow for direct access to dynamic attributes without - # changing the user usage too much. - # Returns true if the method name exists as a key in @all_values, - # indicating that the object can respond to the method. - # Otherwise, calls super to fallback to the default behavior. - # - # @param method_name [Symbol] The name of the method being checked. - # @param include_private [bool] Whether to include private methods in the check. - # @return [bool] `true` if the method can be responded to, false otherwise. - def respond_to_missing?(method_name, include_private = false) - @all_values.key?(method_name.to_s) || super - end - - # String representation - def to_s - str_level - end - - private - - def handle_position_field(name, value, item_page_id) - @all_values[name.to_s] = - Mindee::Parsing::Standard::PositionField.new( - { name.to_s => value }, item_page_id - ) - end - - def handle_default_field(name, value) - @all_values[name] = value&.to_s - end - end - - def self.universal_object?(str_dict) - common_keys = [ - 'value', - 'polygon', - 'rectangle', - 'page_id', - 'confidence', - 'quadrangle', - 'values', - 'raw_value', - ] - str_dict.each_key { |key| return true unless common_keys.include?(key.to_s) } - false - end - end - end -end diff --git a/lib/mindee/parsing/v2.rb b/lib/mindee/parsing/v2.rb deleted file mode 100644 index d5ae4ebb8..000000000 --- a/lib/mindee/parsing/v2.rb +++ /dev/null @@ -1,16 +0,0 @@ -# frozen_string_literal: true - -require_relative 'v2/common_response' -require_relative 'v2/error_response' -require_relative 'v2/field' -require_relative 'v2/inference' -require_relative 'v2/inference_file' -require_relative 'v2/inference_model' -require_relative 'v2/inference_response' -require_relative 'v2/inference_result' -require_relative 'v2/inference_active_options' -require_relative 'v2/job' -require_relative 'v2/job_response' -require_relative 'v2/job_webhook' -require_relative 'v2/raw_text' -require_relative 'v2/raw_text_page' diff --git a/lib/mindee/parsing/v2/inference.rb b/lib/mindee/parsing/v2/inference.rb deleted file mode 100644 index 328015640..000000000 --- a/lib/mindee/parsing/v2/inference.rb +++ /dev/null @@ -1,44 +0,0 @@ -# frozen_string_literal: true - -require_relative 'inference_job' -require_relative 'inference_model' -require_relative 'inference_file' -require_relative 'inference_result' -require_relative 'inference_active_options' -require_relative '../../v2/parsing/base_inference' - -module Mindee - module Parsing - module V2 - # Complete data returned by an inference request. - class Inference < Mindee::V2::Parsing::BaseInference - # @return [InferenceActiveOptions] Options which were activated during the inference. - attr_reader :active_options - # @return [InferenceResult] Result contents. - attr_reader :result - - @params_type = Input::InferenceParameters - @slug = 'extraction' - @response_type = InferenceResponse - - # @param server_response [Hash] Hash representation of the JSON returned by the service. - def initialize(server_response) - super - @active_options = InferenceActiveOptions.new(server_response['active_options']) - @result = InferenceResult.new(server_response['result']) - end - - # String representation. - # @return [String] - def to_s - [ - super, - @active_options.to_s, - @result.to_s, - '', - ].join("\n") - end - end - end - end -end diff --git a/lib/mindee/parsing/v2/inference_response.rb b/lib/mindee/parsing/v2/inference_response.rb deleted file mode 100644 index 7911c33ba..000000000 --- a/lib/mindee/parsing/v2/inference_response.rb +++ /dev/null @@ -1,33 +0,0 @@ -# frozen_string_literal: true - -require_relative 'common_response' -require_relative 'inference' -require_relative '../../v2/parsing/base_response' - -module Mindee - module Parsing - module V2 - # HTTP response wrapper that embeds a V2 Inference. - class InferenceResponse < Mindee::V2::Parsing::BaseResponse - # @return [Inference] Parsed inference payload. - attr_reader :inference - - @slug = 'extraction' - @_params_type = Input::InferenceParameters - - # @param server_response [Hash] Hash parsed from the API JSON response. - def initialize(server_response) - super - - @inference = Inference.new(server_response['inference']) - end - - # String representation. - # @return [String] - def to_s - @inference.to_s - end - end - end - end -end diff --git a/lib/mindee/parsing/v2/inference_result.rb b/lib/mindee/parsing/v2/inference_result.rb deleted file mode 100644 index 8ee1bd1c2..000000000 --- a/lib/mindee/parsing/v2/inference_result.rb +++ /dev/null @@ -1,42 +0,0 @@ -# frozen_string_literal: true - -require_relative 'field/inference_fields' -require_relative 'raw_text' -require_relative 'rag_metadata' - -module Mindee - module Parsing - module V2 - # Wrapper for the result of a V2 inference request. - class InferenceResult - # @return [Mindee::Parsing::V2::Field::InferenceFields] Fields produced by the model. - attr_reader :fields - # @return [Mindee::Parsing::V2::RawText, nil] Optional extra data. - attr_reader :raw_text - # @return [Mindee::Parsing::V2::RAGMetadata, nil] Optional RAG metadata. - attr_reader :rag - - # @param server_response [Hash] Hash version of the JSON returned by the API. - def initialize(server_response) - raise ArgumentError, 'server_response must be a Hash' unless server_response.is_a?(Hash) - - @fields = Field::InferenceFields.new(server_response['fields']) - - @raw_text = server_response['raw_text'] ? RawText.new(server_response['raw_text']) : nil - @rag = (V2::RAGMetadata.new(server_response['rag']) if server_response.key?('rag') && server_response['rag']) - end - - # String representation. - # @return [String] - def to_s - parts = [ - 'Fields', - '======', - @fields.to_s, - ] - parts.join("\n") - end - end - end - end -end diff --git a/lib/mindee/pdf/extracted_pdf.rb b/lib/mindee/pdf/extracted_pdf.rb index 5ac3f7671..7f2efb6f0 100644 --- a/lib/mindee/pdf/extracted_pdf.rb +++ b/lib/mindee/pdf/extracted_pdf.rb @@ -3,57 +3,67 @@ module Mindee # PDF Extraction Module. module PDF - module PDFExtractor - # An extracted sub-Pdf. - class ExtractedPDF - # Byte contents of the pdf - # @return [StringIO] - attr_reader :pdf_bytes - - # Name of the file. - # @return [String] - attr_reader :filename - - # @param pdf_bytes [StringIO] - # @param filename [String] - def initialize(pdf_bytes, filename) - @pdf_bytes = pdf_bytes - @filename = filename - end + # An extracted sub-Pdf. + class ExtractedPDF + # Byte contents of the pdf + # @return [StringIO] + attr_reader :pdf_bytes - # Retrieves the page count for a given pdf. - # @return [Integer] - def page_count - current_pdf = Mindee::PDF::PDFProcessor.open_pdf(pdf_bytes) - current_pdf.pages.size - rescue TypeError, Origami::InvalidPDFError - raise Errors::MindeePDFError, 'Could not retrieve page count from Extracted PDF object.' - end + # Name of the file. + # @return [String] + attr_reader :filename + + # @param pdf_stream [StringIO, File] + # @param filename [String] + def initialize(pdf_stream, filename) + @filename = filename - # Writes the contents of the current PDF object to a file. - # @param output_path [String] Path to write to. - # @param override [bool] Whether to override the destination file. - def write_to_file(output_path, override: false) - raise Errors::MindeePDFError, 'Provided path is not a file' if File.directory?(output_path) - raise Errors::MindeePDFError, 'Invalid save path provided' unless File.exist?( - File.expand_path('..', output_path) - ) && !override - - if File.extname(output_path).downcase == 'pdf' - base_path = File.expand_path('..', output_path) - output_path = File.expand_path("#{File.basename(output_path)}.pdf", base_path) - end - - File.write(output_path, @pdf_bytes) + if pdf_stream.is_a?(File) + pdf_stream.rewind + @pdf_bytes = StringIO.new(pdf_stream.read) + else + @pdf_bytes = pdf_stream end + end + + # Retrieves the page count for a given pdf. + # @return [Integer] + def page_count + current_pdf = Mindee::PDF::PDFProcessor.open_pdf(pdf_bytes) + current_pdf.pages.size + rescue TypeError, Origami::InvalidPDFError + raise Error::MindeePDFError, 'Could not retrieve page count from Extracted PDF object.' + end - # Returns the current PDF object as a usable BytesInputSource. - # @return [Mindee::Input::Source::BytesInputSource] - def as_input_source - raise Errors::MindeePDFError, 'Bytes object is nil.' if @pdf_bytes.nil? + # Writes the contents of the current PDF object to a file. + # @param output_path [String] Path to write to. + # @param override [bool] Whether to override the destination file. + def write_to_file(output_path, override: false) + raise Error::MindeePDFError, 'Provided path is not a file' if File.directory?(output_path) + raise Error::MindeePDFError, 'Invalid save path provided' unless File.exist?( + File.expand_path('..', output_path) + ) && !override - Mindee::Input::Source::BytesInputSource.new(@pdf_bytes.read || '', @filename) + if File.extname(output_path).downcase == 'pdf' + base_path = File.expand_path('..', output_path) + output_path = File.expand_path("#{File.basename(output_path)}.pdf", base_path) end + + @pdf_bytes.rewind if @pdf_bytes.respond_to?(:rewind) + File.binwrite(output_path, @pdf_bytes.read.to_s) + @pdf_bytes.rewind if @pdf_bytes.respond_to?(:rewind) + end + + # Returns the current PDF object as a usable BytesInputSource. + # @return [Mindee::Input::Source::BytesInputSource] + def as_input_source + raise Error::MindeePDFError, 'Bytes object is nil.' if @pdf_bytes.nil? + + @pdf_bytes.rewind if @pdf_bytes.respond_to?(:rewind) + data = @pdf_bytes.read || '' + @pdf_bytes.rewind if @pdf_bytes.respond_to?(:rewind) + + Mindee::Input::Source::BytesInputSource.new(data, @filename) end end end diff --git a/lib/mindee/pdf/pdf_compressor.rb b/lib/mindee/pdf/pdf_compressor.rb index 33a105e09..c93f2369d 100644 --- a/lib/mindee/pdf/pdf_compressor.rb +++ b/lib/mindee/pdf/pdf_compressor.rb @@ -1,6 +1,8 @@ # frozen_string_literal: true +Mindee::Dependency.require_all_deps! require 'pdf-reader' + # Shorthand for pdf-reader's PDF namespace, to avoid mixups with the local Origami fork. PDFReader = PDF diff --git a/lib/mindee/pdf/pdf_extractor.rb b/lib/mindee/pdf/pdf_extractor.rb index 45be549d8..259bec808 100644 --- a/lib/mindee/pdf/pdf_extractor.rb +++ b/lib/mindee/pdf/pdf_extractor.rb @@ -3,118 +3,119 @@ module Mindee # Pdf Extraction Module. module PDF - # Pdf Extraction class. - module PDFExtractor - # Pdf extraction class. - class PDFExtractor - # @param local_input [Mindee::Input::Source::LocalInputSource] - def initialize(local_input) - @filename = local_input.filename - if local_input.pdf? - @source_pdf = local_input.io_stream - else - pdf_image = Image::ImageExtractor.attach_image_as_new_file(local_input.io_stream) - io_buffer = StringIO.new - pdf_image.save(io_buffer) - - @source_pdf = io_buffer - end + # Pdf extraction class. + class PDFExtractor + # @param local_input [Mindee::Input::Source::LocalInputSource] + def initialize(local_input) + unless Mindee::Dependency.all_deps_available? + raise NotImplementedError, Mindee::Dependency::MINDEE_DEPENDENCIES_LOAD_ERROR end - # Retrieves the page count for the Pdf object. - # @return [Integer] - def page_count - Mindee::PDF::PDFProcessor.open_pdf(@source_pdf).pages.size + @filename = local_input.filename + if local_input.pdf? + @source_pdf = local_input.io_stream + else + pdf_image = Image::ImageExtractor.attach_image_as_new_file(local_input.io_stream) + io_buffer = StringIO.new + pdf_image.save(io_buffer) + + @source_pdf = io_buffer end + end - # Creates a new Pdf from pages and save it into a buffer. - # @param page_indexes [Array] List of page number to use for merging in the original Pdf. - # @return [StringIO] The buffer containing the new Pdf. - def cut_pages(page_indexes) - options = PageOptions.new(params: { - page_indexes: page_indexes, - }) + # Retrieves the page count for the Pdf object. + # @return [Integer] + def page_count + Mindee::PDF::PDFProcessor.open_pdf(@source_pdf).pages.size + end - Mindee::PDF::PDFProcessor.parse(@source_pdf, options) - end + # Creates a new Pdf from pages and save it into a buffer. + # @param page_indexes [Array] List of page number to use for merging in the original Pdf. + # @return [StringIO] The buffer containing the new Pdf. + def cut_pages(page_indexes) + options = PageOptions.new(params: { + page_indexes: page_indexes, + }) - # Extract the sub-documents from the main pdf, based on the given list of page indexes. - # @param page_indexes [Array>] List of page number to use for merging in the original Pdf. - # @return [Array] The buffer containing the new Pdf. - def extract_sub_documents(page_indexes) - extracted_pdfs = [] - extension = File.extname(@filename) - basename = File.basename(@filename, extension) - page_indexes.each do |page_index_list| - if page_index_list.nil? || page_index_list.empty? - raise Errors::MindeePDFError, "Empty indexes aren't allowed for extraction #{page_index_list}" - end + Mindee::PDF::PDFProcessor.parse(@source_pdf, options) + end + + # Extract the sub-documents from the main pdf, based on the given list of page indexes. + # @param page_indexes [Array>] List of page number to use for merging in the original Pdf. + # @return [Array] The buffer containing the new Pdf. + def extract_sub_documents(page_indexes) + extracted_pdfs = [] # @type var extracted_pdfs: Array[Mindee::PDF::ExtractedPDF] + extension = File.extname(@filename) + basename = File.basename(@filename, extension) + page_indexes.each do |page_index_list| + if page_index_list.nil? || page_index_list.empty? + raise Error::MindeePDFError, "Empty indexes aren't allowed for extraction #{page_index_list}" + end - page_index_list.each do |page_index| - if (page_index > page_count) || page_index.negative? - raise Errors::MindeePDFError, - "Index #{page_index} is out of range." - end + page_index_list.each do |page_index| + if (page_index > page_count) || page_index.negative? + raise Error::MindeePDFError, + "Index #{page_index} is out of range." end - formatted_max_index = format('%03d', page_index_list[page_index_list.length - 1] + 1).to_s - field_filename = "#{basename}_#{format('%03d', - page_index_list[0] + 1)}-#{formatted_max_index}#{extension}" - extracted_pdf = Mindee::PDF::PDFExtractor::ExtractedPDF.new(cut_pages(page_index_list), - field_filename) - extracted_pdfs << extracted_pdf end - extracted_pdfs + formatted_max_index = format('%03d', page_index_list[-1] + 1).to_s + field_filename = "#{basename}_#{format('%03d', + page_index_list[0] + 1)}-#{formatted_max_index}#{extension}" + extracted_pdf = Mindee::PDF::ExtractedPDF.new(cut_pages(page_index_list), + field_filename) + extracted_pdfs << extracted_pdf end + extracted_pdfs + end - # rubocop:disable Metrics/CyclomaticComplexity - # rubocop:disable Metrics/PerceivedComplexity + # rubocop:disable Metrics/CyclomaticComplexity + # rubocop:disable Metrics/PerceivedComplexity - # Extracts invoices as complete PDFs from the document. - # @param page_indexes [Array, InvoiceSplitterV1InvoicePageGroup>] - # @param strict [bool] - # @return [Array] - def extract_invoices(page_indexes, strict: false) - raise Errors::MindeePDFError, 'No indexes provided.' if page_indexes.empty? + # Extracts invoices as complete PDFs from the document. + # @param page_indexes [Array, InvoiceSplitterV1InvoicePageGroup>] + # @param strict [bool] + # @return [Array] + def extract_invoices(page_indexes, strict: false) + raise Error::MindeePDFError, 'No indexes provided.' if page_indexes.empty? - if page_indexes[0].is_a?(Array) && page_indexes[0].all? { |i| i.is_a?(Integer) } - page_indexes_as_array = page_indexes # @type var page_indexes : Array[Array[Integer]] - return extract_sub_documents(page_indexes_as_array) - end - p_ids = page_indexes # @type var page_indexes: Product::InvoiceSplitter::InvoiceSplitterV1InvoicePageGroups - return extract_sub_documents(p_ids.map(&:page_indexes)) unless strict - - correct_page_indexes = [] - current_list = [] - previous_confidence = nil - p_ids.each_with_index do |p_i, i| - page_index = p_i # @type var page_index: Product::InvoiceSplitter::InvoiceSplitterV1InvoicePageGroup - confidence = page_index.confidence.to_f - page_list = page_index.page_indexes - - if confidence >= 0.5 && previous_confidence.nil? - current_list = page_list - elsif confidence >= 0.5 && i < p_ids.length - 1 - correct_page_indexes << current_list - current_list = page_list - elsif confidence < 0.5 && i == p_ids.length - 1 - current_list.concat page_list - correct_page_indexes << current_list - else - correct_page_indexes << current_list - correct_page_indexes << page_list - end - previous_confidence = confidence + if page_indexes[0].is_a?(Array) && page_indexes[0].all?(Integer) + page_indexes_as_array = page_indexes # @type var page_indexes : Array[Array[Integer]] + return extract_sub_documents(page_indexes_as_array) + end + p_ids = page_indexes # @type var page_indexes: Product::InvoiceSplitter::InvoiceSplitterV1InvoicePageGroups + return extract_sub_documents(p_ids.map(&:page_indexes)) unless strict + + correct_page_indexes = [] # @type var correct_page_indexes: Array[Array[Integer]] + current_list = [] # @type var current_list: Array[Integer] + previous_confidence = nil + p_ids.each_with_index do |p_i, i| + page_index = p_i # @type var page_index: Product::InvoiceSplitter::InvoiceSplitterV1InvoicePageGroup + confidence = page_index.confidence.to_f + page_list = page_index.page_indexes + + if confidence >= 0.5 && previous_confidence.nil? + current_list = page_list + elsif confidence >= 0.5 && i < p_ids.length - 1 + correct_page_indexes << current_list + current_list = page_list + elsif confidence < 0.5 && i == p_ids.length - 1 + current_list.concat page_list + correct_page_indexes << current_list + else + correct_page_indexes << current_list + correct_page_indexes << page_list end - extract_sub_documents(correct_page_indexes) + previous_confidence = confidence end + extract_sub_documents(correct_page_indexes) + end - # rubocop:enable Metrics/CyclomaticComplexity - # rubocop:enable Metrics/PerceivedComplexity + # rubocop:enable Metrics/CyclomaticComplexity + # rubocop:enable Metrics/PerceivedComplexity - private + private - attr_reader :source_pdf, :filename - end + attr_reader :source_pdf, :filename end end end diff --git a/lib/mindee/pdf/pdf_processor.rb b/lib/mindee/pdf/pdf_processor.rb index 4f37116f4..a40a79fe0 100644 --- a/lib/mindee/pdf/pdf_processor.rb +++ b/lib/mindee/pdf/pdf_processor.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'set' +Mindee::Dependency.require_all_deps! require 'origami' require_relative 'pdf_tools' @@ -61,6 +61,11 @@ def self.indexes_from_remove(page_indexes, all_pages) # @param io_stream [StringIO] # @return [Origami::PDF] def self.open_pdf(io_stream) + unless PDFTools.pdf_header?(io_stream) + raise Origami::InvalidPDFError, + 'Input stream does not contain a PDF header.' + end + pdf_parser = Origami::PDF::LinearParser.new({ verbosity: Origami::Parser::VERBOSE_QUIET }) io_stream.seek(0) pdf_parser.parse(io_stream) diff --git a/lib/mindee/pdf/pdf_tools.rb b/lib/mindee/pdf/pdf_tools.rb index c3e6bb549..8a2d851eb 100644 --- a/lib/mindee/pdf/pdf_tools.rb +++ b/lib/mindee/pdf/pdf_tools.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +Mindee::Dependency.require_all_deps! require 'origami' module Mindee @@ -53,10 +54,28 @@ def self.stream_has_text?(stream) text_operators.any? { |op| data.include?(op) } end + # Checks whether a stream contains a PDF header near the beginning. + # @param [StringIO] io_stream Binary-encoded stream. + # @param [Integer] maximum_offset Maximum allowed offset to find '%PDF-'. + # @return [bool] `true` when the stream appears to be a PDF. + def self.pdf_header?(io_stream, maximum_offset: 500) + initial_pos = nil + initial_pos = io_stream.pos if io_stream.respond_to?(:pos) + io_stream.seek(0) + io_stream.gets('%PDF-') + !(io_stream.eof? || io_stream.pos > maximum_offset) + rescue TypeError, IOError, SystemCallError + false + ensure + io_stream.seek(initial_pos) if !initial_pos.nil? && io_stream.respond_to?(:seek) + end + # Checks whether the file has source_text. Sends false if the file isn't a PDF. # @param [StringIO] pdf_data Abinary-encoded stream representing the PDF file. # @return [bool] `true` if the pdf has source text, false otherwise. def self.source_text?(pdf_data) + return false unless pdf_header?(pdf_data) + begin pdf_data.rewind pdf = Origami::PDF.read(pdf_data) diff --git a/lib/mindee/product/barcode_reader/barcode_reader_v1.rb b/lib/mindee/product/barcode_reader/barcode_reader_v1.rb deleted file mode 100644 index dc2e0ed2b..000000000 --- a/lib/mindee/product/barcode_reader/barcode_reader_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'barcode_reader_v1_document' -require_relative 'barcode_reader_v1_page' - -module Mindee - module Product - # Barcode Reader module. - module BarcodeReader - # Barcode Reader API version 1 inference prediction. - class BarcodeReaderV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'barcode_reader' - @endpoint_version = '1' - @has_async = false - @has_sync = true - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = BarcodeReaderV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(BarcodeReaderV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/barcode_reader/barcode_reader_v1_document.rb b/lib/mindee/product/barcode_reader/barcode_reader_v1_document.rb deleted file mode 100644 index 3f82168e0..000000000 --- a/lib/mindee/product/barcode_reader/barcode_reader_v1_document.rb +++ /dev/null @@ -1,44 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module BarcodeReader - # Barcode Reader API version 1.0 document data. - class BarcodeReaderV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # List of decoded 1D barcodes. - # @return [Array] - attr_reader :codes_1d - # List of decoded 2D barcodes. - # @return [Array] - attr_reader :codes_2d - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @codes_1d = [] # : Array[Parsing::Standard::StringField] - prediction['codes_1d'].each do |item| - @codes_1d.push(Parsing::Standard::StringField.new(item, page_id)) - end - @codes_2d = [] # : Array[Parsing::Standard::StringField] - prediction['codes_2d'].each do |item| - @codes_2d.push(Parsing::Standard::StringField.new(item, page_id)) - end - end - - # @return [String] - def to_s - codes_1d = @codes_1d.join("\n #{' ' * 13}") - codes_2d = @codes_2d.join("\n #{' ' * 13}") - out_str = String.new - out_str << "\n:Barcodes 1D: #{codes_1d}".rstrip - out_str << "\n:Barcodes 2D: #{codes_2d}".rstrip - out_str[1..].to_s - end - end - end - end -end diff --git a/lib/mindee/product/barcode_reader/barcode_reader_v1_page.rb b/lib/mindee/product/barcode_reader/barcode_reader_v1_page.rb deleted file mode 100644 index 9eec78591..000000000 --- a/lib/mindee/product/barcode_reader/barcode_reader_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'barcode_reader_v1_document' - -module Mindee - module Product - module BarcodeReader - # Barcode Reader API version 1.0 page data. - class BarcodeReaderV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - BarcodeReaderV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Barcode Reader V1 page prediction. - class BarcodeReaderV1PagePrediction < BarcodeReaderV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/bill_of_lading/bill_of_lading_v1.rb b/lib/mindee/product/bill_of_lading/bill_of_lading_v1.rb deleted file mode 100644 index 620f68065..000000000 --- a/lib/mindee/product/bill_of_lading/bill_of_lading_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'bill_of_lading_v1_document' -require_relative 'bill_of_lading_v1_page' - -module Mindee - module Product - # Bill of Lading module. - module BillOfLading - # Bill of Lading API version 1 inference prediction. - class BillOfLadingV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'bill_of_lading' - @endpoint_version = '1' - @has_async = true - @has_sync = false - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = BillOfLadingV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(BillOfLadingV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_carrier.rb b/lib/mindee/product/bill_of_lading/bill_of_lading_v1_carrier.rb deleted file mode 100644 index 5e2db186e..000000000 --- a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_carrier.rb +++ /dev/null @@ -1,52 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module BillOfLading - # The shipping company responsible for transporting the goods. - class BillOfLadingV1Carrier < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The name of the carrier. - # @return [String] - attr_reader :name - # The professional number of the carrier. - # @return [String] - attr_reader :professional_number - # The Standard Carrier Alpha Code (SCAC) of the carrier. - # @return [String] - attr_reader :scac - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @name = prediction['name'] - @professional_number = prediction['professional_number'] - @scac = prediction['scac'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:name] = format_for_display(@name) - printable[:professional_number] = format_for_display(@professional_number) - printable[:scac] = format_for_display(@scac) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Name: #{printable[:name]}" - out_str << "\n :Professional Number: #{printable[:professional_number]}" - out_str << "\n :SCAC: #{printable[:scac]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_item.rb b/lib/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_item.rb deleted file mode 100644 index a68f03ba1..000000000 --- a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_item.rb +++ /dev/null @@ -1,101 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module BillOfLading - # The goods being shipped. - class BillOfLadingV1CarrierItem < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # A description of the item. - # @return [String] - attr_reader :description - # The gross weight of the item. - # @return [Float] - attr_reader :gross_weight - # The measurement of the item. - # @return [Float] - attr_reader :measurement - # The unit of measurement for the measurement. - # @return [String] - attr_reader :measurement_unit - # The quantity of the item being shipped. - # @return [Float] - attr_reader :quantity - # The unit of measurement for weights. - # @return [String] - attr_reader :weight_unit - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @description = prediction['description'] - @gross_weight = prediction['gross_weight'] - @measurement = prediction['measurement'] - @measurement_unit = prediction['measurement_unit'] - @quantity = prediction['quantity'] - @weight_unit = prediction['weight_unit'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:description] = format_for_display(@description) - printable[:gross_weight] = - @gross_weight.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@gross_weight) - printable[:measurement] = - @measurement.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@measurement) - printable[:measurement_unit] = format_for_display(@measurement_unit) - printable[:quantity] = - @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) - printable[:weight_unit] = format_for_display(@weight_unit) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:description] = format_for_display(@description, 36) - printable[:gross_weight] = - @gross_weight.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@gross_weight) - printable[:measurement] = - @measurement.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@measurement) - printable[:measurement_unit] = format_for_display(@measurement_unit, nil) - printable[:quantity] = - @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) - printable[:weight_unit] = format_for_display(@weight_unit, nil) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 37s', printable[:description]) - out_str << format('| %- 13s', printable[:gross_weight]) - out_str << format('| %- 12s', printable[:measurement]) - out_str << format('| %- 17s', printable[:measurement_unit]) - out_str << format('| %- 9s', printable[:quantity]) - out_str << format('| %- 12s', printable[:weight_unit]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Description: #{printable[:description]}" - out_str << "\n :Gross Weight: #{printable[:gross_weight]}" - out_str << "\n :Measurement: #{printable[:measurement]}" - out_str << "\n :Measurement Unit: #{printable[:measurement_unit]}" - out_str << "\n :Quantity: #{printable[:quantity]}" - out_str << "\n :Weight Unit: #{printable[:weight_unit]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_items.rb b/lib/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_items.rb deleted file mode 100644 index 9c5541afa..000000000 --- a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_items.rb +++ /dev/null @@ -1,62 +0,0 @@ -# frozen_string_literal: true - -require_relative 'bill_of_lading_v1_shipper' -require_relative 'bill_of_lading_v1_consignee' -require_relative 'bill_of_lading_v1_notify_party' -require_relative 'bill_of_lading_v1_carrier' -require_relative 'bill_of_lading_v1_carrier_item' - -module Mindee - module Product - module BillOfLading - # The goods being shipped. - class BillOfLadingV1CarrierItems < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - BillOfLading::BillOfLadingV1CarrierItem.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 38}" - out_str << "+#{char * 14}" - out_str << "+#{char * 13}" - out_str << "+#{char * 18}" - out_str << "+#{char * 10}" - out_str << "+#{char * 13}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Description ' - out_str << ' | Gross Weight' - out_str << ' | Measurement' - out_str << ' | Measurement Unit' - out_str << ' | Quantity' - out_str << ' | Weight Unit' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_consignee.rb b/lib/mindee/product/bill_of_lading/bill_of_lading_v1_consignee.rb deleted file mode 100644 index d81dd0dde..000000000 --- a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_consignee.rb +++ /dev/null @@ -1,58 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module BillOfLading - # The party to whom the goods are being shipped. - class BillOfLadingV1Consignee < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The address of the consignee. - # @return [String] - attr_reader :address - # The email of the shipper. - # @return [String] - attr_reader :email - # The name of the consignee. - # @return [String] - attr_reader :name - # The phone number of the consignee. - # @return [String] - attr_reader :phone - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address = prediction['address'] - @email = prediction['email'] - @name = prediction['name'] - @phone = prediction['phone'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:address] = format_for_display(@address) - printable[:email] = format_for_display(@email) - printable[:name] = format_for_display(@name) - printable[:phone] = format_for_display(@phone) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Address: #{printable[:address]}" - out_str << "\n :Email: #{printable[:email]}" - out_str << "\n :Name: #{printable[:name]}" - out_str << "\n :Phone: #{printable[:phone]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_document.rb b/lib/mindee/product/bill_of_lading/bill_of_lading_v1_document.rb deleted file mode 100644 index 4e7fb064f..000000000 --- a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_document.rb +++ /dev/null @@ -1,163 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'bill_of_lading_v1_shipper' -require_relative 'bill_of_lading_v1_consignee' -require_relative 'bill_of_lading_v1_notify_party' -require_relative 'bill_of_lading_v1_carrier' -require_relative 'bill_of_lading_v1_carrier_items' - -module Mindee - module Product - module BillOfLading - # Bill of Lading API version 1.1 document data. - class BillOfLadingV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # A unique identifier assigned to a Bill of Lading document. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :bill_of_lading_number - # The shipping company responsible for transporting the goods. - # @return [Mindee::Product::BillOfLading::BillOfLadingV1Carrier] - attr_reader :carrier - # The goods being shipped. - # @return [Mindee::Product::BillOfLading::BillOfLadingV1CarrierItems] - attr_reader :carrier_items - # The party to whom the goods are being shipped. - # @return [Mindee::Product::BillOfLading::BillOfLadingV1Consignee] - attr_reader :consignee - # The date when the bill of lading is issued. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :date_of_issue - # The date when the vessel departs from the port of loading. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :departure_date - # The party to be notified of the arrival of the goods. - # @return [Mindee::Product::BillOfLading::BillOfLadingV1NotifyParty] - attr_reader :notify_party - # The place where the goods are to be delivered. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :place_of_delivery - # The port where the goods are unloaded from the vessel. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :port_of_discharge - # The port where the goods are loaded onto the vessel. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :port_of_loading - # The party responsible for shipping the goods. - # @return [Mindee::Product::BillOfLading::BillOfLadingV1Shipper] - attr_reader :shipper - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @bill_of_lading_number = Parsing::Standard::StringField.new( - prediction['bill_of_lading_number'], - page_id - ) - @carrier = Product::BillOfLading::BillOfLadingV1Carrier.new( - prediction['carrier'], - page_id - ) - @carrier_items = Product::BillOfLading::BillOfLadingV1CarrierItems.new(prediction['carrier_items'], page_id) - @consignee = Product::BillOfLading::BillOfLadingV1Consignee.new( - prediction['consignee'], - page_id - ) - @date_of_issue = Parsing::Standard::DateField.new( - prediction['date_of_issue'], - page_id - ) - @departure_date = Parsing::Standard::DateField.new( - prediction['departure_date'], - page_id - ) - @notify_party = Product::BillOfLading::BillOfLadingV1NotifyParty.new( - prediction['notify_party'], - page_id - ) - @place_of_delivery = Parsing::Standard::StringField.new( - prediction['place_of_delivery'], - page_id - ) - @port_of_discharge = Parsing::Standard::StringField.new( - prediction['port_of_discharge'], - page_id - ) - @port_of_loading = Parsing::Standard::StringField.new( - prediction['port_of_loading'], - page_id - ) - @shipper = Product::BillOfLading::BillOfLadingV1Shipper.new( - prediction['shipper'], - page_id - ) - end - - # @return [String] - def to_s - shipper = @shipper.to_s - consignee = @consignee.to_s - notify_party = @notify_party.to_s - carrier = @carrier.to_s - carrier_items = carrier_items_to_s - out_str = String.new - out_str << "\n:Bill of Lading Number: #{@bill_of_lading_number}".rstrip - out_str << "\n:Shipper:" - out_str << shipper - out_str << "\n:Consignee:" - out_str << consignee - out_str << "\n:Notify Party:" - out_str << notify_party - out_str << "\n:Carrier:" - out_str << carrier - out_str << "\n:Items:" - out_str << carrier_items - out_str << "\n:Port of Loading: #{@port_of_loading}".rstrip - out_str << "\n:Port of Discharge: #{@port_of_discharge}".rstrip - out_str << "\n:Place of Delivery: #{@place_of_delivery}".rstrip - out_str << "\n:Date of issue: #{@date_of_issue}".rstrip - out_str << "\n:Departure Date: #{@departure_date}".rstrip - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def carrier_items_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 38}" - out_str << "+#{char * 14}" - out_str << "+#{char * 13}" - out_str << "+#{char * 18}" - out_str << "+#{char * 10}" - out_str << "+#{char * 13}" - out_str << '+' - out_str - end - - # @return [String] - def carrier_items_to_s - return '' if @carrier_items.empty? - - line_items = @carrier_items.map(&:to_table_line).join("\n#{carrier_items_separator('-')}\n ") - out_str = String.new - out_str << "\n#{carrier_items_separator('-')}" - out_str << "\n |" - out_str << ' Description |' - out_str << ' Gross Weight |' - out_str << ' Measurement |' - out_str << ' Measurement Unit |' - out_str << ' Quantity |' - out_str << ' Weight Unit |' - out_str << "\n#{carrier_items_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{carrier_items_separator('-')}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_notify_party.rb b/lib/mindee/product/bill_of_lading/bill_of_lading_v1_notify_party.rb deleted file mode 100644 index b2cc144f2..000000000 --- a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_notify_party.rb +++ /dev/null @@ -1,58 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module BillOfLading - # The party to be notified of the arrival of the goods. - class BillOfLadingV1NotifyParty < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The address of the notify party. - # @return [String] - attr_reader :address - # The email of the shipper. - # @return [String] - attr_reader :email - # The name of the notify party. - # @return [String] - attr_reader :name - # The phone number of the notify party. - # @return [String] - attr_reader :phone - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address = prediction['address'] - @email = prediction['email'] - @name = prediction['name'] - @phone = prediction['phone'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:address] = format_for_display(@address) - printable[:email] = format_for_display(@email) - printable[:name] = format_for_display(@name) - printable[:phone] = format_for_display(@phone) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Address: #{printable[:address]}" - out_str << "\n :Email: #{printable[:email]}" - out_str << "\n :Name: #{printable[:name]}" - out_str << "\n :Phone: #{printable[:phone]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_page.rb b/lib/mindee/product/bill_of_lading/bill_of_lading_v1_page.rb deleted file mode 100644 index 4a7093c8f..000000000 --- a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'bill_of_lading_v1_document' - -module Mindee - module Product - module BillOfLading - # Bill of Lading API version 1.1 page data. - class BillOfLadingV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - BillOfLadingV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Bill of Lading V1 page prediction. - class BillOfLadingV1PagePrediction < BillOfLadingV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_shipper.rb b/lib/mindee/product/bill_of_lading/bill_of_lading_v1_shipper.rb deleted file mode 100644 index 5ad40f7d1..000000000 --- a/lib/mindee/product/bill_of_lading/bill_of_lading_v1_shipper.rb +++ /dev/null @@ -1,58 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module BillOfLading - # The party responsible for shipping the goods. - class BillOfLadingV1Shipper < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The address of the shipper. - # @return [String] - attr_reader :address - # The email of the shipper. - # @return [String] - attr_reader :email - # The name of the shipper. - # @return [String] - attr_reader :name - # The phone number of the shipper. - # @return [String] - attr_reader :phone - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address = prediction['address'] - @email = prediction['email'] - @name = prediction['name'] - @phone = prediction['phone'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:address] = format_for_display(@address) - printable[:email] = format_for_display(@email) - printable[:name] = format_for_display(@name) - printable[:phone] = format_for_display(@phone) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Address: #{printable[:address]}" - out_str << "\n :Email: #{printable[:email]}" - out_str << "\n :Name: #{printable[:name]}" - out_str << "\n :Phone: #{printable[:phone]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/business_card/business_card_v1.rb b/lib/mindee/product/business_card/business_card_v1.rb deleted file mode 100644 index 79e9b7e48..000000000 --- a/lib/mindee/product/business_card/business_card_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'business_card_v1_document' -require_relative 'business_card_v1_page' - -module Mindee - module Product - # Business Card module. - module BusinessCard - # Business Card API version 1 inference prediction. - class BusinessCardV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'business_card' - @endpoint_version = '1' - @has_async = true - @has_sync = false - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = BusinessCardV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(BusinessCardV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/business_card/business_card_v1_document.rb b/lib/mindee/product/business_card/business_card_v1_document.rb deleted file mode 100644 index 3a0d7082f..000000000 --- a/lib/mindee/product/business_card/business_card_v1_document.rb +++ /dev/null @@ -1,112 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module BusinessCard - # Business Card API version 1.0 document data. - class BusinessCardV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The address of the person. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :address - # The company the person works for. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :company - # The email address of the person. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :email - # The Fax number of the person. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :fax_number - # The given name of the person. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :firstname - # The job title of the person. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :job_title - # The lastname of the person. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :lastname - # The mobile number of the person. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mobile_number - # The phone number of the person. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :phone_number - # The social media profiles of the person or company. - # @return [Array] - attr_reader :social_media - # The website of the person or company. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :website - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address = Parsing::Standard::StringField.new( - prediction['address'], - page_id - ) - @company = Parsing::Standard::StringField.new( - prediction['company'], - page_id - ) - @email = Parsing::Standard::StringField.new(prediction['email'], page_id) - @fax_number = Parsing::Standard::StringField.new( - prediction['fax_number'], - page_id - ) - @firstname = Parsing::Standard::StringField.new( - prediction['firstname'], - page_id - ) - @job_title = Parsing::Standard::StringField.new( - prediction['job_title'], - page_id - ) - @lastname = Parsing::Standard::StringField.new( - prediction['lastname'], - page_id - ) - @mobile_number = Parsing::Standard::StringField.new( - prediction['mobile_number'], - page_id - ) - @phone_number = Parsing::Standard::StringField.new( - prediction['phone_number'], - page_id - ) - @social_media = [] # : Array[Parsing::Standard::StringField] - prediction['social_media'].each do |item| - @social_media.push(Parsing::Standard::StringField.new(item, page_id)) - end - @website = Parsing::Standard::StringField.new( - prediction['website'], - page_id - ) - end - - # @return [String] - def to_s - social_media = @social_media.join("\n #{' ' * 14}") - out_str = String.new - out_str << "\n:Firstname: #{@firstname}".rstrip - out_str << "\n:Lastname: #{@lastname}".rstrip - out_str << "\n:Job Title: #{@job_title}".rstrip - out_str << "\n:Company: #{@company}".rstrip - out_str << "\n:Email: #{@email}".rstrip - out_str << "\n:Phone Number: #{@phone_number}".rstrip - out_str << "\n:Mobile Number: #{@mobile_number}".rstrip - out_str << "\n:Fax Number: #{@fax_number}".rstrip - out_str << "\n:Address: #{@address}".rstrip - out_str << "\n:Website: #{@website}".rstrip - out_str << "\n:Social Media: #{social_media}".rstrip - out_str[1..].to_s - end - end - end - end -end diff --git a/lib/mindee/product/business_card/business_card_v1_page.rb b/lib/mindee/product/business_card/business_card_v1_page.rb deleted file mode 100644 index 488136996..000000000 --- a/lib/mindee/product/business_card/business_card_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'business_card_v1_document' - -module Mindee - module Product - module BusinessCard - # Business Card API version 1.0 page data. - class BusinessCardV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - BusinessCardV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Business Card V1 page prediction. - class BusinessCardV1PagePrediction < BusinessCardV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/cropper/cropper_v1.rb b/lib/mindee/product/cropper/cropper_v1.rb deleted file mode 100644 index 83f312ab1..000000000 --- a/lib/mindee/product/cropper/cropper_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'cropper_v1_document' -require_relative 'cropper_v1_page' - -module Mindee - module Product - # Cropper module. - module Cropper - # Cropper API version 1 inference prediction. - class CropperV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'cropper' - @endpoint_version = '1' - @has_async = false - @has_sync = true - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = CropperV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(CropperV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/cropper/cropper_v1_document.rb b/lib/mindee/product/cropper/cropper_v1_document.rb deleted file mode 100644 index 22514b387..000000000 --- a/lib/mindee/product/cropper/cropper_v1_document.rb +++ /dev/null @@ -1,13 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module Cropper - # Cropper API version 1.1 document data. - class CropperV1Document < Mindee::Parsing::Common::Prediction - end - end - end -end diff --git a/lib/mindee/product/cropper/cropper_v1_page.rb b/lib/mindee/product/cropper/cropper_v1_page.rb deleted file mode 100644 index bff5ebe4f..000000000 --- a/lib/mindee/product/cropper/cropper_v1_page.rb +++ /dev/null @@ -1,53 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'cropper_v1_document' - -module Mindee - module Product - module Cropper - # Cropper API version 1.1 page data. - class CropperV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - CropperV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Cropper V1 page prediction. - class CropperV1PagePrediction < CropperV1Document - include Mindee::Parsing::Standard - - # List of documents found in the image. - # @return [Array] - attr_reader :cropping - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - @cropping = [] - prediction['cropping'].each do |item| - @cropping.push(Parsing::Standard::PositionField.new(item, page_id)) - end - super - end - - # @return [String] - def to_s - cropping = @cropping.join("\n #{' ' * 18}") - out_str = String.new - out_str << "\n:Document Cropper: #{cropping}".rstrip - out_str - end - end - end - end -end diff --git a/lib/mindee/product/delivery_note/delivery_note_v1.rb b/lib/mindee/product/delivery_note/delivery_note_v1.rb deleted file mode 100644 index f0e561d24..000000000 --- a/lib/mindee/product/delivery_note/delivery_note_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'delivery_note_v1_document' -require_relative 'delivery_note_v1_page' - -module Mindee - module Product - # Delivery note module. - module DeliveryNote - # Delivery note API version 1 inference prediction. - class DeliveryNoteV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'delivery_notes' - @endpoint_version = '1' - @has_async = true - @has_sync = false - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = DeliveryNoteV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(DeliveryNoteV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/delivery_note/delivery_note_v1_document.rb b/lib/mindee/product/delivery_note/delivery_note_v1_document.rb deleted file mode 100644 index 995d92a7d..000000000 --- a/lib/mindee/product/delivery_note/delivery_note_v1_document.rb +++ /dev/null @@ -1,82 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module DeliveryNote - # Delivery note API version 1.2 document data. - class DeliveryNoteV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The address of the customer receiving the goods. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :customer_address - # The name of the customer receiving the goods. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :customer_name - # The date on which the delivery is scheduled to arrive. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :delivery_date - # A unique identifier for the delivery note. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :delivery_number - # The address of the supplier providing the goods. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_address - # The name of the supplier providing the goods. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_name - # The total monetary value of the goods being delivered. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_amount - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @customer_address = Parsing::Standard::StringField.new( - prediction['customer_address'], - page_id - ) - @customer_name = Parsing::Standard::StringField.new( - prediction['customer_name'], - page_id - ) - @delivery_date = Parsing::Standard::DateField.new( - prediction['delivery_date'], - page_id - ) - @delivery_number = Parsing::Standard::StringField.new( - prediction['delivery_number'], - page_id - ) - @supplier_address = Parsing::Standard::StringField.new( - prediction['supplier_address'], - page_id - ) - @supplier_name = Parsing::Standard::StringField.new( - prediction['supplier_name'], - page_id - ) - @total_amount = Parsing::Standard::AmountField.new( - prediction['total_amount'], - page_id - ) - end - - # @return [String] - def to_s - out_str = String.new - out_str << "\n:Delivery Date: #{@delivery_date}".rstrip - out_str << "\n:Delivery Number: #{@delivery_number}".rstrip - out_str << "\n:Supplier Name: #{@supplier_name}".rstrip - out_str << "\n:Supplier Address: #{@supplier_address}".rstrip - out_str << "\n:Customer Name: #{@customer_name}".rstrip - out_str << "\n:Customer Address: #{@customer_address}".rstrip - out_str << "\n:Total Amount: #{@total_amount}".rstrip - out_str[1..].to_s - end - end - end - end -end diff --git a/lib/mindee/product/delivery_note/delivery_note_v1_page.rb b/lib/mindee/product/delivery_note/delivery_note_v1_page.rb deleted file mode 100644 index 3d08d6588..000000000 --- a/lib/mindee/product/delivery_note/delivery_note_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'delivery_note_v1_document' - -module Mindee - module Product - module DeliveryNote - # Delivery note API version 1.2 page data. - class DeliveryNoteV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - DeliveryNoteV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Delivery note V1 page prediction. - class DeliveryNoteV1PagePrediction < DeliveryNoteV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/driver_license/driver_license_v1.rb b/lib/mindee/product/driver_license/driver_license_v1.rb deleted file mode 100644 index 6c1c016d6..000000000 --- a/lib/mindee/product/driver_license/driver_license_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'driver_license_v1_document' -require_relative 'driver_license_v1_page' - -module Mindee - module Product - # Driver License module. - module DriverLicense - # Driver License API version 1 inference prediction. - class DriverLicenseV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'driver_license' - @endpoint_version = '1' - @has_async = true - @has_sync = false - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = DriverLicenseV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(DriverLicenseV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/driver_license/driver_license_v1_document.rb b/lib/mindee/product/driver_license/driver_license_v1_document.rb deleted file mode 100644 index 1ecdf8aff..000000000 --- a/lib/mindee/product/driver_license/driver_license_v1_document.rb +++ /dev/null @@ -1,121 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module DriverLicense - # Driver License API version 1.0 document data. - class DriverLicenseV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The category or class of the driver license. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :category - # The alpha-3 ISO 3166 code of the country where the driver license was issued. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :country_code - # The date of birth of the driver license holder. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :date_of_birth - # The DD number of the driver license. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :dd_number - # The expiry date of the driver license. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :expiry_date - # The first name of the driver license holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :first_name - # The unique identifier of the driver license. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :id - # The date when the driver license was issued. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :issued_date - # The authority that issued the driver license. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :issuing_authority - # The last name of the driver license holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :last_name - # The Machine Readable Zone (MRZ) of the driver license. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz - # The place of birth of the driver license holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :place_of_birth - # Second part of the ISO 3166-2 code, consisting of two letters indicating the US State. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :state - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @category = Parsing::Standard::StringField.new( - prediction['category'], - page_id - ) - @country_code = Parsing::Standard::StringField.new( - prediction['country_code'], - page_id - ) - @date_of_birth = Parsing::Standard::DateField.new( - prediction['date_of_birth'], - page_id - ) - @dd_number = Parsing::Standard::StringField.new( - prediction['dd_number'], - page_id - ) - @expiry_date = Parsing::Standard::DateField.new( - prediction['expiry_date'], - page_id - ) - @first_name = Parsing::Standard::StringField.new( - prediction['first_name'], - page_id - ) - @id = Parsing::Standard::StringField.new(prediction['id'], page_id) - @issued_date = Parsing::Standard::DateField.new( - prediction['issued_date'], - page_id - ) - @issuing_authority = Parsing::Standard::StringField.new( - prediction['issuing_authority'], - page_id - ) - @last_name = Parsing::Standard::StringField.new( - prediction['last_name'], - page_id - ) - @mrz = Parsing::Standard::StringField.new(prediction['mrz'], page_id) - @place_of_birth = Parsing::Standard::StringField.new( - prediction['place_of_birth'], - page_id - ) - @state = Parsing::Standard::StringField.new(prediction['state'], page_id) - end - - # @return [String] - def to_s - out_str = String.new - out_str << "\n:Country Code: #{@country_code}".rstrip - out_str << "\n:State: #{@state}".rstrip - out_str << "\n:ID: #{@id}".rstrip - out_str << "\n:Category: #{@category}".rstrip - out_str << "\n:Last Name: #{@last_name}".rstrip - out_str << "\n:First Name: #{@first_name}".rstrip - out_str << "\n:Date of Birth: #{@date_of_birth}".rstrip - out_str << "\n:Place of Birth: #{@place_of_birth}".rstrip - out_str << "\n:Expiry Date: #{@expiry_date}".rstrip - out_str << "\n:Issued Date: #{@issued_date}".rstrip - out_str << "\n:Issuing Authority: #{@issuing_authority}".rstrip - out_str << "\n:MRZ: #{@mrz}".rstrip - out_str << "\n:DD Number: #{@dd_number}".rstrip - out_str[1..].to_s - end - end - end - end -end diff --git a/lib/mindee/product/driver_license/driver_license_v1_page.rb b/lib/mindee/product/driver_license/driver_license_v1_page.rb deleted file mode 100644 index 3d1a36413..000000000 --- a/lib/mindee/product/driver_license/driver_license_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'driver_license_v1_document' - -module Mindee - module Product - module DriverLicense - # Driver License API version 1.0 page data. - class DriverLicenseV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - DriverLicenseV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Driver License V1 page prediction. - class DriverLicenseV1PagePrediction < DriverLicenseV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/financial_document/financial_document_v1.rb b/lib/mindee/product/financial_document/financial_document_v1.rb deleted file mode 100644 index 4b8fc8c90..000000000 --- a/lib/mindee/product/financial_document/financial_document_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'financial_document_v1_document' -require_relative 'financial_document_v1_page' - -module Mindee - module Product - # Financial Document module. - module FinancialDocument - # Financial Document API version 1 inference prediction. - class FinancialDocumentV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'financial_document' - @endpoint_version = '1' - @has_async = true - @has_sync = true - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = FinancialDocumentV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(FinancialDocumentV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/financial_document/financial_document_v1_document.rb b/lib/mindee/product/financial_document/financial_document_v1_document.rb deleted file mode 100644 index 0a86d1b85..000000000 --- a/lib/mindee/product/financial_document/financial_document_v1_document.rb +++ /dev/null @@ -1,326 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'financial_document_v1_line_items' - -module Mindee - module Product - module FinancialDocument - # Financial Document API version 1.14 document data. - class FinancialDocumentV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The customer's address used for billing. - # @return [Mindee::Parsing::Standard::AddressField] - attr_reader :billing_address - # The purchase category. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :category - # The address of the customer. - # @return [Mindee::Parsing::Standard::AddressField] - attr_reader :customer_address - # List of company registration numbers associated to the customer. - # @return [Array] - attr_reader :customer_company_registrations - # The customer account number or identifier from the supplier. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :customer_id - # The name of the customer. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :customer_name - # The date the purchase was made. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :date - # The document number or identifier (invoice number or receipt number). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :document_number - # The type of the document: INVOICE or CREDIT NOTE if it is an invoice, CREDIT CARD RECEIPT or EXPENSE - # RECEIPT if it is a receipt. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :document_type - # Document type extended. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :document_type_extended - # The date on which the payment is due. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :due_date - # The invoice number or identifier only if document is an invoice. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :invoice_number - # List of line item present on the document. - # @return [Mindee::Product::FinancialDocument::FinancialDocumentV1LineItems] - attr_reader :line_items - # The locale of the document. - # @return [Mindee::Parsing::Standard::LocaleField] - attr_reader :locale - # The date on which the payment is due / fullfilled. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :payment_date - # The purchase order number, only if the document is an invoice. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :po_number - # The receipt number or identifier only if document is a receipt. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :receipt_number - # List of Reference numbers, including PO number, only if the document is an invoice. - # @return [Array] - attr_reader :reference_numbers - # The customer's address used for shipping. - # @return [Mindee::Parsing::Standard::AddressField] - attr_reader :shipping_address - # The purchase subcategory for transport, food and shooping. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :subcategory - # The address of the supplier or merchant. - # @return [Mindee::Parsing::Standard::AddressField] - attr_reader :supplier_address - # List of company registration numbers associated to the supplier. - # @return [Array] - attr_reader :supplier_company_registrations - # The email of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_email - # The name of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_name - # List of payment details associated to the supplier (only for invoices). - # @return [Array] - attr_reader :supplier_payment_details - # The phone number of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_phone_number - # The website URL of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_website - # List of all taxes on the document. - # @return [Mindee::Parsing::Standard::Taxes] - attr_reader :taxes - # The time the purchase was made (only for receipts). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :time - # The total amount of tip and gratuity - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :tip - # The total amount paid: includes taxes, tips, fees, and other charges. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_amount - # The net amount paid: does not include taxes, fees, and discounts. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_net - # The sum of all taxes present on the document. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_tax - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @billing_address = Parsing::Standard::AddressField.new( - prediction['billing_address'], - page_id - ) - @category = Parsing::Standard::ClassificationField.new( - prediction['category'], - page_id - ) - @customer_address = Parsing::Standard::AddressField.new( - prediction['customer_address'], - page_id - ) - @customer_company_registrations = [] # : Array[Parsing::Standard::CompanyRegistrationField] - prediction['customer_company_registrations'].each do |item| - @customer_company_registrations.push(Parsing::Standard::CompanyRegistrationField.new(item, page_id)) - end - @customer_id = Parsing::Standard::StringField.new( - prediction['customer_id'], - page_id - ) - @customer_name = Parsing::Standard::StringField.new( - prediction['customer_name'], - page_id - ) - @date = Parsing::Standard::DateField.new(prediction['date'], page_id) - @document_number = Parsing::Standard::StringField.new( - prediction['document_number'], - page_id - ) - @document_type = Parsing::Standard::ClassificationField.new( - prediction['document_type'], - page_id - ) - @document_type_extended = Parsing::Standard::ClassificationField.new( - prediction['document_type_extended'], - page_id - ) - @due_date = Parsing::Standard::DateField.new( - prediction['due_date'], - page_id - ) - @invoice_number = Parsing::Standard::StringField.new( - prediction['invoice_number'], - page_id - ) - @line_items = Product::FinancialDocument::FinancialDocumentV1LineItems.new( - prediction['line_items'], page_id - ) - @locale = Parsing::Standard::LocaleField.new( - prediction['locale'], - page_id - ) - @payment_date = Parsing::Standard::DateField.new( - prediction['payment_date'], - page_id - ) - @po_number = Parsing::Standard::StringField.new( - prediction['po_number'], - page_id - ) - @receipt_number = Parsing::Standard::StringField.new( - prediction['receipt_number'], - page_id - ) - @reference_numbers = [] # : Array[Parsing::Standard::StringField] - prediction['reference_numbers'].each do |item| - @reference_numbers.push(Parsing::Standard::StringField.new(item, page_id)) - end - @shipping_address = Parsing::Standard::AddressField.new( - prediction['shipping_address'], - page_id - ) - @subcategory = Parsing::Standard::ClassificationField.new( - prediction['subcategory'], - page_id - ) - @supplier_address = Parsing::Standard::AddressField.new( - prediction['supplier_address'], - page_id - ) - @supplier_company_registrations = [] # : Array[Parsing::Standard::CompanyRegistrationField] - prediction['supplier_company_registrations'].each do |item| - @supplier_company_registrations.push(Parsing::Standard::CompanyRegistrationField.new(item, page_id)) - end - @supplier_email = Parsing::Standard::StringField.new( - prediction['supplier_email'], - page_id - ) - @supplier_name = Parsing::Standard::StringField.new( - prediction['supplier_name'], - page_id - ) - @supplier_payment_details = [] # : Array[Parsing::Standard::PaymentDetailsField] - prediction['supplier_payment_details'].each do |item| - @supplier_payment_details.push(Parsing::Standard::PaymentDetailsField.new(item, page_id)) - end - @supplier_phone_number = Parsing::Standard::StringField.new( - prediction['supplier_phone_number'], - page_id - ) - @supplier_website = Parsing::Standard::StringField.new( - prediction['supplier_website'], - page_id - ) - @taxes = Parsing::Standard::Taxes.new(prediction['taxes'], page_id) - @time = Parsing::Standard::StringField.new(prediction['time'], page_id) - @tip = Parsing::Standard::AmountField.new(prediction['tip'], page_id) - @total_amount = Parsing::Standard::AmountField.new( - prediction['total_amount'], - page_id - ) - @total_net = Parsing::Standard::AmountField.new( - prediction['total_net'], - page_id - ) - @total_tax = Parsing::Standard::AmountField.new( - prediction['total_tax'], - page_id - ) - end - - # @return [String] - def to_s - reference_numbers = @reference_numbers.join("\n #{' ' * 19}") - supplier_payment_details = @supplier_payment_details.join("\n #{' ' * 26}") - supplier_company_registrations = @supplier_company_registrations.join("\n #{' ' * 32}") - customer_company_registrations = @customer_company_registrations.join("\n #{' ' * 32}") - line_items = line_items_to_s - out_str = String.new - out_str << "\n:Locale: #{@locale}".rstrip - out_str << "\n:Invoice Number: #{@invoice_number}".rstrip - out_str << "\n:Purchase Order Number: #{@po_number}".rstrip - out_str << "\n:Receipt Number: #{@receipt_number}".rstrip - out_str << "\n:Document Number: #{@document_number}".rstrip - out_str << "\n:Reference Numbers: #{reference_numbers}".rstrip - out_str << "\n:Purchase Date: #{@date}".rstrip - out_str << "\n:Due Date: #{@due_date}".rstrip - out_str << "\n:Payment Date: #{@payment_date}".rstrip - out_str << "\n:Total Net: #{@total_net}".rstrip - out_str << "\n:Total Amount: #{@total_amount}".rstrip - out_str << "\n:Taxes:#{@taxes}".rstrip - out_str << "\n:Supplier Payment Details: #{supplier_payment_details}".rstrip - out_str << "\n:Supplier Name: #{@supplier_name}".rstrip - out_str << "\n:Supplier Company Registrations: #{supplier_company_registrations}".rstrip - out_str << "\n:Supplier Address: #{@supplier_address}".rstrip - out_str << "\n:Supplier Phone Number: #{@supplier_phone_number}".rstrip - out_str << "\n:Customer Name: #{@customer_name}".rstrip - out_str << "\n:Supplier Website: #{@supplier_website}".rstrip - out_str << "\n:Supplier Email: #{@supplier_email}".rstrip - out_str << "\n:Customer Company Registrations: #{customer_company_registrations}".rstrip - out_str << "\n:Customer Address: #{@customer_address}".rstrip - out_str << "\n:Customer ID: #{@customer_id}".rstrip - out_str << "\n:Shipping Address: #{@shipping_address}".rstrip - out_str << "\n:Billing Address: #{@billing_address}".rstrip - out_str << "\n:Document Type: #{@document_type}".rstrip - out_str << "\n:Document Type Extended: #{@document_type_extended}".rstrip - out_str << "\n:Purchase Subcategory: #{@subcategory}".rstrip - out_str << "\n:Purchase Category: #{@category}".rstrip - out_str << "\n:Total Tax: #{@total_tax}".rstrip - out_str << "\n:Tip and Gratuity: #{@tip}".rstrip - out_str << "\n:Purchase Time: #{@time}".rstrip - out_str << "\n:Line Items:" - out_str << line_items - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def line_items_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 38}" - out_str << "+#{char * 14}" - out_str << "+#{char * 10}" - out_str << "+#{char * 12}" - out_str << "+#{char * 14}" - out_str << "+#{char * 14}" - out_str << "+#{char * 17}" - out_str << "+#{char * 12}" - out_str << '+' - out_str - end - - # @return [String] - def line_items_to_s - return '' if @line_items.empty? - - line_items = @line_items.map(&:to_table_line).join("\n#{line_items_separator('-')}\n ") - out_str = String.new - out_str << "\n#{line_items_separator('-')}" - out_str << "\n |" - out_str << ' Description |' - out_str << ' Product code |' - out_str << ' Quantity |' - out_str << ' Tax Amount |' - out_str << ' Tax Rate (%) |' - out_str << ' Total Amount |' - out_str << ' Unit of measure |' - out_str << ' Unit Price |' - out_str << "\n#{line_items_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{line_items_separator('-')}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/financial_document/financial_document_v1_line_item.rb b/lib/mindee/product/financial_document/financial_document_v1_line_item.rb deleted file mode 100644 index 6c0b6d6b9..000000000 --- a/lib/mindee/product/financial_document/financial_document_v1_line_item.rb +++ /dev/null @@ -1,121 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module FinancialDocument - # List of line item present on the document. - class FinancialDocumentV1LineItem < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The item description. - # @return [String] - attr_reader :description - # The product code referring to the item. - # @return [String] - attr_reader :product_code - # The item quantity - # @return [Float] - attr_reader :quantity - # The item tax amount. - # @return [Float] - attr_reader :tax_amount - # The item tax rate in percentage. - # @return [Float] - attr_reader :tax_rate - # The item total amount. - # @return [Float] - attr_reader :total_amount - # The item unit of measure. - # @return [String] - attr_reader :unit_measure - # The item unit price. - # @return [Float] - attr_reader :unit_price - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @description = prediction['description'] - @product_code = prediction['product_code'] - @quantity = prediction['quantity'] - @tax_amount = prediction['tax_amount'] - @tax_rate = prediction['tax_rate'] - @total_amount = prediction['total_amount'] - @unit_measure = prediction['unit_measure'] - @unit_price = prediction['unit_price'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:description] = format_for_display(@description) - printable[:product_code] = format_for_display(@product_code) - printable[:quantity] = - @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) - printable[:tax_amount] = - @tax_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_amount) - printable[:tax_rate] = - @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) - printable[:total_amount] = - @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) - printable[:unit_measure] = format_for_display(@unit_measure) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:description] = format_for_display(@description, 36) - printable[:product_code] = format_for_display(@product_code, nil) - printable[:quantity] = - @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) - printable[:tax_amount] = - @tax_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_amount) - printable[:tax_rate] = - @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) - printable[:total_amount] = - @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) - printable[:unit_measure] = format_for_display(@unit_measure, nil) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 37s', printable[:description]) - out_str << format('| %- 13s', printable[:product_code]) - out_str << format('| %- 9s', printable[:quantity]) - out_str << format('| %- 11s', printable[:tax_amount]) - out_str << format('| %- 13s', printable[:tax_rate]) - out_str << format('| %- 13s', printable[:total_amount]) - out_str << format('| %- 16s', printable[:unit_measure]) - out_str << format('| %- 11s', printable[:unit_price]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Description: #{printable[:description]}" - out_str << "\n :Product code: #{printable[:product_code]}" - out_str << "\n :Quantity: #{printable[:quantity]}" - out_str << "\n :Tax Amount: #{printable[:tax_amount]}" - out_str << "\n :Tax Rate (%): #{printable[:tax_rate]}" - out_str << "\n :Total Amount: #{printable[:total_amount]}" - out_str << "\n :Unit of measure: #{printable[:unit_measure]}" - out_str << "\n :Unit Price: #{printable[:unit_price]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/financial_document/financial_document_v1_line_items.rb b/lib/mindee/product/financial_document/financial_document_v1_line_items.rb deleted file mode 100644 index c6e19c14d..000000000 --- a/lib/mindee/product/financial_document/financial_document_v1_line_items.rb +++ /dev/null @@ -1,62 +0,0 @@ -# frozen_string_literal: true - -require_relative 'financial_document_v1_line_item' - -module Mindee - module Product - module FinancialDocument - # List of line item present on the document. - class FinancialDocumentV1LineItems < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - FinancialDocument::FinancialDocumentV1LineItem.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 38}" - out_str << "+#{char * 14}" - out_str << "+#{char * 10}" - out_str << "+#{char * 12}" - out_str << "+#{char * 14}" - out_str << "+#{char * 14}" - out_str << "+#{char * 17}" - out_str << "+#{char * 12}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Description ' - out_str << ' | Product code' - out_str << ' | Quantity' - out_str << ' | Tax Amount' - out_str << ' | Tax Rate (%)' - out_str << ' | Total Amount' - out_str << ' | Unit of measure' - out_str << ' | Unit Price' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/financial_document/financial_document_v1_page.rb b/lib/mindee/product/financial_document/financial_document_v1_page.rb deleted file mode 100644 index 929826d13..000000000 --- a/lib/mindee/product/financial_document/financial_document_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'financial_document_v1_document' - -module Mindee - module Product - module FinancialDocument - # Financial Document API version 1.14 page data. - class FinancialDocumentV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - FinancialDocumentV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Financial Document V1 page prediction. - class FinancialDocumentV1PagePrediction < FinancialDocumentV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/fr/bank_account_details/bank_account_details_v1_document.rb b/lib/mindee/product/fr/bank_account_details/bank_account_details_v1_document.rb deleted file mode 100644 index d26750204..000000000 --- a/lib/mindee/product/fr/bank_account_details/bank_account_details_v1_document.rb +++ /dev/null @@ -1,46 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module BankAccountDetails - # Bank Account Details API version 1.0 document data. - class BankAccountDetailsV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The name of the account holder as seen on the document. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :account_holder_name - # The International Bank Account Number (IBAN). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :iban - # The bank's SWIFT Business Identifier Code (BIC). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :swift - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @account_holder_name = Parsing::Standard::StringField.new( - prediction['account_holder_name'], - page_id - ) - @iban = Parsing::Standard::StringField.new(prediction['iban'], page_id) - @swift = Parsing::Standard::StringField.new(prediction['swift'], page_id) - end - - # @return [String] - def to_s - out_str = String.new - out_str << "\n:IBAN: #{@iban}".rstrip - out_str << "\n:Account Holder's Name: #{@account_holder_name}".rstrip - out_str << "\n:SWIFT Code: #{@swift}".rstrip - out_str[1..].to_s - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/bank_account_details/bank_account_details_v2.rb b/lib/mindee/product/fr/bank_account_details/bank_account_details_v2.rb deleted file mode 100644 index b2f0465f0..000000000 --- a/lib/mindee/product/fr/bank_account_details/bank_account_details_v2.rb +++ /dev/null @@ -1,47 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'bank_account_details_v2_document' -require_relative 'bank_account_details_v2_page' - -module Mindee - module Product - module FR - # Bank Account Details module. - module BankAccountDetails - # Bank Account Details API version 2 inference prediction. - class BankAccountDetailsV2 < Mindee::Parsing::Common::Inference - @endpoint_name = 'bank_account_details' - @endpoint_version = '2' - @has_async = false - @has_sync = true - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = BankAccountDetailsV2Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(BankAccountDetailsV2Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/bank_account_details/bank_account_details_v2_bban.rb b/lib/mindee/product/fr/bank_account_details/bank_account_details_v2_bban.rb deleted file mode 100644 index 387fd3063..000000000 --- a/lib/mindee/product/fr/bank_account_details/bank_account_details_v2_bban.rb +++ /dev/null @@ -1,60 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module BankAccountDetails - # Full extraction of BBAN, including: branch code, bank code, account and key. - class BankAccountDetailsV2Bban < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The BBAN bank code outputted as a string. - # @return [String] - attr_reader :bban_bank_code - # The BBAN branch code outputted as a string. - # @return [String] - attr_reader :bban_branch_code - # The BBAN key outputted as a string. - # @return [String] - attr_reader :bban_key - # The BBAN Account number outputted as a string. - # @return [String] - attr_reader :bban_number - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @bban_bank_code = prediction['bban_bank_code'] - @bban_branch_code = prediction['bban_branch_code'] - @bban_key = prediction['bban_key'] - @bban_number = prediction['bban_number'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:bban_bank_code] = format_for_display(@bban_bank_code) - printable[:bban_branch_code] = format_for_display(@bban_branch_code) - printable[:bban_key] = format_for_display(@bban_key) - printable[:bban_number] = format_for_display(@bban_number) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Bank Code: #{printable[:bban_bank_code]}" - out_str << "\n :Branch Code: #{printable[:bban_branch_code]}" - out_str << "\n :Key: #{printable[:bban_key]}" - out_str << "\n :Account Number: #{printable[:bban_number]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/bank_account_details/bank_account_details_v2_document.rb b/lib/mindee/product/fr/bank_account_details/bank_account_details_v2_document.rb deleted file mode 100644 index aee8f8501..000000000 --- a/lib/mindee/product/fr/bank_account_details/bank_account_details_v2_document.rb +++ /dev/null @@ -1,57 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'bank_account_details_v2_bban' - -module Mindee - module Product - module FR - module BankAccountDetails - # Bank Account Details API version 2.0 document data. - class BankAccountDetailsV2Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # Full extraction of the account holders names. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :account_holders_names - # Full extraction of BBAN, including: branch code, bank code, account and key. - # @return [Mindee::Product::FR::BankAccountDetails::BankAccountDetailsV2Bban] - attr_reader :bban - # Full extraction of the IBAN number. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :iban - # Full extraction of the SWIFT code. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :swift_code - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @account_holders_names = Parsing::Standard::StringField.new( - prediction['account_holders_names'], - page_id - ) - @bban = Product::FR::BankAccountDetails::BankAccountDetailsV2Bban.new(prediction['bban'], page_id) - @iban = Parsing::Standard::StringField.new(prediction['iban'], page_id) - @swift_code = Parsing::Standard::StringField.new( - prediction['swift_code'], - page_id - ) - end - - # @return [String] - def to_s - bban = @bban.to_s - out_str = String.new - out_str << "\n:Account Holder's Names: #{@account_holders_names}".rstrip - out_str << "\n:Basic Bank Account Number:" - out_str << bban - out_str << "\n:IBAN: #{@iban}".rstrip - out_str << "\n:SWIFT Code: #{@swift_code}".rstrip - out_str[1..].to_s - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/bank_account_details/bank_account_details_v2_page.rb b/lib/mindee/product/fr/bank_account_details/bank_account_details_v2_page.rb deleted file mode 100644 index 7e835e3cb..000000000 --- a/lib/mindee/product/fr/bank_account_details/bank_account_details_v2_page.rb +++ /dev/null @@ -1,38 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'bank_account_details_v2_document' - -module Mindee - module Product - module FR - module BankAccountDetails - # Bank Account Details API version 2.0 page data. - class BankAccountDetailsV2Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - BankAccountDetailsV2PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Bank Account Details V2 page prediction. - class BankAccountDetailsV2PagePrediction < BankAccountDetailsV2Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/bank_statement/bank_statement_v2_document.rb b/lib/mindee/product/fr/bank_statement/bank_statement_v2_document.rb deleted file mode 100644 index 21f0490b4..000000000 --- a/lib/mindee/product/fr/bank_statement/bank_statement_v2_document.rb +++ /dev/null @@ -1,166 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'bank_statement_v2_transactions' - -module Mindee - module Product - module FR - module BankStatement - # Bank Statement API version 2.0 document data. - class BankStatementV2Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The unique identifier for a customer's account in the bank's system. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :account_number - # The physical location of the bank where the statement was issued. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :bank_address - # The name of the bank that issued the statement. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :bank_name - # The address of the client associated with the bank statement. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :client_address - # The name of the clients who own the bank statement. - # @return [Array] - attr_reader :client_names - # The final amount of money in the account at the end of the statement period. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :closing_balance - # The initial amount of money in an account at the start of the period. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :opening_balance - # The date on which the bank statement was generated. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :statement_date - # The date when the statement period ends. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :statement_end_date - # The date when the bank statement period begins. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :statement_start_date - # The total amount of money deposited into the account. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_credits - # The total amount of money debited from the account. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_debits - # The list of values that represent the financial transactions recorded in a bank statement. - # @return [Mindee::Product::FR::BankStatement::BankStatementV2Transactions] - attr_reader :transactions - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @account_number = Parsing::Standard::StringField.new( - prediction['account_number'], - page_id - ) - @bank_address = Parsing::Standard::StringField.new( - prediction['bank_address'], - page_id - ) - @bank_name = Parsing::Standard::StringField.new( - prediction['bank_name'], - page_id - ) - @client_address = Parsing::Standard::StringField.new( - prediction['client_address'], - page_id - ) - @client_names = [] # : Array[Parsing::Standard::StringField] - prediction['client_names'].each do |item| - @client_names.push(Parsing::Standard::StringField.new(item, page_id)) - end - @closing_balance = Parsing::Standard::AmountField.new( - prediction['closing_balance'], - page_id - ) - @opening_balance = Parsing::Standard::AmountField.new( - prediction['opening_balance'], - page_id - ) - @statement_date = Parsing::Standard::DateField.new( - prediction['statement_date'], - page_id - ) - @statement_end_date = Parsing::Standard::DateField.new( - prediction['statement_end_date'], - page_id - ) - @statement_start_date = Parsing::Standard::DateField.new( - prediction['statement_start_date'], - page_id - ) - @total_credits = Parsing::Standard::AmountField.new( - prediction['total_credits'], - page_id - ) - @total_debits = Parsing::Standard::AmountField.new( - prediction['total_debits'], - page_id - ) - @transactions = Product::FR::BankStatement::BankStatementV2Transactions.new( - prediction['transactions'], page_id - ) - end - - # @return [String] - def to_s - client_names = @client_names.join("\n #{' ' * 14}") - transactions = transactions_to_s - out_str = String.new - out_str << "\n:Account Number: #{@account_number}".rstrip - out_str << "\n:Bank Name: #{@bank_name}".rstrip - out_str << "\n:Bank Address: #{@bank_address}".rstrip - out_str << "\n:Client Names: #{client_names}".rstrip - out_str << "\n:Client Address: #{@client_address}".rstrip - out_str << "\n:Statement Date: #{@statement_date}".rstrip - out_str << "\n:Statement Start Date: #{@statement_start_date}".rstrip - out_str << "\n:Statement End Date: #{@statement_end_date}".rstrip - out_str << "\n:Opening Balance: #{@opening_balance}".rstrip - out_str << "\n:Closing Balance: #{@closing_balance}".rstrip - out_str << "\n:Transactions:" - out_str << transactions - out_str << "\n:Total Debits: #{@total_debits}".rstrip - out_str << "\n:Total Credits: #{@total_credits}".rstrip - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def transactions_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 12}" - out_str << "+#{char * 12}" - out_str << "+#{char * 38}" - out_str << '+' - out_str - end - - # @return [String] - def transactions_to_s - return '' if @transactions.empty? - - line_items = @transactions.map(&:to_table_line).join("\n#{transactions_separator('-')}\n ") - out_str = String.new - out_str << "\n#{transactions_separator('-')}" - out_str << "\n |" - out_str << ' Amount |' - out_str << ' Date |' - out_str << ' Description |' - out_str << "\n#{transactions_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{transactions_separator('-')}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/bank_statement/bank_statement_v2_transaction.rb b/lib/mindee/product/fr/bank_statement/bank_statement_v2_transaction.rb deleted file mode 100644 index a75bb208c..000000000 --- a/lib/mindee/product/fr/bank_statement/bank_statement_v2_transaction.rb +++ /dev/null @@ -1,75 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module BankStatement - # The list of values that represent the financial transactions recorded in a bank statement. - class BankStatementV2Transaction < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The monetary amount of the transaction. - # @return [Float] - attr_reader :amount - # The date on which the transaction occurred. - # @return [String] - attr_reader :date - # The additional information about the transaction. - # @return [String] - attr_reader :description - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @amount = prediction['amount'] - @date = prediction['date'] - @description = prediction['description'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:amount] = - @amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@amount) - printable[:date] = format_for_display(@date) - printable[:description] = format_for_display(@description) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:amount] = - @amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@amount) - printable[:date] = format_for_display(@date, 10) - printable[:description] = format_for_display(@description, 36) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 11s', printable[:amount]) - out_str << format('| %- 11s', printable[:date]) - out_str << format('| %- 37s', printable[:description]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Amount: #{printable[:amount]}" - out_str << "\n :Date: #{printable[:date]}" - out_str << "\n :Description: #{printable[:description]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/carte_grise/carte_grise_v1_document.rb b/lib/mindee/product/fr/carte_grise/carte_grise_v1_document.rb deleted file mode 100644 index 20f5c7123..000000000 --- a/lib/mindee/product/fr/carte_grise/carte_grise_v1_document.rb +++ /dev/null @@ -1,242 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module CarteGrise - # Carte Grise API version 1.1 document data. - class CarteGriseV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The vehicle's license plate number. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :a - # The vehicle's first release date. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :b - # The vehicle owner's full name including maiden name. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :c1 - # The vehicle owner's address. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :c3 - # Number of owners of the license certificate. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :c41 - # Mentions about the ownership of the vehicle. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :c4a - # The vehicle's brand. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :d1 - # The vehicle's commercial name. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :d3 - # The Vehicle Identification Number (VIN). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :e - # The vehicle's maximum admissible weight. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :f1 - # The vehicle's maximum admissible weight within the license's state. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :f2 - # The vehicle's maximum authorized weight with coupling. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :f3 - # The document's formula number. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :formula_number - # The vehicle's weight with coupling if tractor different than category M1. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :g - # The vehicle's national empty weight. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :g1 - # The car registration date of the given certificate. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :i - # The vehicle's category. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :j - # The vehicle's national type. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :j1 - # The vehicle's body type (CE). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :j2 - # The vehicle's body type (National designation). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :j3 - # Machine Readable Zone, first line. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz1 - # Machine Readable Zone, second line. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz2 - # The vehicle's owner first name. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :owner_first_name - # The vehicle's owner surname. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :owner_surname - # The vehicle engine's displacement (cm3). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :p1 - # The vehicle's maximum net power (kW). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :p2 - # The vehicle's fuel type or energy source. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :p3 - # The vehicle's administrative power (fiscal horsepower). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :p6 - # The vehicle's power to weight ratio. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :q - # The vehicle's number of seats. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :s1 - # The vehicle's number of standing rooms (person). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :s2 - # The vehicle's sound level (dB). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :u1 - # The vehicle engine's rotation speed (RPM). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :u2 - # The vehicle's CO2 emission (g/km). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :v7 - # Next technical control date. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :x1 - # Amount of the regional proportional tax of the registration (in euros). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :y1 - # Amount of the additional parafiscal tax of the registration (in euros). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :y2 - # Amount of the additional CO2 tax of the registration (in euros). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :y3 - # Amount of the fee for managing the registration (in euros). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :y4 - # Amount of the fee for delivery of the registration certificate in euros. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :y5 - # Total amount of registration fee to be paid in euros. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :y6 - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @a = Parsing::Standard::StringField.new(prediction['a'], page_id) - @b = Parsing::Standard::DateField.new(prediction['b'], page_id) - @c1 = Parsing::Standard::StringField.new(prediction['c1'], page_id) - @c3 = Parsing::Standard::StringField.new(prediction['c3'], page_id) - @c41 = Parsing::Standard::StringField.new(prediction['c41'], page_id) - @c4a = Parsing::Standard::StringField.new(prediction['c4a'], page_id) - @d1 = Parsing::Standard::StringField.new(prediction['d1'], page_id) - @d3 = Parsing::Standard::StringField.new(prediction['d3'], page_id) - @e = Parsing::Standard::StringField.new(prediction['e'], page_id) - @f1 = Parsing::Standard::StringField.new(prediction['f1'], page_id) - @f2 = Parsing::Standard::StringField.new(prediction['f2'], page_id) - @f3 = Parsing::Standard::StringField.new(prediction['f3'], page_id) - @formula_number = Parsing::Standard::StringField.new( - prediction['formula_number'], - page_id - ) - @g = Parsing::Standard::StringField.new(prediction['g'], page_id) - @g1 = Parsing::Standard::StringField.new(prediction['g1'], page_id) - @i = Parsing::Standard::DateField.new(prediction['i'], page_id) - @j = Parsing::Standard::StringField.new(prediction['j'], page_id) - @j1 = Parsing::Standard::StringField.new(prediction['j1'], page_id) - @j2 = Parsing::Standard::StringField.new(prediction['j2'], page_id) - @j3 = Parsing::Standard::StringField.new(prediction['j3'], page_id) - @mrz1 = Parsing::Standard::StringField.new(prediction['mrz1'], page_id) - @mrz2 = Parsing::Standard::StringField.new(prediction['mrz2'], page_id) - @owner_first_name = Parsing::Standard::StringField.new( - prediction['owner_first_name'], - page_id - ) - @owner_surname = Parsing::Standard::StringField.new( - prediction['owner_surname'], - page_id - ) - @p1 = Parsing::Standard::StringField.new(prediction['p1'], page_id) - @p2 = Parsing::Standard::StringField.new(prediction['p2'], page_id) - @p3 = Parsing::Standard::StringField.new(prediction['p3'], page_id) - @p6 = Parsing::Standard::StringField.new(prediction['p6'], page_id) - @q = Parsing::Standard::StringField.new(prediction['q'], page_id) - @s1 = Parsing::Standard::StringField.new(prediction['s1'], page_id) - @s2 = Parsing::Standard::StringField.new(prediction['s2'], page_id) - @u1 = Parsing::Standard::StringField.new(prediction['u1'], page_id) - @u2 = Parsing::Standard::StringField.new(prediction['u2'], page_id) - @v7 = Parsing::Standard::StringField.new(prediction['v7'], page_id) - @x1 = Parsing::Standard::StringField.new(prediction['x1'], page_id) - @y1 = Parsing::Standard::StringField.new(prediction['y1'], page_id) - @y2 = Parsing::Standard::StringField.new(prediction['y2'], page_id) - @y3 = Parsing::Standard::StringField.new(prediction['y3'], page_id) - @y4 = Parsing::Standard::StringField.new(prediction['y4'], page_id) - @y5 = Parsing::Standard::StringField.new(prediction['y5'], page_id) - @y6 = Parsing::Standard::StringField.new(prediction['y6'], page_id) - end - - # @return [String] - def to_s - out_str = String.new - out_str << "\n:a: #{@a}".rstrip - out_str << "\n:b: #{@b}".rstrip - out_str << "\n:c1: #{@c1}".rstrip - out_str << "\n:c3: #{@c3}".rstrip - out_str << "\n:c41: #{@c41}".rstrip - out_str << "\n:c4a: #{@c4a}".rstrip - out_str << "\n:d1: #{@d1}".rstrip - out_str << "\n:d3: #{@d3}".rstrip - out_str << "\n:e: #{@e}".rstrip - out_str << "\n:f1: #{@f1}".rstrip - out_str << "\n:f2: #{@f2}".rstrip - out_str << "\n:f3: #{@f3}".rstrip - out_str << "\n:g: #{@g}".rstrip - out_str << "\n:g1: #{@g1}".rstrip - out_str << "\n:i: #{@i}".rstrip - out_str << "\n:j: #{@j}".rstrip - out_str << "\n:j1: #{@j1}".rstrip - out_str << "\n:j2: #{@j2}".rstrip - out_str << "\n:j3: #{@j3}".rstrip - out_str << "\n:p1: #{@p1}".rstrip - out_str << "\n:p2: #{@p2}".rstrip - out_str << "\n:p3: #{@p3}".rstrip - out_str << "\n:p6: #{@p6}".rstrip - out_str << "\n:q: #{@q}".rstrip - out_str << "\n:s1: #{@s1}".rstrip - out_str << "\n:s2: #{@s2}".rstrip - out_str << "\n:u1: #{@u1}".rstrip - out_str << "\n:u2: #{@u2}".rstrip - out_str << "\n:v7: #{@v7}".rstrip - out_str << "\n:x1: #{@x1}".rstrip - out_str << "\n:y1: #{@y1}".rstrip - out_str << "\n:y2: #{@y2}".rstrip - out_str << "\n:y3: #{@y3}".rstrip - out_str << "\n:y4: #{@y4}".rstrip - out_str << "\n:y5: #{@y5}".rstrip - out_str << "\n:y6: #{@y6}".rstrip - out_str << "\n:Formula Number: #{@formula_number}".rstrip - out_str << "\n:Owner's First Name: #{@owner_first_name}".rstrip - out_str << "\n:Owner's Surname: #{@owner_surname}".rstrip - out_str << "\n:MRZ Line 1: #{@mrz1}".rstrip - out_str << "\n:MRZ Line 2: #{@mrz2}".rstrip - out_str[1..].to_s - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_document.rb b/lib/mindee/product/fr/energy_bill/energy_bill_v1_document.rb deleted file mode 100644 index ce46201d8..000000000 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_document.rb +++ /dev/null @@ -1,265 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'energy_bill_v1_energy_supplier' -require_relative 'energy_bill_v1_energy_consumer' -require_relative 'energy_bill_v1_subscriptions' -require_relative 'energy_bill_v1_energy_usages' -require_relative 'energy_bill_v1_taxes_and_contributions' -require_relative 'energy_bill_v1_meter_detail' - -module Mindee - module Product - module FR - module EnergyBill - # Energy Bill API version 1.2 document data. - class EnergyBillV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The unique identifier associated with a specific contract. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :contract_id - # The unique identifier assigned to each electricity or gas consumption point. It specifies the exact - # location where the energy is delivered. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :delivery_point - # The date by which the payment for the energy invoice is due. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :due_date - # The entity that consumes the energy. - # @return [Mindee::Product::FR::EnergyBill::EnergyBillV1EnergyConsumer] - attr_reader :energy_consumer - # The company that supplies the energy. - # @return [Mindee::Product::FR::EnergyBill::EnergyBillV1EnergySupplier] - attr_reader :energy_supplier - # Details of energy consumption. - # @return [Mindee::Product::FR::EnergyBill::EnergyBillV1EnergyUsages] - attr_reader :energy_usage - # The date when the energy invoice was issued. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :invoice_date - # The unique identifier of the energy invoice. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :invoice_number - # Information about the energy meter. - # @return [Mindee::Product::FR::EnergyBill::EnergyBillV1MeterDetail] - attr_reader :meter_details - # The subscription details fee for the energy service. - # @return [Mindee::Product::FR::EnergyBill::EnergyBillV1Subscriptions] - attr_reader :subscription - # Details of Taxes and Contributions. - # @return [Mindee::Product::FR::EnergyBill::EnergyBillV1TaxesAndContributions] - attr_reader :taxes_and_contributions - # The total amount to be paid for the energy invoice. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_amount - # The total amount to be paid for the energy invoice before taxes. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_before_taxes - # Total of taxes applied to the invoice. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_taxes - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @contract_id = Parsing::Standard::StringField.new( - prediction['contract_id'], - page_id - ) - @delivery_point = Parsing::Standard::StringField.new( - prediction['delivery_point'], - page_id - ) - @due_date = Parsing::Standard::DateField.new( - prediction['due_date'], - page_id - ) - @energy_consumer = Product::FR::EnergyBill::EnergyBillV1EnergyConsumer.new( - prediction['energy_consumer'], - page_id - ) - @energy_supplier = Product::FR::EnergyBill::EnergyBillV1EnergySupplier.new( - prediction['energy_supplier'], - page_id - ) - @energy_usage = Product::FR::EnergyBill::EnergyBillV1EnergyUsages.new(prediction['energy_usage'], page_id) - @invoice_date = Parsing::Standard::DateField.new( - prediction['invoice_date'], - page_id - ) - @invoice_number = Parsing::Standard::StringField.new( - prediction['invoice_number'], - page_id - ) - @meter_details = Product::FR::EnergyBill::EnergyBillV1MeterDetail.new( - prediction['meter_details'], - page_id - ) - @subscription = Product::FR::EnergyBill::EnergyBillV1Subscriptions.new(prediction['subscription'], page_id) - @taxes_and_contributions = Product::FR::EnergyBill::EnergyBillV1TaxesAndContributions.new( - prediction['taxes_and_contributions'], page_id - ) - @total_amount = Parsing::Standard::AmountField.new( - prediction['total_amount'], - page_id - ) - @total_before_taxes = Parsing::Standard::AmountField.new( - prediction['total_before_taxes'], - page_id - ) - @total_taxes = Parsing::Standard::AmountField.new( - prediction['total_taxes'], - page_id - ) - end - - # @return [String] - def to_s - energy_supplier = @energy_supplier.to_s - energy_consumer = @energy_consumer.to_s - subscription = subscription_to_s - energy_usage = energy_usage_to_s - taxes_and_contributions = taxes_and_contributions_to_s - meter_details = @meter_details.to_s - out_str = String.new - out_str << "\n:Invoice Number: #{@invoice_number}".rstrip - out_str << "\n:Contract ID: #{@contract_id}".rstrip - out_str << "\n:Delivery Point: #{@delivery_point}".rstrip - out_str << "\n:Invoice Date: #{@invoice_date}".rstrip - out_str << "\n:Due Date: #{@due_date}".rstrip - out_str << "\n:Total Before Taxes: #{@total_before_taxes}".rstrip - out_str << "\n:Total Taxes: #{@total_taxes}".rstrip - out_str << "\n:Total Amount: #{@total_amount}".rstrip - out_str << "\n:Energy Supplier:" - out_str << energy_supplier - out_str << "\n:Energy Consumer:" - out_str << energy_consumer - out_str << "\n:Subscription:" - out_str << subscription - out_str << "\n:Energy Usage:" - out_str << energy_usage - out_str << "\n:Taxes and Contributions:" - out_str << taxes_and_contributions - out_str << "\n:Meter Details:" - out_str << meter_details - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def subscription_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 38}" - out_str << "+#{char * 12}" - out_str << "+#{char * 12}" - out_str << "+#{char * 10}" - out_str << "+#{char * 11}" - out_str << "+#{char * 12}" - out_str << '+' - out_str - end - - # @return [String] - def subscription_to_s - return '' if @subscription.empty? - - line_items = @subscription.map(&:to_table_line).join("\n#{subscription_separator('-')}\n ") - out_str = String.new - out_str << "\n#{subscription_separator('-')}" - out_str << "\n |" - out_str << ' Description |' - out_str << ' End Date |' - out_str << ' Start Date |' - out_str << ' Tax Rate |' - out_str << ' Total |' - out_str << ' Unit Price |' - out_str << "\n#{subscription_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{subscription_separator('-')}" - out_str - end - - # @param char [String] - # @return [String] - def energy_usage_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 13}" - out_str << "+#{char * 38}" - out_str << "+#{char * 12}" - out_str << "+#{char * 12}" - out_str << "+#{char * 10}" - out_str << "+#{char * 11}" - out_str << "+#{char * 17}" - out_str << "+#{char * 12}" - out_str << '+' - out_str - end - - # @return [String] - def energy_usage_to_s - return '' if @energy_usage.empty? - - line_items = @energy_usage.map(&:to_table_line).join("\n#{energy_usage_separator('-')}\n ") - out_str = String.new - out_str << "\n#{energy_usage_separator('-')}" - out_str << "\n |" - out_str << ' Consumption |' - out_str << ' Description |' - out_str << ' End Date |' - out_str << ' Start Date |' - out_str << ' Tax Rate |' - out_str << ' Total |' - out_str << ' Unit of Measure |' - out_str << ' Unit Price |' - out_str << "\n#{energy_usage_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{energy_usage_separator('-')}" - out_str - end - - # @param char [String] - # @return [String] - def taxes_and_contributions_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 38}" - out_str << "+#{char * 12}" - out_str << "+#{char * 12}" - out_str << "+#{char * 10}" - out_str << "+#{char * 11}" - out_str << "+#{char * 12}" - out_str << '+' - out_str - end - - # @return [String] - def taxes_and_contributions_to_s - return '' if @taxes_and_contributions.empty? - - line_items = @taxes_and_contributions.map(&:to_table_line).join( - "\n#{taxes_and_contributions_separator('-')}\n " - ) - out_str = String.new - out_str << "\n#{taxes_and_contributions_separator('-')}" - out_str << "\n |" - out_str << ' Description |' - out_str << ' End Date |' - out_str << ' Start Date |' - out_str << ' Tax Rate |' - out_str << ' Total |' - out_str << ' Unit Price |' - out_str << "\n#{taxes_and_contributions_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{taxes_and_contributions_separator('-')}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_consumer.rb b/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_consumer.rb deleted file mode 100644 index 6d6ce2f51..000000000 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_consumer.rb +++ /dev/null @@ -1,48 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module EnergyBill - # The entity that consumes the energy. - class EnergyBillV1EnergyConsumer < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The address of the energy consumer. - # @return [String] - attr_reader :address - # The name of the energy consumer. - # @return [String] - attr_reader :name - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address = prediction['address'] - @name = prediction['name'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:address] = format_for_display(@address) - printable[:name] = format_for_display(@name) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Address: #{printable[:address]}" - out_str << "\n :Name: #{printable[:name]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_supplier.rb b/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_supplier.rb deleted file mode 100644 index 6bf004f70..000000000 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_supplier.rb +++ /dev/null @@ -1,48 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module EnergyBill - # The company that supplies the energy. - class EnergyBillV1EnergySupplier < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The address of the energy supplier. - # @return [String] - attr_reader :address - # The name of the energy supplier. - # @return [String] - attr_reader :name - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address = prediction['address'] - @name = prediction['name'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:address] = format_for_display(@address) - printable[:name] = format_for_display(@name) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Address: #{printable[:address]}" - out_str << "\n :Name: #{printable[:name]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_usage.rb b/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_usage.rb deleted file mode 100644 index 29b6ce5fd..000000000 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_usage.rb +++ /dev/null @@ -1,121 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module EnergyBill - # Details of energy consumption. - class EnergyBillV1EnergyUsage < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The price per unit of energy consumed. - # @return [Float] - attr_reader :consumption - # Description or details of the energy usage. - # @return [String] - attr_reader :description - # The end date of the energy usage. - # @return [String] - attr_reader :end_date - # The start date of the energy usage. - # @return [String] - attr_reader :start_date - # The rate of tax applied to the total cost. - # @return [Float] - attr_reader :tax_rate - # The total cost of energy consumed. - # @return [Float] - attr_reader :total - # The unit of measurement for energy consumption. - # @return [String] - attr_reader :unit - # The price per unit of energy consumed. - # @return [Float] - attr_reader :unit_price - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @consumption = prediction['consumption'] - @description = prediction['description'] - @end_date = prediction['end_date'] - @start_date = prediction['start_date'] - @tax_rate = prediction['tax_rate'] - @total = prediction['total'] - @unit = prediction['unit'] - @unit_price = prediction['unit_price'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:consumption] = - @consumption.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@consumption) - printable[:description] = format_for_display(@description) - printable[:end_date] = format_for_display(@end_date) - printable[:start_date] = format_for_display(@start_date) - printable[:tax_rate] = - @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) - printable[:total] = - @total.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total) - printable[:unit] = format_for_display(@unit) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:consumption] = - @consumption.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@consumption) - printable[:description] = format_for_display(@description, 36) - printable[:end_date] = format_for_display(@end_date, 10) - printable[:start_date] = format_for_display(@start_date, nil) - printable[:tax_rate] = - @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) - printable[:total] = - @total.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total) - printable[:unit] = format_for_display(@unit, nil) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 12s', printable[:consumption]) - out_str << format('| %- 37s', printable[:description]) - out_str << format('| %- 11s', printable[:end_date]) - out_str << format('| %- 11s', printable[:start_date]) - out_str << format('| %- 9s', printable[:tax_rate]) - out_str << format('| %- 10s', printable[:total]) - out_str << format('| %- 16s', printable[:unit]) - out_str << format('| %- 11s', printable[:unit_price]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Consumption: #{printable[:consumption]}" - out_str << "\n :Description: #{printable[:description]}" - out_str << "\n :End Date: #{printable[:end_date]}" - out_str << "\n :Start Date: #{printable[:start_date]}" - out_str << "\n :Tax Rate: #{printable[:tax_rate]}" - out_str << "\n :Total: #{printable[:total]}" - out_str << "\n :Unit of Measure: #{printable[:unit]}" - out_str << "\n :Unit Price: #{printable[:unit_price]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_meter_detail.rb b/lib/mindee/product/fr/energy_bill/energy_bill_v1_meter_detail.rb deleted file mode 100644 index a59c42876..000000000 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_meter_detail.rb +++ /dev/null @@ -1,54 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module EnergyBill - # Information about the energy meter. - class EnergyBillV1MeterDetail < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The unique identifier of the energy meter. - # @return [String] - attr_reader :meter_number - # The type of energy meter. - # @return [String] - attr_reader :meter_type - # The unit of power for energy consumption. - # @return [String] - attr_reader :unit - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @meter_number = prediction['meter_number'] - @meter_type = prediction['meter_type'] - @unit = prediction['unit'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:meter_number] = format_for_display(@meter_number) - printable[:meter_type] = format_for_display(@meter_type) - printable[:unit] = format_for_display(@unit) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Meter Number: #{printable[:meter_number]}" - out_str << "\n :Meter Type: #{printable[:meter_type]}" - out_str << "\n :Unit of Power: #{printable[:unit]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_subscription.rb b/lib/mindee/product/fr/energy_bill/energy_bill_v1_subscription.rb deleted file mode 100644 index f34fe4640..000000000 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_subscription.rb +++ /dev/null @@ -1,103 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module EnergyBill - # The subscription details fee for the energy service. - class EnergyBillV1Subscription < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # Description or details of the subscription. - # @return [String] - attr_reader :description - # The end date of the subscription. - # @return [String] - attr_reader :end_date - # The start date of the subscription. - # @return [String] - attr_reader :start_date - # The rate of tax applied to the total cost. - # @return [Float] - attr_reader :tax_rate - # The total cost of subscription. - # @return [Float] - attr_reader :total - # The price per unit of subscription. - # @return [Float] - attr_reader :unit_price - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @description = prediction['description'] - @end_date = prediction['end_date'] - @start_date = prediction['start_date'] - @tax_rate = prediction['tax_rate'] - @total = prediction['total'] - @unit_price = prediction['unit_price'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:description] = format_for_display(@description) - printable[:end_date] = format_for_display(@end_date) - printable[:start_date] = format_for_display(@start_date) - printable[:tax_rate] = - @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) - printable[:total] = - @total.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:description] = format_for_display(@description, 36) - printable[:end_date] = format_for_display(@end_date, 10) - printable[:start_date] = format_for_display(@start_date, nil) - printable[:tax_rate] = - @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) - printable[:total] = - @total.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 37s', printable[:description]) - out_str << format('| %- 11s', printable[:end_date]) - out_str << format('| %- 11s', printable[:start_date]) - out_str << format('| %- 9s', printable[:tax_rate]) - out_str << format('| %- 10s', printable[:total]) - out_str << format('| %- 11s', printable[:unit_price]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Description: #{printable[:description]}" - out_str << "\n :End Date: #{printable[:end_date]}" - out_str << "\n :Start Date: #{printable[:start_date]}" - out_str << "\n :Tax Rate: #{printable[:tax_rate]}" - out_str << "\n :Total: #{printable[:total]}" - out_str << "\n :Unit Price: #{printable[:unit_price]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contribution.rb b/lib/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contribution.rb deleted file mode 100644 index 64fbe2395..000000000 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contribution.rb +++ /dev/null @@ -1,103 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module EnergyBill - # Details of Taxes and Contributions. - class EnergyBillV1TaxesAndContribution < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # Description or details of the Taxes and Contributions. - # @return [String] - attr_reader :description - # The end date of the Taxes and Contributions. - # @return [String] - attr_reader :end_date - # The start date of the Taxes and Contributions. - # @return [String] - attr_reader :start_date - # The rate of tax applied to the total cost. - # @return [Float] - attr_reader :tax_rate - # The total cost of Taxes and Contributions. - # @return [Float] - attr_reader :total - # The price per unit of Taxes and Contributions. - # @return [Float] - attr_reader :unit_price - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @description = prediction['description'] - @end_date = prediction['end_date'] - @start_date = prediction['start_date'] - @tax_rate = prediction['tax_rate'] - @total = prediction['total'] - @unit_price = prediction['unit_price'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:description] = format_for_display(@description) - printable[:end_date] = format_for_display(@end_date) - printable[:start_date] = format_for_display(@start_date) - printable[:tax_rate] = - @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) - printable[:total] = - @total.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:description] = format_for_display(@description, 36) - printable[:end_date] = format_for_display(@end_date, 10) - printable[:start_date] = format_for_display(@start_date, nil) - printable[:tax_rate] = - @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) - printable[:total] = - @total.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 37s', printable[:description]) - out_str << format('| %- 11s', printable[:end_date]) - out_str << format('| %- 11s', printable[:start_date]) - out_str << format('| %- 9s', printable[:tax_rate]) - out_str << format('| %- 10s', printable[:total]) - out_str << format('| %- 11s', printable[:unit_price]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Description: #{printable[:description]}" - out_str << "\n :End Date: #{printable[:end_date]}" - out_str << "\n :Start Date: #{printable[:start_date]}" - out_str << "\n :Tax Rate: #{printable[:tax_rate]}" - out_str << "\n :Total: #{printable[:total]}" - out_str << "\n :Unit Price: #{printable[:unit_price]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/health_card/health_card_v1_document.rb b/lib/mindee/product/fr/health_card/health_card_v1_document.rb deleted file mode 100644 index 96a27dda3..000000000 --- a/lib/mindee/product/fr/health_card/health_card_v1_document.rb +++ /dev/null @@ -1,61 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module HealthCard - # Health Card API version 1.0 document data. - class HealthCardV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The given names of the card holder. - # @return [Array] - attr_reader :given_names - # The date when the carte vitale document was issued. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :issuance_date - # The social security number of the card holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :social_security - # The surname of the card holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :surname - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @given_names = [] # : Array[Parsing::Standard::StringField] - prediction['given_names'].each do |item| - @given_names.push(Parsing::Standard::StringField.new(item, page_id)) - end - @issuance_date = Parsing::Standard::DateField.new( - prediction['issuance_date'], - page_id - ) - @social_security = Parsing::Standard::StringField.new( - prediction['social_security'], - page_id - ) - @surname = Parsing::Standard::StringField.new( - prediction['surname'], - page_id - ) - end - - # @return [String] - def to_s - given_names = @given_names.join("\n #{' ' * 15}") - out_str = String.new - out_str << "\n:Given Name(s): #{given_names}".rstrip - out_str << "\n:Surname: #{@surname}".rstrip - out_str << "\n:Social Security Number: #{@social_security}".rstrip - out_str << "\n:Issuance Date: #{@issuance_date}".rstrip - out_str[1..].to_s - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/id_card/id_card_v1_page.rb b/lib/mindee/product/fr/id_card/id_card_v1_page.rb deleted file mode 100644 index 3aa026a4b..000000000 --- a/lib/mindee/product/fr/id_card/id_card_v1_page.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'id_card_v1_document' - -module Mindee - module Product - module FR - module IdCard - # Carte Nationale d'Identité API version 1.1 page data. - class IdCardV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - IdCardV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Carte Nationale d'Identité V1 page prediction. - class IdCardV1PagePrediction < IdCardV1Document - include Mindee::Parsing::Standard - - # The side of the document which is visible. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :document_side - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - @document_side = Parsing::Standard::ClassificationField.new( - prediction['document_side'], - page_id - ) - super - end - - # @return [String] - def to_s - out_str = String.new - out_str << "\n:Document Side: #{@document_side}".rstrip - out_str << "\n#{super}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/id_card/id_card_v2.rb b/lib/mindee/product/fr/id_card/id_card_v2.rb deleted file mode 100644 index 9bf5daf74..000000000 --- a/lib/mindee/product/fr/id_card/id_card_v2.rb +++ /dev/null @@ -1,47 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'id_card_v2_document' -require_relative 'id_card_v2_page' - -module Mindee - module Product - module FR - # Carte Nationale d'Identité module. - module IdCard - # Carte Nationale d'Identité API version 2 inference prediction. - class IdCardV2 < Mindee::Parsing::Common::Inference - @endpoint_name = 'idcard_fr' - @endpoint_version = '2' - @has_async = false - @has_sync = true - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = IdCardV2Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(IdCardV2Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/id_card/id_card_v2_document.rb b/lib/mindee/product/fr/id_card/id_card_v2_document.rb deleted file mode 100644 index e367ad221..000000000 --- a/lib/mindee/product/fr/id_card/id_card_v2_document.rb +++ /dev/null @@ -1,140 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module IdCard - # Carte Nationale d'Identité API version 2.0 document data. - class IdCardV2Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The alternate name of the card holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :alternate_name - # The name of the issuing authority. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :authority - # The date of birth of the card holder. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :birth_date - # The place of birth of the card holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :birth_place - # The card access number (CAN). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :card_access_number - # The document number. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :document_number - # The expiry date of the identification card. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :expiry_date - # The gender of the card holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :gender - # The given name(s) of the card holder. - # @return [Array] - attr_reader :given_names - # The date of issue of the identification card. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :issue_date - # The Machine Readable Zone, first line. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz1 - # The Machine Readable Zone, second line. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz2 - # The Machine Readable Zone, third line. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz3 - # The nationality of the card holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :nationality - # The surname of the card holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :surname - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @alternate_name = Parsing::Standard::StringField.new( - prediction['alternate_name'], - page_id - ) - @authority = Parsing::Standard::StringField.new( - prediction['authority'], - page_id - ) - @birth_date = Parsing::Standard::DateField.new( - prediction['birth_date'], - page_id - ) - @birth_place = Parsing::Standard::StringField.new( - prediction['birth_place'], - page_id - ) - @card_access_number = Parsing::Standard::StringField.new( - prediction['card_access_number'], - page_id - ) - @document_number = Parsing::Standard::StringField.new( - prediction['document_number'], - page_id - ) - @expiry_date = Parsing::Standard::DateField.new( - prediction['expiry_date'], - page_id - ) - @gender = Parsing::Standard::StringField.new( - prediction['gender'], - page_id - ) - @given_names = [] # : Array[Parsing::Standard::StringField] - prediction['given_names'].each do |item| - @given_names.push(Parsing::Standard::StringField.new(item, page_id)) - end - @issue_date = Parsing::Standard::DateField.new( - prediction['issue_date'], - page_id - ) - @mrz1 = Parsing::Standard::StringField.new(prediction['mrz1'], page_id) - @mrz2 = Parsing::Standard::StringField.new(prediction['mrz2'], page_id) - @mrz3 = Parsing::Standard::StringField.new(prediction['mrz3'], page_id) - @nationality = Parsing::Standard::StringField.new( - prediction['nationality'], - page_id - ) - @surname = Parsing::Standard::StringField.new( - prediction['surname'], - page_id - ) - end - - # @return [String] - def to_s - given_names = @given_names.join("\n #{' ' * 15}") - out_str = String.new - out_str << "\n:Nationality: #{@nationality}".rstrip - out_str << "\n:Card Access Number: #{@card_access_number}".rstrip - out_str << "\n:Document Number: #{@document_number}".rstrip - out_str << "\n:Given Name(s): #{given_names}".rstrip - out_str << "\n:Surname: #{@surname}".rstrip - out_str << "\n:Alternate Name: #{@alternate_name}".rstrip - out_str << "\n:Date of Birth: #{@birth_date}".rstrip - out_str << "\n:Place of Birth: #{@birth_place}".rstrip - out_str << "\n:Gender: #{@gender}".rstrip - out_str << "\n:Expiry Date: #{@expiry_date}".rstrip - out_str << "\n:Mrz Line 1: #{@mrz1}".rstrip - out_str << "\n:Mrz Line 2: #{@mrz2}".rstrip - out_str << "\n:Mrz Line 3: #{@mrz3}".rstrip - out_str << "\n:Date of Issue: #{@issue_date}".rstrip - out_str << "\n:Issuing Authority: #{@authority}".rstrip - out_str[1..].to_s - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/id_card/id_card_v2_page.rb b/lib/mindee/product/fr/id_card/id_card_v2_page.rb deleted file mode 100644 index afd8ce3b1..000000000 --- a/lib/mindee/product/fr/id_card/id_card_v2_page.rb +++ /dev/null @@ -1,63 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'id_card_v2_document' - -module Mindee - module Product - module FR - module IdCard - # Carte Nationale d'Identité API version 2.0 page data. - class IdCardV2Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - IdCardV2PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Carte Nationale d'Identité V2 page prediction. - class IdCardV2PagePrediction < IdCardV2Document - include Mindee::Parsing::Standard - - # The sides of the document which are visible. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :document_side - # The document type or format. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :document_type - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - @document_side = Parsing::Standard::ClassificationField.new( - prediction['document_side'], - page_id - ) - @document_type = Parsing::Standard::ClassificationField.new( - prediction['document_type'], - page_id - ) - super - end - - # @return [String] - def to_s - out_str = String.new - out_str << "\n:Document Type: #{@document_type}".rstrip - out_str << "\n:Document Sides: #{@document_side}".rstrip - out_str << "\n#{super}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_bank_account_detail.rb b/lib/mindee/product/fr/payslip/payslip_v3_bank_account_detail.rb deleted file mode 100644 index 84e411f7b..000000000 --- a/lib/mindee/product/fr/payslip/payslip_v3_bank_account_detail.rb +++ /dev/null @@ -1,54 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module Payslip - # Information about the employee's bank account. - class PayslipV3BankAccountDetail < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The name of the bank. - # @return [String] - attr_reader :bank_name - # The IBAN of the bank account. - # @return [String] - attr_reader :iban - # The SWIFT code of the bank. - # @return [String] - attr_reader :swift - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @bank_name = prediction['bank_name'] - @iban = prediction['iban'] - @swift = prediction['swift'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:bank_name] = format_for_display(@bank_name) - printable[:iban] = format_for_display(@iban) - printable[:swift] = format_for_display(@swift) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Bank Name: #{printable[:bank_name]}" - out_str << "\n :IBAN: #{printable[:iban]}" - out_str << "\n :SWIFT: #{printable[:swift]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_document.rb b/lib/mindee/product/fr/payslip/payslip_v3_document.rb deleted file mode 100644 index 7689f166c..000000000 --- a/lib/mindee/product/fr/payslip/payslip_v3_document.rb +++ /dev/null @@ -1,178 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'payslip_v3_pay_period' -require_relative 'payslip_v3_employee' -require_relative 'payslip_v3_employer' -require_relative 'payslip_v3_bank_account_detail' -require_relative 'payslip_v3_employment' -require_relative 'payslip_v3_salary_details' -require_relative 'payslip_v3_pay_detail' -require_relative 'payslip_v3_paid_time_offs' - -module Mindee - module Product - module FR - module Payslip - # Payslip API version 3.0 document data. - class PayslipV3Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # Information about the employee's bank account. - # @return [Mindee::Product::FR::Payslip::PayslipV3BankAccountDetail] - attr_reader :bank_account_details - # Information about the employee. - # @return [Mindee::Product::FR::Payslip::PayslipV3Employee] - attr_reader :employee - # Information about the employer. - # @return [Mindee::Product::FR::Payslip::PayslipV3Employer] - attr_reader :employer - # Information about the employment. - # @return [Mindee::Product::FR::Payslip::PayslipV3Employment] - attr_reader :employment - # Information about paid time off. - # @return [Mindee::Product::FR::Payslip::PayslipV3PaidTimeOffs] - attr_reader :paid_time_off - # Detailed information about the pay. - # @return [Mindee::Product::FR::Payslip::PayslipV3PayDetail] - attr_reader :pay_detail - # Information about the pay period. - # @return [Mindee::Product::FR::Payslip::PayslipV3PayPeriod] - attr_reader :pay_period - # Detailed information about the earnings. - # @return [Mindee::Product::FR::Payslip::PayslipV3SalaryDetails] - attr_reader :salary_details - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @bank_account_details = Product::FR::Payslip::PayslipV3BankAccountDetail.new( - prediction['bank_account_details'], - page_id - ) - @employee = Product::FR::Payslip::PayslipV3Employee.new( - prediction['employee'], - page_id - ) - @employer = Product::FR::Payslip::PayslipV3Employer.new( - prediction['employer'], - page_id - ) - @employment = Product::FR::Payslip::PayslipV3Employment.new( - prediction['employment'], - page_id - ) - @paid_time_off = Product::FR::Payslip::PayslipV3PaidTimeOffs.new(prediction['paid_time_off'], page_id) - @pay_detail = Product::FR::Payslip::PayslipV3PayDetail.new( - prediction['pay_detail'], - page_id - ) - @pay_period = Product::FR::Payslip::PayslipV3PayPeriod.new( - prediction['pay_period'], - page_id - ) - @salary_details = Product::FR::Payslip::PayslipV3SalaryDetails.new(prediction['salary_details'], page_id) - end - - # @return [String] - def to_s - pay_period = @pay_period.to_s - employee = @employee.to_s - employer = @employer.to_s - bank_account_details = @bank_account_details.to_s - employment = @employment.to_s - salary_details = salary_details_to_s - pay_detail = @pay_detail.to_s - paid_time_off = paid_time_off_to_s - out_str = String.new - out_str << "\n:Pay Period:" - out_str << pay_period - out_str << "\n:Employee:" - out_str << employee - out_str << "\n:Employer:" - out_str << employer - out_str << "\n:Bank Account Details:" - out_str << bank_account_details - out_str << "\n:Employment:" - out_str << employment - out_str << "\n:Salary Details:" - out_str << salary_details - out_str << "\n:Pay Detail:" - out_str << pay_detail - out_str << "\n:Paid Time Off:" - out_str << paid_time_off - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def salary_details_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 14}" - out_str << "+#{char * 11}" - out_str << "+#{char * 38}" - out_str << "+#{char * 8}" - out_str << "+#{char * 11}" - out_str << '+' - out_str - end - - # @return [String] - def salary_details_to_s - return '' if @salary_details.empty? - - line_items = @salary_details.map(&:to_table_line).join("\n#{salary_details_separator('-')}\n ") - out_str = String.new - out_str << "\n#{salary_details_separator('-')}" - out_str << "\n |" - out_str << ' Amount |' - out_str << ' Base |' - out_str << ' Description |' - out_str << ' Number |' - out_str << ' Rate |' - out_str << "\n#{salary_details_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{salary_details_separator('-')}" - out_str - end - - # @param char [String] - # @return [String] - def paid_time_off_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 11}" - out_str << "+#{char * 8}" - out_str << "+#{char * 13}" - out_str << "+#{char * 11}" - out_str << "+#{char * 11}" - out_str << '+' - out_str - end - - # @return [String] - def paid_time_off_to_s - return '' if @paid_time_off.empty? - - line_items = @paid_time_off.map(&:to_table_line).join("\n#{paid_time_off_separator('-')}\n ") - out_str = String.new - out_str << "\n#{paid_time_off_separator('-')}" - out_str << "\n |" - out_str << ' Accrued |' - out_str << ' Period |' - out_str << ' Type |' - out_str << ' Remaining |' - out_str << ' Used |' - out_str << "\n#{paid_time_off_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{paid_time_off_separator('-')}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_employee.rb b/lib/mindee/product/fr/payslip/payslip_v3_employee.rb deleted file mode 100644 index 698b50773..000000000 --- a/lib/mindee/product/fr/payslip/payslip_v3_employee.rb +++ /dev/null @@ -1,78 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module Payslip - # Information about the employee. - class PayslipV3Employee < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The address of the employee. - # @return [String] - attr_reader :address - # The date of birth of the employee. - # @return [String] - attr_reader :date_of_birth - # The first name of the employee. - # @return [String] - attr_reader :first_name - # The last name of the employee. - # @return [String] - attr_reader :last_name - # The phone number of the employee. - # @return [String] - attr_reader :phone_number - # The registration number of the employee. - # @return [String] - attr_reader :registration_number - # The social security number of the employee. - # @return [String] - attr_reader :social_security_number - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address = prediction['address'] - @date_of_birth = prediction['date_of_birth'] - @first_name = prediction['first_name'] - @last_name = prediction['last_name'] - @phone_number = prediction['phone_number'] - @registration_number = prediction['registration_number'] - @social_security_number = prediction['social_security_number'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:address] = format_for_display(@address) - printable[:date_of_birth] = format_for_display(@date_of_birth) - printable[:first_name] = format_for_display(@first_name) - printable[:last_name] = format_for_display(@last_name) - printable[:phone_number] = format_for_display(@phone_number) - printable[:registration_number] = format_for_display(@registration_number) - printable[:social_security_number] = format_for_display(@social_security_number) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Address: #{printable[:address]}" - out_str << "\n :Date of Birth: #{printable[:date_of_birth]}" - out_str << "\n :First Name: #{printable[:first_name]}" - out_str << "\n :Last Name: #{printable[:last_name]}" - out_str << "\n :Phone Number: #{printable[:phone_number]}" - out_str << "\n :Registration Number: #{printable[:registration_number]}" - out_str << "\n :Social Security Number: #{printable[:social_security_number]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_employer.rb b/lib/mindee/product/fr/payslip/payslip_v3_employer.rb deleted file mode 100644 index 62c640cd4..000000000 --- a/lib/mindee/product/fr/payslip/payslip_v3_employer.rb +++ /dev/null @@ -1,78 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module Payslip - # Information about the employer. - class PayslipV3Employer < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The address of the employer. - # @return [String] - attr_reader :address - # The company ID of the employer. - # @return [String] - attr_reader :company_id - # The site of the company. - # @return [String] - attr_reader :company_site - # The NAF code of the employer. - # @return [String] - attr_reader :naf_code - # The name of the employer. - # @return [String] - attr_reader :name - # The phone number of the employer. - # @return [String] - attr_reader :phone_number - # The URSSAF number of the employer. - # @return [String] - attr_reader :urssaf_number - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address = prediction['address'] - @company_id = prediction['company_id'] - @company_site = prediction['company_site'] - @naf_code = prediction['naf_code'] - @name = prediction['name'] - @phone_number = prediction['phone_number'] - @urssaf_number = prediction['urssaf_number'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:address] = format_for_display(@address) - printable[:company_id] = format_for_display(@company_id) - printable[:company_site] = format_for_display(@company_site) - printable[:naf_code] = format_for_display(@naf_code) - printable[:name] = format_for_display(@name) - printable[:phone_number] = format_for_display(@phone_number) - printable[:urssaf_number] = format_for_display(@urssaf_number) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Address: #{printable[:address]}" - out_str << "\n :Company ID: #{printable[:company_id]}" - out_str << "\n :Company Site: #{printable[:company_site]}" - out_str << "\n :NAF Code: #{printable[:naf_code]}" - out_str << "\n :Name: #{printable[:name]}" - out_str << "\n :Phone Number: #{printable[:phone_number]}" - out_str << "\n :URSSAF Number: #{printable[:urssaf_number]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_employment.rb b/lib/mindee/product/fr/payslip/payslip_v3_employment.rb deleted file mode 100644 index e8ad90c8f..000000000 --- a/lib/mindee/product/fr/payslip/payslip_v3_employment.rb +++ /dev/null @@ -1,78 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module Payslip - # Information about the employment. - class PayslipV3Employment < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The category of the employment. - # @return [String] - attr_reader :category - # The coefficient of the employment. - # @return [String] - attr_reader :coefficient - # The collective agreement of the employment. - # @return [String] - attr_reader :collective_agreement - # The job title of the employee. - # @return [String] - attr_reader :job_title - # The position level of the employment. - # @return [String] - attr_reader :position_level - # The seniority date of the employment. - # @return [String] - attr_reader :seniority_date - # The start date of the employment. - # @return [String] - attr_reader :start_date - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @category = prediction['category'] - @coefficient = prediction['coefficient'] - @collective_agreement = prediction['collective_agreement'] - @job_title = prediction['job_title'] - @position_level = prediction['position_level'] - @seniority_date = prediction['seniority_date'] - @start_date = prediction['start_date'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:category] = format_for_display(@category) - printable[:coefficient] = format_for_display(@coefficient) - printable[:collective_agreement] = format_for_display(@collective_agreement) - printable[:job_title] = format_for_display(@job_title) - printable[:position_level] = format_for_display(@position_level) - printable[:seniority_date] = format_for_display(@seniority_date) - printable[:start_date] = format_for_display(@start_date) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Category: #{printable[:category]}" - out_str << "\n :Coefficient: #{printable[:coefficient]}" - out_str << "\n :Collective Agreement: #{printable[:collective_agreement]}" - out_str << "\n :Job Title: #{printable[:job_title]}" - out_str << "\n :Position Level: #{printable[:position_level]}" - out_str << "\n :Seniority Date: #{printable[:seniority_date]}" - out_str << "\n :Start Date: #{printable[:start_date]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_paid_time_off.rb b/lib/mindee/product/fr/payslip/payslip_v3_paid_time_off.rb deleted file mode 100644 index ef2cfc405..000000000 --- a/lib/mindee/product/fr/payslip/payslip_v3_paid_time_off.rb +++ /dev/null @@ -1,95 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module Payslip - # Information about paid time off. - class PayslipV3PaidTimeOff < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The amount of paid time off accrued in the period. - # @return [Float] - attr_reader :accrued - # The paid time off period. - # @return [String] - attr_reader :period - # The type of paid time off. - # @return [String] - attr_reader :pto_type - # The remaining amount of paid time off at the end of the period. - # @return [Float] - attr_reader :remaining - # The amount of paid time off used in the period. - # @return [Float] - attr_reader :used - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @accrued = prediction['accrued'] - @period = prediction['period'] - @pto_type = prediction['pto_type'] - @remaining = prediction['remaining'] - @used = prediction['used'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:accrued] = - @accrued.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@accrued) - printable[:period] = format_for_display(@period) - printable[:pto_type] = format_for_display(@pto_type) - printable[:remaining] = - @remaining.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@remaining) - printable[:used] = - @used.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@used) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:accrued] = - @accrued.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@accrued) - printable[:period] = format_for_display(@period, 6) - printable[:pto_type] = format_for_display(@pto_type, 11) - printable[:remaining] = - @remaining.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@remaining) - printable[:used] = - @used.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@used) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 10s', printable[:accrued]) - out_str << format('| %- 7s', printable[:period]) - out_str << format('| %- 12s', printable[:pto_type]) - out_str << format('| %- 10s', printable[:remaining]) - out_str << format('| %- 10s', printable[:used]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Accrued: #{printable[:accrued]}" - out_str << "\n :Period: #{printable[:period]}" - out_str << "\n :Type: #{printable[:pto_type]}" - out_str << "\n :Remaining: #{printable[:remaining]}" - out_str << "\n :Used: #{printable[:used]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_pay_detail.rb b/lib/mindee/product/fr/payslip/payslip_v3_pay_detail.rb deleted file mode 100644 index 5d706add1..000000000 --- a/lib/mindee/product/fr/payslip/payslip_v3_pay_detail.rb +++ /dev/null @@ -1,122 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module Payslip - # Detailed information about the pay. - class PayslipV3PayDetail < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The gross salary of the employee. - # @return [Float] - attr_reader :gross_salary - # The year-to-date gross salary of the employee. - # @return [Float] - attr_reader :gross_salary_ytd - # The income tax rate of the employee. - # @return [Float] - attr_reader :income_tax_rate - # The income tax withheld from the employee's pay. - # @return [Float] - attr_reader :income_tax_withheld - # The net paid amount of the employee. - # @return [Float] - attr_reader :net_paid - # The net paid amount before tax of the employee. - # @return [Float] - attr_reader :net_paid_before_tax - # The net taxable amount of the employee. - # @return [Float] - attr_reader :net_taxable - # The year-to-date net taxable amount of the employee. - # @return [Float] - attr_reader :net_taxable_ytd - # The total cost to the employer. - # @return [Float] - attr_reader :total_cost_employer - # The total taxes and deductions of the employee. - # @return [Float] - attr_reader :total_taxes_and_deductions - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @gross_salary = prediction['gross_salary'] - @gross_salary_ytd = prediction['gross_salary_ytd'] - @income_tax_rate = prediction['income_tax_rate'] - @income_tax_withheld = prediction['income_tax_withheld'] - @net_paid = prediction['net_paid'] - @net_paid_before_tax = prediction['net_paid_before_tax'] - @net_taxable = prediction['net_taxable'] - @net_taxable_ytd = prediction['net_taxable_ytd'] - @total_cost_employer = prediction['total_cost_employer'] - @total_taxes_and_deductions = prediction['total_taxes_and_deductions'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:gross_salary] = - @gross_salary.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@gross_salary) - printable[:gross_salary_ytd] = - @gross_salary_ytd.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@gross_salary_ytd) - printable[:income_tax_rate] = - @income_tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@income_tax_rate) - printable[:income_tax_withheld] = - if @income_tax_withheld.nil? - '' - else - Parsing::Standard::BaseField.float_to_string(@income_tax_withheld) - end - printable[:net_paid] = - @net_paid.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@net_paid) - printable[:net_paid_before_tax] = - if @net_paid_before_tax.nil? - '' - else - Parsing::Standard::BaseField.float_to_string(@net_paid_before_tax) - end - printable[:net_taxable] = - @net_taxable.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@net_taxable) - printable[:net_taxable_ytd] = - @net_taxable_ytd.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@net_taxable_ytd) - printable[:total_cost_employer] = - if @total_cost_employer.nil? - '' - else - Parsing::Standard::BaseField.float_to_string(@total_cost_employer) - end - printable[:total_taxes_and_deductions] = - if @total_taxes_and_deductions.nil? - '' - else - Parsing::Standard::BaseField.float_to_string(@total_taxes_and_deductions) - end - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Gross Salary: #{printable[:gross_salary]}" - out_str << "\n :Gross Salary YTD: #{printable[:gross_salary_ytd]}" - out_str << "\n :Income Tax Rate: #{printable[:income_tax_rate]}" - out_str << "\n :Income Tax Withheld: #{printable[:income_tax_withheld]}" - out_str << "\n :Net Paid: #{printable[:net_paid]}" - out_str << "\n :Net Paid Before Tax: #{printable[:net_paid_before_tax]}" - out_str << "\n :Net Taxable: #{printable[:net_taxable]}" - out_str << "\n :Net Taxable YTD: #{printable[:net_taxable_ytd]}" - out_str << "\n :Total Cost Employer: #{printable[:total_cost_employer]}" - out_str << "\n :Total Taxes and Deductions: #{printable[:total_taxes_and_deductions]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_pay_period.rb b/lib/mindee/product/fr/payslip/payslip_v3_pay_period.rb deleted file mode 100644 index 376fb9ef8..000000000 --- a/lib/mindee/product/fr/payslip/payslip_v3_pay_period.rb +++ /dev/null @@ -1,66 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module Payslip - # Information about the pay period. - class PayslipV3PayPeriod < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The end date of the pay period. - # @return [String] - attr_reader :end_date - # The month of the pay period. - # @return [String] - attr_reader :month - # The date of payment for the pay period. - # @return [String] - attr_reader :payment_date - # The start date of the pay period. - # @return [String] - attr_reader :start_date - # The year of the pay period. - # @return [String] - attr_reader :year - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @end_date = prediction['end_date'] - @month = prediction['month'] - @payment_date = prediction['payment_date'] - @start_date = prediction['start_date'] - @year = prediction['year'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:end_date] = format_for_display(@end_date) - printable[:month] = format_for_display(@month) - printable[:payment_date] = format_for_display(@payment_date) - printable[:start_date] = format_for_display(@start_date) - printable[:year] = format_for_display(@year) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :End Date: #{printable[:end_date]}" - out_str << "\n :Month: #{printable[:month]}" - out_str << "\n :Payment Date: #{printable[:payment_date]}" - out_str << "\n :Start Date: #{printable[:start_date]}" - out_str << "\n :Year: #{printable[:year]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_salary_detail.rb b/lib/mindee/product/fr/payslip/payslip_v3_salary_detail.rb deleted file mode 100644 index 5e4b9b712..000000000 --- a/lib/mindee/product/fr/payslip/payslip_v3_salary_detail.rb +++ /dev/null @@ -1,97 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module FR - module Payslip - # Detailed information about the earnings. - class PayslipV3SalaryDetail < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The amount of the earning. - # @return [Float] - attr_reader :amount - # The base rate value of the earning. - # @return [Float] - attr_reader :base - # The description of the earnings. - # @return [String] - attr_reader :description - # The number of units in the earning. - # @return [Float] - attr_reader :number - # The rate of the earning. - # @return [Float] - attr_reader :rate - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @amount = prediction['amount'] - @base = prediction['base'] - @description = prediction['description'] - @number = prediction['number'] - @rate = prediction['rate'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:amount] = - @amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@amount) - printable[:base] = - @base.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@base) - printable[:description] = format_for_display(@description) - printable[:number] = - @number.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@number) - printable[:rate] = - @rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@rate) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:amount] = - @amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@amount) - printable[:base] = - @base.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@base) - printable[:description] = format_for_display(@description, 36) - printable[:number] = - @number.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@number) - printable[:rate] = - @rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@rate) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 13s', printable[:amount]) - out_str << format('| %- 10s', printable[:base]) - out_str << format('| %- 37s', printable[:description]) - out_str << format('| %- 7s', printable[:number]) - out_str << format('| %- 10s', printable[:rate]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Amount: #{printable[:amount]}" - out_str << "\n :Base: #{printable[:base]}" - out_str << "\n :Description: #{printable[:description]}" - out_str << "\n :Number: #{printable[:number]}" - out_str << "\n :Rate: #{printable[:rate]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/ind/indian_passport/indian_passport_v1_document.rb b/lib/mindee/product/ind/indian_passport/indian_passport_v1_document.rb deleted file mode 100644 index 694d378c0..000000000 --- a/lib/mindee/product/ind/indian_passport/indian_passport_v1_document.rb +++ /dev/null @@ -1,206 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module IND - module IndianPassport - # Passport - India API version 1.2 document data. - class IndianPassportV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The first line of the address of the passport holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :address1 - # The second line of the address of the passport holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :address2 - # The third line of the address of the passport holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :address3 - # The birth date of the passport holder, ISO format: YYYY-MM-DD. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :birth_date - # The birth place of the passport holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :birth_place - # ISO 3166-1 alpha-3 country code (3 letters format). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :country - # The date when the passport will expire, ISO format: YYYY-MM-DD. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :expiry_date - # The file number of the passport document. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :file_number - # The gender of the passport holder. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :gender - # The given names of the passport holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :given_names - # The identification number of the passport document. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :id_number - # The date when the passport was issued, ISO format: YYYY-MM-DD. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :issuance_date - # The place where the passport was issued. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :issuance_place - # The name of the legal guardian of the passport holder (if applicable). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :legal_guardian - # The first line of the machine-readable zone (MRZ) of the passport document. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz1 - # The second line of the machine-readable zone (MRZ) of the passport document. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz2 - # The name of the mother of the passport holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :name_of_mother - # The name of the spouse of the passport holder (if applicable). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :name_of_spouse - # The date of issue of the old passport (if applicable), ISO format: YYYY-MM-DD. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :old_passport_date_of_issue - # The number of the old passport (if applicable). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :old_passport_number - # The place of issue of the old passport (if applicable). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :old_passport_place_of_issue - # The page number of the passport document. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :page_number - # The surname of the passport holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :surname - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address1 = Parsing::Standard::StringField.new( - prediction['address1'], - page_id - ) - @address2 = Parsing::Standard::StringField.new( - prediction['address2'], - page_id - ) - @address3 = Parsing::Standard::StringField.new( - prediction['address3'], - page_id - ) - @birth_date = Parsing::Standard::DateField.new( - prediction['birth_date'], - page_id - ) - @birth_place = Parsing::Standard::StringField.new( - prediction['birth_place'], - page_id - ) - @country = Parsing::Standard::StringField.new( - prediction['country'], - page_id - ) - @expiry_date = Parsing::Standard::DateField.new( - prediction['expiry_date'], - page_id - ) - @file_number = Parsing::Standard::StringField.new( - prediction['file_number'], - page_id - ) - @gender = Parsing::Standard::ClassificationField.new( - prediction['gender'], - page_id - ) - @given_names = Parsing::Standard::StringField.new( - prediction['given_names'], - page_id - ) - @id_number = Parsing::Standard::StringField.new( - prediction['id_number'], - page_id - ) - @issuance_date = Parsing::Standard::DateField.new( - prediction['issuance_date'], - page_id - ) - @issuance_place = Parsing::Standard::StringField.new( - prediction['issuance_place'], - page_id - ) - @legal_guardian = Parsing::Standard::StringField.new( - prediction['legal_guardian'], - page_id - ) - @mrz1 = Parsing::Standard::StringField.new(prediction['mrz1'], page_id) - @mrz2 = Parsing::Standard::StringField.new(prediction['mrz2'], page_id) - @name_of_mother = Parsing::Standard::StringField.new( - prediction['name_of_mother'], - page_id - ) - @name_of_spouse = Parsing::Standard::StringField.new( - prediction['name_of_spouse'], - page_id - ) - @old_passport_date_of_issue = Parsing::Standard::DateField.new( - prediction['old_passport_date_of_issue'], - page_id - ) - @old_passport_number = Parsing::Standard::StringField.new( - prediction['old_passport_number'], - page_id - ) - @old_passport_place_of_issue = Parsing::Standard::StringField.new( - prediction['old_passport_place_of_issue'], - page_id - ) - @page_number = Parsing::Standard::ClassificationField.new( - prediction['page_number'], - page_id - ) - @surname = Parsing::Standard::StringField.new( - prediction['surname'], - page_id - ) - end - - # @return [String] - def to_s - out_str = String.new - out_str << "\n:Page Number: #{@page_number}".rstrip - out_str << "\n:Country: #{@country}".rstrip - out_str << "\n:ID Number: #{@id_number}".rstrip - out_str << "\n:Given Names: #{@given_names}".rstrip - out_str << "\n:Surname: #{@surname}".rstrip - out_str << "\n:Birth Date: #{@birth_date}".rstrip - out_str << "\n:Birth Place: #{@birth_place}".rstrip - out_str << "\n:Issuance Place: #{@issuance_place}".rstrip - out_str << "\n:Gender: #{@gender}".rstrip - out_str << "\n:Issuance Date: #{@issuance_date}".rstrip - out_str << "\n:Expiry Date: #{@expiry_date}".rstrip - out_str << "\n:MRZ Line 1: #{@mrz1}".rstrip - out_str << "\n:MRZ Line 2: #{@mrz2}".rstrip - out_str << "\n:Legal Guardian: #{@legal_guardian}".rstrip - out_str << "\n:Name of Spouse: #{@name_of_spouse}".rstrip - out_str << "\n:Name of Mother: #{@name_of_mother}".rstrip - out_str << "\n:Old Passport Date of Issue: #{@old_passport_date_of_issue}".rstrip - out_str << "\n:Old Passport Number: #{@old_passport_number}".rstrip - out_str << "\n:Old Passport Place of Issue: #{@old_passport_place_of_issue}".rstrip - out_str << "\n:Address Line 1: #{@address1}".rstrip - out_str << "\n:Address Line 2: #{@address2}".rstrip - out_str << "\n:Address Line 3: #{@address3}".rstrip - out_str << "\n:File Number: #{@file_number}".rstrip - out_str[1..].to_s - end - end - end - end - end -end diff --git a/lib/mindee/product/ind/indian_passport/indian_passport_v1_page.rb b/lib/mindee/product/ind/indian_passport/indian_passport_v1_page.rb deleted file mode 100644 index 77b1faa66..000000000 --- a/lib/mindee/product/ind/indian_passport/indian_passport_v1_page.rb +++ /dev/null @@ -1,38 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'indian_passport_v1_document' - -module Mindee - module Product - module IND - module IndianPassport - # Passport - India API version 1.2 page data. - class IndianPassportV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - IndianPassportV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Passport - India V1 page prediction. - class IndianPassportV1PagePrediction < IndianPassportV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/international_id/international_id_v2.rb b/lib/mindee/product/international_id/international_id_v2.rb deleted file mode 100644 index 290b9435d..000000000 --- a/lib/mindee/product/international_id/international_id_v2.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'international_id_v2_document' -require_relative 'international_id_v2_page' - -module Mindee - module Product - # International ID module. - module InternationalId - # International ID API version 2 inference prediction. - class InternationalIdV2 < Mindee::Parsing::Common::Inference - @endpoint_name = 'international_id' - @endpoint_version = '2' - @has_async = true - @has_sync = false - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = InternationalIdV2Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(InternationalIdV2Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/international_id/international_id_v2_document.rb b/lib/mindee/product/international_id/international_id_v2_document.rb deleted file mode 100644 index 5a5e1242a..000000000 --- a/lib/mindee/product/international_id/international_id_v2_document.rb +++ /dev/null @@ -1,161 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module InternationalId - # International ID API version 2.2 document data. - class InternationalIdV2Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The physical address of the document holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :address - # The date of birth of the document holder. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :birth_date - # The place of birth of the document holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :birth_place - # The country where the document was issued. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :country_of_issue - # The unique identifier assigned to the document. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :document_number - # The type of personal identification document. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :document_type - # The date when the document becomes invalid. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :expiry_date - # The list of the document holder's given names. - # @return [Array] - attr_reader :given_names - # The date when the document was issued. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :issue_date - # The Machine Readable Zone, first line. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz_line1 - # The Machine Readable Zone, second line. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz_line2 - # The Machine Readable Zone, third line. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz_line3 - # The country of citizenship of the document holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :nationality - # The unique identifier assigned to the document holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :personal_number - # The biological sex of the document holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :sex - # The state or territory where the document was issued. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :state_of_issue - # The list of the document holder's family names. - # @return [Array] - attr_reader :surnames - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address = Parsing::Standard::StringField.new( - prediction['address'], - page_id - ) - @birth_date = Parsing::Standard::DateField.new( - prediction['birth_date'], - page_id - ) - @birth_place = Parsing::Standard::StringField.new( - prediction['birth_place'], - page_id - ) - @country_of_issue = Parsing::Standard::StringField.new( - prediction['country_of_issue'], - page_id - ) - @document_number = Parsing::Standard::StringField.new( - prediction['document_number'], - page_id - ) - @document_type = Parsing::Standard::ClassificationField.new( - prediction['document_type'], - page_id - ) - @expiry_date = Parsing::Standard::DateField.new( - prediction['expiry_date'], - page_id - ) - @given_names = [] # : Array[Parsing::Standard::StringField] - prediction['given_names'].each do |item| - @given_names.push(Parsing::Standard::StringField.new(item, page_id)) - end - @issue_date = Parsing::Standard::DateField.new( - prediction['issue_date'], - page_id - ) - @mrz_line1 = Parsing::Standard::StringField.new( - prediction['mrz_line1'], - page_id - ) - @mrz_line2 = Parsing::Standard::StringField.new( - prediction['mrz_line2'], - page_id - ) - @mrz_line3 = Parsing::Standard::StringField.new( - prediction['mrz_line3'], - page_id - ) - @nationality = Parsing::Standard::StringField.new( - prediction['nationality'], - page_id - ) - @personal_number = Parsing::Standard::StringField.new( - prediction['personal_number'], - page_id - ) - @sex = Parsing::Standard::StringField.new(prediction['sex'], page_id) - @state_of_issue = Parsing::Standard::StringField.new( - prediction['state_of_issue'], - page_id - ) - @surnames = [] # : Array[Parsing::Standard::StringField] - prediction['surnames'].each do |item| - @surnames.push(Parsing::Standard::StringField.new(item, page_id)) - end - end - - # @return [String] - def to_s - surnames = @surnames.join("\n #{' ' * 10}") - given_names = @given_names.join("\n #{' ' * 13}") - out_str = String.new - out_str << "\n:Document Type: #{@document_type}".rstrip - out_str << "\n:Document Number: #{@document_number}".rstrip - out_str << "\n:Surnames: #{surnames}".rstrip - out_str << "\n:Given Names: #{given_names}".rstrip - out_str << "\n:Sex: #{@sex}".rstrip - out_str << "\n:Birth Date: #{@birth_date}".rstrip - out_str << "\n:Birth Place: #{@birth_place}".rstrip - out_str << "\n:Nationality: #{@nationality}".rstrip - out_str << "\n:Personal Number: #{@personal_number}".rstrip - out_str << "\n:Country of Issue: #{@country_of_issue}".rstrip - out_str << "\n:State of Issue: #{@state_of_issue}".rstrip - out_str << "\n:Issue Date: #{@issue_date}".rstrip - out_str << "\n:Expiration Date: #{@expiry_date}".rstrip - out_str << "\n:Address: #{@address}".rstrip - out_str << "\n:MRZ Line 1: #{@mrz_line1}".rstrip - out_str << "\n:MRZ Line 2: #{@mrz_line2}".rstrip - out_str << "\n:MRZ Line 3: #{@mrz_line3}".rstrip - out_str[1..].to_s - end - end - end - end -end diff --git a/lib/mindee/product/international_id/international_id_v2_page.rb b/lib/mindee/product/international_id/international_id_v2_page.rb deleted file mode 100644 index 025be4c51..000000000 --- a/lib/mindee/product/international_id/international_id_v2_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'international_id_v2_document' - -module Mindee - module Product - module InternationalId - # International ID API version 2.2 page data. - class InternationalIdV2Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - InternationalIdV2PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # International ID V2 page prediction. - class InternationalIdV2PagePrediction < InternationalIdV2Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/invoice/invoice_v4.rb b/lib/mindee/product/invoice/invoice_v4.rb deleted file mode 100644 index edf101dd0..000000000 --- a/lib/mindee/product/invoice/invoice_v4.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'invoice_v4_document' -require_relative 'invoice_v4_page' - -module Mindee - module Product - # Invoice module. - module Invoice - # Invoice API version 4 inference prediction. - class InvoiceV4 < Mindee::Parsing::Common::Inference - @endpoint_name = 'invoices' - @endpoint_version = '4' - @has_async = true - @has_sync = true - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = InvoiceV4Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(InvoiceV4Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/invoice/invoice_v4_document.rb b/lib/mindee/product/invoice/invoice_v4_document.rb deleted file mode 100644 index 9d4f1f044..000000000 --- a/lib/mindee/product/invoice/invoice_v4_document.rb +++ /dev/null @@ -1,297 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'invoice_v4_line_items' - -module Mindee - module Product - module Invoice - # Invoice API version 4.11 document data. - class InvoiceV4Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The customer billing address. - # @return [Mindee::Parsing::Standard::AddressField] - attr_reader :billing_address - # The purchase category. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :category - # The address of the customer. - # @return [Mindee::Parsing::Standard::AddressField] - attr_reader :customer_address - # List of company registration numbers associated to the customer. - # @return [Array] - attr_reader :customer_company_registrations - # The customer account number or identifier from the supplier. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :customer_id - # The name of the customer or client. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :customer_name - # The date the purchase was made. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :date - # Document type: INVOICE or CREDIT NOTE. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :document_type - # Document type extended. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :document_type_extended - # The date on which the payment is due. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :due_date - # The invoice number or identifier. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :invoice_number - # List of all the line items present on the invoice. - # @return [Mindee::Product::Invoice::InvoiceV4LineItems] - attr_reader :line_items - # The locale of the document. - # @return [Mindee::Parsing::Standard::LocaleField] - attr_reader :locale - # The date on which the payment is due / was full-filled. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :payment_date - # The purchase order number. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :po_number - # List of all reference numbers on the invoice, including the purchase order number. - # @return [Array] - attr_reader :reference_numbers - # Customer's delivery address. - # @return [Mindee::Parsing::Standard::AddressField] - attr_reader :shipping_address - # The purchase subcategory for transport, food and shopping. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :subcategory - # The address of the supplier or merchant. - # @return [Mindee::Parsing::Standard::AddressField] - attr_reader :supplier_address - # List of company registration numbers associated to the supplier. - # @return [Array] - attr_reader :supplier_company_registrations - # The email address of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_email - # The name of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_name - # List of payment details associated to the supplier of the invoice. - # @return [Array] - attr_reader :supplier_payment_details - # The phone number of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_phone_number - # The website URL of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_website - # List of taxes. Each item contains the detail of the tax. - # @return [Mindee::Parsing::Standard::Taxes] - attr_reader :taxes - # The total amount of the invoice: includes taxes, tips, fees, and other charges. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_amount - # The net amount of the invoice: does not include taxes, fees, and discounts. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_net - # The total tax: the sum of all the taxes for this invoice. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_tax - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @billing_address = Parsing::Standard::AddressField.new( - prediction['billing_address'], - page_id - ) - @category = Parsing::Standard::ClassificationField.new( - prediction['category'], - page_id - ) - @customer_address = Parsing::Standard::AddressField.new( - prediction['customer_address'], - page_id - ) - @customer_company_registrations = [] # : Array[Parsing::Standard::CompanyRegistrationField] - prediction['customer_company_registrations'].each do |item| - @customer_company_registrations.push(Parsing::Standard::CompanyRegistrationField.new(item, page_id)) - end - @customer_id = Parsing::Standard::StringField.new( - prediction['customer_id'], - page_id - ) - @customer_name = Parsing::Standard::StringField.new( - prediction['customer_name'], - page_id - ) - @date = Parsing::Standard::DateField.new(prediction['date'], page_id) - @document_type = Parsing::Standard::ClassificationField.new( - prediction['document_type'], - page_id - ) - @document_type_extended = Parsing::Standard::ClassificationField.new( - prediction['document_type_extended'], - page_id - ) - @due_date = Parsing::Standard::DateField.new( - prediction['due_date'], - page_id - ) - @invoice_number = Parsing::Standard::StringField.new( - prediction['invoice_number'], - page_id - ) - @line_items = Product::Invoice::InvoiceV4LineItems.new(prediction['line_items'], page_id) - @locale = Parsing::Standard::LocaleField.new( - prediction['locale'], - page_id - ) - @payment_date = Parsing::Standard::DateField.new( - prediction['payment_date'], - page_id - ) - @po_number = Parsing::Standard::StringField.new( - prediction['po_number'], - page_id - ) - @reference_numbers = [] # : Array[Parsing::Standard::StringField] - prediction['reference_numbers'].each do |item| - @reference_numbers.push(Parsing::Standard::StringField.new(item, page_id)) - end - @shipping_address = Parsing::Standard::AddressField.new( - prediction['shipping_address'], - page_id - ) - @subcategory = Parsing::Standard::ClassificationField.new( - prediction['subcategory'], - page_id - ) - @supplier_address = Parsing::Standard::AddressField.new( - prediction['supplier_address'], - page_id - ) - @supplier_company_registrations = [] # : Array[Parsing::Standard::CompanyRegistrationField] - prediction['supplier_company_registrations'].each do |item| - @supplier_company_registrations.push(Parsing::Standard::CompanyRegistrationField.new(item, page_id)) - end - @supplier_email = Parsing::Standard::StringField.new( - prediction['supplier_email'], - page_id - ) - @supplier_name = Parsing::Standard::StringField.new( - prediction['supplier_name'], - page_id - ) - @supplier_payment_details = [] # : Array[Parsing::Standard::PaymentDetailsField] - prediction['supplier_payment_details'].each do |item| - @supplier_payment_details.push(Parsing::Standard::PaymentDetailsField.new(item, page_id)) - end - @supplier_phone_number = Parsing::Standard::StringField.new( - prediction['supplier_phone_number'], - page_id - ) - @supplier_website = Parsing::Standard::StringField.new( - prediction['supplier_website'], - page_id - ) - @taxes = Parsing::Standard::Taxes.new(prediction['taxes'], page_id) - @total_amount = Parsing::Standard::AmountField.new( - prediction['total_amount'], - page_id - ) - @total_net = Parsing::Standard::AmountField.new( - prediction['total_net'], - page_id - ) - @total_tax = Parsing::Standard::AmountField.new( - prediction['total_tax'], - page_id - ) - end - - # @return [String] - def to_s - reference_numbers = @reference_numbers.join("\n #{' ' * 19}") - supplier_payment_details = @supplier_payment_details.join("\n #{' ' * 26}") - supplier_company_registrations = @supplier_company_registrations.join("\n #{' ' * 32}") - customer_company_registrations = @customer_company_registrations.join("\n #{' ' * 32}") - line_items = line_items_to_s - out_str = String.new - out_str << "\n:Locale: #{@locale}".rstrip - out_str << "\n:Invoice Number: #{@invoice_number}".rstrip - out_str << "\n:Purchase Order Number: #{@po_number}".rstrip - out_str << "\n:Reference Numbers: #{reference_numbers}".rstrip - out_str << "\n:Purchase Date: #{@date}".rstrip - out_str << "\n:Due Date: #{@due_date}".rstrip - out_str << "\n:Payment Date: #{@payment_date}".rstrip - out_str << "\n:Total Net: #{@total_net}".rstrip - out_str << "\n:Total Amount: #{@total_amount}".rstrip - out_str << "\n:Total Tax: #{@total_tax}".rstrip - out_str << "\n:Taxes:#{@taxes}".rstrip - out_str << "\n:Supplier Payment Details: #{supplier_payment_details}".rstrip - out_str << "\n:Supplier Name: #{@supplier_name}".rstrip - out_str << "\n:Supplier Company Registrations: #{supplier_company_registrations}".rstrip - out_str << "\n:Supplier Address: #{@supplier_address}".rstrip - out_str << "\n:Supplier Phone Number: #{@supplier_phone_number}".rstrip - out_str << "\n:Supplier Website: #{@supplier_website}".rstrip - out_str << "\n:Supplier Email: #{@supplier_email}".rstrip - out_str << "\n:Customer Name: #{@customer_name}".rstrip - out_str << "\n:Customer Company Registrations: #{customer_company_registrations}".rstrip - out_str << "\n:Customer Address: #{@customer_address}".rstrip - out_str << "\n:Customer ID: #{@customer_id}".rstrip - out_str << "\n:Shipping Address: #{@shipping_address}".rstrip - out_str << "\n:Billing Address: #{@billing_address}".rstrip - out_str << "\n:Document Type: #{@document_type}".rstrip - out_str << "\n:Document Type Extended: #{@document_type_extended}".rstrip - out_str << "\n:Purchase Subcategory: #{@subcategory}".rstrip - out_str << "\n:Purchase Category: #{@category}".rstrip - out_str << "\n:Line Items:" - out_str << line_items - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def line_items_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 38}" - out_str << "+#{char * 14}" - out_str << "+#{char * 10}" - out_str << "+#{char * 12}" - out_str << "+#{char * 14}" - out_str << "+#{char * 14}" - out_str << "+#{char * 17}" - out_str << "+#{char * 12}" - out_str << '+' - out_str - end - - # @return [String] - def line_items_to_s - return '' if @line_items.empty? - - line_items = @line_items.map(&:to_table_line).join("\n#{line_items_separator('-')}\n ") - out_str = String.new - out_str << "\n#{line_items_separator('-')}" - out_str << "\n |" - out_str << ' Description |' - out_str << ' Product code |' - out_str << ' Quantity |' - out_str << ' Tax Amount |' - out_str << ' Tax Rate (%) |' - out_str << ' Total Amount |' - out_str << ' Unit of measure |' - out_str << ' Unit Price |' - out_str << "\n#{line_items_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{line_items_separator('-')}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/invoice/invoice_v4_line_item.rb b/lib/mindee/product/invoice/invoice_v4_line_item.rb deleted file mode 100644 index 7664851e5..000000000 --- a/lib/mindee/product/invoice/invoice_v4_line_item.rb +++ /dev/null @@ -1,121 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module Invoice - # List of all the line items present on the invoice. - class InvoiceV4LineItem < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The item description. - # @return [String] - attr_reader :description - # The product code of the item. - # @return [String] - attr_reader :product_code - # The item quantity - # @return [Float] - attr_reader :quantity - # The item tax amount. - # @return [Float] - attr_reader :tax_amount - # The item tax rate in percentage. - # @return [Float] - attr_reader :tax_rate - # The item total amount. - # @return [Float] - attr_reader :total_amount - # The item unit of measure. - # @return [String] - attr_reader :unit_measure - # The item unit price. - # @return [Float] - attr_reader :unit_price - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @description = prediction['description'] - @product_code = prediction['product_code'] - @quantity = prediction['quantity'] - @tax_amount = prediction['tax_amount'] - @tax_rate = prediction['tax_rate'] - @total_amount = prediction['total_amount'] - @unit_measure = prediction['unit_measure'] - @unit_price = prediction['unit_price'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:description] = format_for_display(@description) - printable[:product_code] = format_for_display(@product_code) - printable[:quantity] = - @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) - printable[:tax_amount] = - @tax_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_amount) - printable[:tax_rate] = - @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) - printable[:total_amount] = - @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) - printable[:unit_measure] = format_for_display(@unit_measure) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:description] = format_for_display(@description, 36) - printable[:product_code] = format_for_display(@product_code, nil) - printable[:quantity] = - @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) - printable[:tax_amount] = - @tax_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_amount) - printable[:tax_rate] = - @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) - printable[:total_amount] = - @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) - printable[:unit_measure] = format_for_display(@unit_measure, nil) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 37s', printable[:description]) - out_str << format('| %- 13s', printable[:product_code]) - out_str << format('| %- 9s', printable[:quantity]) - out_str << format('| %- 11s', printable[:tax_amount]) - out_str << format('| %- 13s', printable[:tax_rate]) - out_str << format('| %- 13s', printable[:total_amount]) - out_str << format('| %- 16s', printable[:unit_measure]) - out_str << format('| %- 11s', printable[:unit_price]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Description: #{printable[:description]}" - out_str << "\n :Product code: #{printable[:product_code]}" - out_str << "\n :Quantity: #{printable[:quantity]}" - out_str << "\n :Tax Amount: #{printable[:tax_amount]}" - out_str << "\n :Tax Rate (%): #{printable[:tax_rate]}" - out_str << "\n :Total Amount: #{printable[:total_amount]}" - out_str << "\n :Unit of measure: #{printable[:unit_measure]}" - out_str << "\n :Unit Price: #{printable[:unit_price]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/invoice/invoice_v4_line_items.rb b/lib/mindee/product/invoice/invoice_v4_line_items.rb deleted file mode 100644 index 1af5d7723..000000000 --- a/lib/mindee/product/invoice/invoice_v4_line_items.rb +++ /dev/null @@ -1,62 +0,0 @@ -# frozen_string_literal: true - -require_relative 'invoice_v4_line_item' - -module Mindee - module Product - module Invoice - # List of all the line items present on the invoice. - class InvoiceV4LineItems < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - Invoice::InvoiceV4LineItem.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 38}" - out_str << "+#{char * 14}" - out_str << "+#{char * 10}" - out_str << "+#{char * 12}" - out_str << "+#{char * 14}" - out_str << "+#{char * 14}" - out_str << "+#{char * 17}" - out_str << "+#{char * 12}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Description ' - out_str << ' | Product code' - out_str << ' | Quantity' - out_str << ' | Tax Amount' - out_str << ' | Tax Rate (%)' - out_str << ' | Total Amount' - out_str << ' | Unit of measure' - out_str << ' | Unit Price' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/invoice/invoice_v4_page.rb b/lib/mindee/product/invoice/invoice_v4_page.rb deleted file mode 100644 index a5e6c004d..000000000 --- a/lib/mindee/product/invoice/invoice_v4_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'invoice_v4_document' - -module Mindee - module Product - module Invoice - # Invoice API version 4.11 page data. - class InvoiceV4Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - InvoiceV4PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Invoice V4 page prediction. - class InvoiceV4PagePrediction < InvoiceV4Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/invoice_splitter/invoice_splitter_v1.rb b/lib/mindee/product/invoice_splitter/invoice_splitter_v1.rb deleted file mode 100644 index b0b1fbfd4..000000000 --- a/lib/mindee/product/invoice_splitter/invoice_splitter_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'invoice_splitter_v1_document' -require_relative 'invoice_splitter_v1_page' - -module Mindee - module Product - # Invoice Splitter module. - module InvoiceSplitter - # Invoice Splitter API version 1 inference prediction. - class InvoiceSplitterV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'invoice_splitter' - @endpoint_version = '1' - @has_async = true - @has_sync = false - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = InvoiceSplitterV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(InvoiceSplitterV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/invoice_splitter/invoice_splitter_v1_document.rb b/lib/mindee/product/invoice_splitter/invoice_splitter_v1_document.rb deleted file mode 100644 index 6e03d6eeb..000000000 --- a/lib/mindee/product/invoice_splitter/invoice_splitter_v1_document.rb +++ /dev/null @@ -1,63 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'invoice_splitter_v1_invoice_page_groups' - -module Mindee - module Product - module InvoiceSplitter - # Invoice Splitter API version 1.4 document data. - class InvoiceSplitterV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # List of page groups. Each group represents a single invoice within a multi-invoice document. - # @return [Mindee::Product::InvoiceSplitter::InvoiceSplitterV1InvoicePageGroups] - attr_reader :invoice_page_groups - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @invoice_page_groups = Product::InvoiceSplitter::InvoiceSplitterV1InvoicePageGroups.new( - prediction['invoice_page_groups'], page_id - ) - end - - # @return [String] - def to_s - invoice_page_groups = invoice_page_groups_to_s - out_str = String.new - out_str << "\n:Invoice Page Groups:" - out_str << invoice_page_groups - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def invoice_page_groups_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 74}" - out_str << '+' - out_str - end - - # @return [String] - def invoice_page_groups_to_s - return '' if @invoice_page_groups.empty? - - line_items = @invoice_page_groups.map(&:to_table_line).join("\n#{invoice_page_groups_separator('-')}\n ") - out_str = String.new - out_str << "\n#{invoice_page_groups_separator('-')}" - out_str << "\n |" - out_str << ' Page Indexes |' - out_str << "\n#{invoice_page_groups_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{invoice_page_groups_separator('-')}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rb b/lib/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rb deleted file mode 100644 index 861000194..000000000 --- a/lib/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module InvoiceSplitter - # List of page groups. Each group represents a single invoice within a multi-invoice document. - class InvoiceSplitterV1InvoicePageGroup < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # List of page indexes that belong to the same invoice (group). - # @return [Array] - attr_reader :page_indexes - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @page_indexes = prediction['page_indexes'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:page_indexes] = format_for_display(@page_indexes) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:page_indexes] = @page_indexes.join(', ') - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 73s', printable[:page_indexes]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Page Indexes: #{printable[:page_indexes]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rb b/lib/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rb deleted file mode 100644 index d098b9548..000000000 --- a/lib/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rb +++ /dev/null @@ -1,48 +0,0 @@ -# frozen_string_literal: true - -require_relative 'invoice_splitter_v1_invoice_page_group' - -module Mindee - module Product - module InvoiceSplitter - # List of page groups. Each group represents a single invoice within a multi-invoice document. - class InvoiceSplitterV1InvoicePageGroups < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - InvoiceSplitter::InvoiceSplitterV1InvoicePageGroup.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 74}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Page Indexes ' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/invoice_splitter/invoice_splitter_v1_page.rb b/lib/mindee/product/invoice_splitter/invoice_splitter_v1_page.rb deleted file mode 100644 index 3654c193c..000000000 --- a/lib/mindee/product/invoice_splitter/invoice_splitter_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'invoice_splitter_v1_document' - -module Mindee - module Product - module InvoiceSplitter - # Invoice Splitter API version 1.4 page data. - class InvoiceSplitterV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - InvoiceSplitterV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Invoice Splitter V1 page prediction. - class InvoiceSplitterV1PagePrediction < InvoiceSplitterV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1.rb b/lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1.rb deleted file mode 100644 index 46bfce456..000000000 --- a/lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'multi_receipts_detector_v1_document' -require_relative 'multi_receipts_detector_v1_page' - -module Mindee - module Product - # Multi Receipts Detector module. - module MultiReceiptsDetector - # Multi Receipts Detector API version 1 inference prediction. - class MultiReceiptsDetectorV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'multi_receipts_detector' - @endpoint_version = '1' - @has_async = false - @has_sync = true - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = MultiReceiptsDetectorV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(MultiReceiptsDetectorV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_document.rb b/lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_document.rb deleted file mode 100644 index 372b2b71a..000000000 --- a/lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_document.rb +++ /dev/null @@ -1,35 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module MultiReceiptsDetector - # Multi Receipts Detector API version 1.1 document data. - class MultiReceiptsDetectorV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # Positions of the receipts on the document. - # @return [Array] - attr_reader :receipts - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @receipts = [] # : Array[Parsing::Standard::PositionField] - prediction['receipts'].each do |item| - @receipts.push(Parsing::Standard::PositionField.new(item, page_id)) - end - end - - # @return [String] - def to_s - receipts = @receipts.join("\n #{' ' * 18}") - out_str = String.new - out_str << "\n:List of Receipts: #{receipts}".rstrip - out_str[1..].to_s - end - end - end - end -end diff --git a/lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_page.rb b/lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_page.rb deleted file mode 100644 index cb5d7568b..000000000 --- a/lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'multi_receipts_detector_v1_document' - -module Mindee - module Product - module MultiReceiptsDetector - # Multi Receipts Detector API version 1.1 page data. - class MultiReceiptsDetectorV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - MultiReceiptsDetectorV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Multi Receipts Detector V1 page prediction. - class MultiReceiptsDetectorV1PagePrediction < MultiReceiptsDetectorV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1.rb deleted file mode 100644 index 2cdc8cd13..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'nutrition_facts_label_v1_document' -require_relative 'nutrition_facts_label_v1_page' - -module Mindee - module Product - # Nutrition Facts Label module. - module NutritionFactsLabel - # Nutrition Facts Label API version 1 inference prediction. - class NutritionFactsLabelV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'nutrition_facts' - @endpoint_version = '1' - @has_async = true - @has_sync = false - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = NutritionFactsLabelV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(NutritionFactsLabelV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_added_sugar.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_added_sugar.rb deleted file mode 100644 index af705dbc6..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_added_sugar.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The amount of added sugars in the product. - class NutritionFactsLabelV1AddedSugar < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of added sugars to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of added sugars per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of added sugars per serving of the product. - # @return [Float] - attr_reader :per_serving - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_calorie.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_calorie.rb deleted file mode 100644 index e956fbe8d..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_calorie.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The amount of calories in the product. - class NutritionFactsLabelV1Calorie < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of calories to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of calories per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of calories per serving of the product. - # @return [Float] - attr_reader :per_serving - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_cholesterol.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_cholesterol.rb deleted file mode 100644 index b787fbbda..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_cholesterol.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The amount of cholesterol in the product. - class NutritionFactsLabelV1Cholesterol < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of cholesterol to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of cholesterol per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of cholesterol per serving of the product. - # @return [Float] - attr_reader :per_serving - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_dietary_fiber.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_dietary_fiber.rb deleted file mode 100644 index 5eeaebc1c..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_dietary_fiber.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The amount of dietary fiber in the product. - class NutritionFactsLabelV1DietaryFiber < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of dietary fiber to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of dietary fiber per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of dietary fiber per serving of the product. - # @return [Float] - attr_reader :per_serving - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_document.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_document.rb deleted file mode 100644 index 07c466d52..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_document.rb +++ /dev/null @@ -1,211 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'nutrition_facts_label_v1_serving_size' -require_relative 'nutrition_facts_label_v1_calorie' -require_relative 'nutrition_facts_label_v1_total_fat' -require_relative 'nutrition_facts_label_v1_saturated_fat' -require_relative 'nutrition_facts_label_v1_trans_fat' -require_relative 'nutrition_facts_label_v1_cholesterol' -require_relative 'nutrition_facts_label_v1_total_carbohydrate' -require_relative 'nutrition_facts_label_v1_dietary_fiber' -require_relative 'nutrition_facts_label_v1_total_sugar' -require_relative 'nutrition_facts_label_v1_added_sugar' -require_relative 'nutrition_facts_label_v1_protein' -require_relative 'nutrition_facts_label_v1_sodium' -require_relative 'nutrition_facts_label_v1_nutrients' - -module Mindee - module Product - module NutritionFactsLabel - # Nutrition Facts Label API version 1.0 document data. - class NutritionFactsLabelV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The amount of added sugars in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1AddedSugar] - attr_reader :added_sugars - # The amount of calories in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1Calorie] - attr_reader :calories - # The amount of cholesterol in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1Cholesterol] - attr_reader :cholesterol - # The amount of dietary fiber in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1DietaryFiber] - attr_reader :dietary_fiber - # The amount of nutrients in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1Nutrients] - attr_reader :nutrients - # The amount of protein in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1Protein] - attr_reader :protein - # The amount of saturated fat in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1SaturatedFat] - attr_reader :saturated_fat - # The number of servings in each box of the product. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :serving_per_box - # The size of a single serving of the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1ServingSize] - attr_reader :serving_size - # The amount of sodium in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1Sodium] - attr_reader :sodium - # The total amount of carbohydrates in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1TotalCarbohydrate] - attr_reader :total_carbohydrate - # The total amount of fat in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1TotalFat] - attr_reader :total_fat - # The total amount of sugars in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1TotalSugar] - attr_reader :total_sugars - # The amount of trans fat in the product. - # @return [Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1TransFat] - attr_reader :trans_fat - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @added_sugars = Product::NutritionFactsLabel::NutritionFactsLabelV1AddedSugar.new( - prediction['added_sugars'], - page_id - ) - @calories = Product::NutritionFactsLabel::NutritionFactsLabelV1Calorie.new( - prediction['calories'], - page_id - ) - @cholesterol = Product::NutritionFactsLabel::NutritionFactsLabelV1Cholesterol.new( - prediction['cholesterol'], - page_id - ) - @dietary_fiber = Product::NutritionFactsLabel::NutritionFactsLabelV1DietaryFiber.new( - prediction['dietary_fiber'], - page_id - ) - @nutrients = Product::NutritionFactsLabel::NutritionFactsLabelV1Nutrients.new( - prediction['nutrients'], page_id - ) - @protein = Product::NutritionFactsLabel::NutritionFactsLabelV1Protein.new( - prediction['protein'], - page_id - ) - @saturated_fat = Product::NutritionFactsLabel::NutritionFactsLabelV1SaturatedFat.new( - prediction['saturated_fat'], - page_id - ) - @serving_per_box = Parsing::Standard::AmountField.new( - prediction['serving_per_box'], - page_id - ) - @serving_size = Product::NutritionFactsLabel::NutritionFactsLabelV1ServingSize.new( - prediction['serving_size'], - page_id - ) - @sodium = Product::NutritionFactsLabel::NutritionFactsLabelV1Sodium.new( - prediction['sodium'], - page_id - ) - @total_carbohydrate = Product::NutritionFactsLabel::NutritionFactsLabelV1TotalCarbohydrate.new( - prediction['total_carbohydrate'], - page_id - ) - @total_fat = Product::NutritionFactsLabel::NutritionFactsLabelV1TotalFat.new( - prediction['total_fat'], - page_id - ) - @total_sugars = Product::NutritionFactsLabel::NutritionFactsLabelV1TotalSugar.new( - prediction['total_sugars'], - page_id - ) - @trans_fat = Product::NutritionFactsLabel::NutritionFactsLabelV1TransFat.new( - prediction['trans_fat'], - page_id - ) - end - - # @return [String] - def to_s - serving_size = @serving_size.to_s - calories = @calories.to_s - total_fat = @total_fat.to_s - saturated_fat = @saturated_fat.to_s - trans_fat = @trans_fat.to_s - cholesterol = @cholesterol.to_s - total_carbohydrate = @total_carbohydrate.to_s - dietary_fiber = @dietary_fiber.to_s - total_sugars = @total_sugars.to_s - added_sugars = @added_sugars.to_s - protein = @protein.to_s - sodium = @sodium.to_s - nutrients = nutrients_to_s - out_str = String.new - out_str << "\n:Serving per Box: #{@serving_per_box}".rstrip - out_str << "\n:Serving Size:" - out_str << serving_size - out_str << "\n:Calories:" - out_str << calories - out_str << "\n:Total Fat:" - out_str << total_fat - out_str << "\n:Saturated Fat:" - out_str << saturated_fat - out_str << "\n:Trans Fat:" - out_str << trans_fat - out_str << "\n:Cholesterol:" - out_str << cholesterol - out_str << "\n:Total Carbohydrate:" - out_str << total_carbohydrate - out_str << "\n:Dietary Fiber:" - out_str << dietary_fiber - out_str << "\n:Total Sugars:" - out_str << total_sugars - out_str << "\n:Added Sugars:" - out_str << added_sugars - out_str << "\n:Protein:" - out_str << protein - out_str << "\n:sodium:" - out_str << sodium - out_str << "\n:nutrients:" - out_str << nutrients - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def nutrients_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 13}" - out_str << "+#{char * 22}" - out_str << "+#{char * 10}" - out_str << "+#{char * 13}" - out_str << "+#{char * 6}" - out_str << '+' - out_str - end - - # @return [String] - def nutrients_to_s - return '' if @nutrients.empty? - - line_items = @nutrients.map(&:to_table_line).join("\n#{nutrients_separator('-')}\n ") - out_str = String.new - out_str << "\n#{nutrients_separator('-')}" - out_str << "\n |" - out_str << ' Daily Value |' - out_str << ' Name |' - out_str << ' Per 100g |' - out_str << ' Per Serving |' - out_str << ' Unit |' - out_str << "\n#{nutrients_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{nutrients_separator('-')}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrient.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrient.rb deleted file mode 100644 index cadc0aaa2..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrient.rb +++ /dev/null @@ -1,93 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The amount of nutrients in the product. - class NutritionFactsLabelV1Nutrient < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of nutrients to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The name of nutrients of the product. - # @return [String] - attr_reader :name - # The amount of nutrients per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of nutrients per serving of the product. - # @return [Float] - attr_reader :per_serving - # The unit of measurement for the amount of nutrients. - # @return [String] - attr_reader :unit - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @name = prediction['name'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @unit = prediction['unit'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:name] = format_for_display(@name) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable[:unit] = format_for_display(@unit) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:name] = format_for_display(@name, 20) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable[:unit] = format_for_display(@unit, nil) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 12s', printable[:daily_value]) - out_str << format('| %- 21s', printable[:name]) - out_str << format('| %- 9s', printable[:per_100g]) - out_str << format('| %- 12s', printable[:per_serving]) - out_str << format('| %- 5s', printable[:unit]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Name: #{printable[:name]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str << "\n :Unit: #{printable[:unit]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrients.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrients.rb deleted file mode 100644 index 995a9648b..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrients.rb +++ /dev/null @@ -1,68 +0,0 @@ -# frozen_string_literal: true - -require_relative 'nutrition_facts_label_v1_serving_size' -require_relative 'nutrition_facts_label_v1_calorie' -require_relative 'nutrition_facts_label_v1_total_fat' -require_relative 'nutrition_facts_label_v1_saturated_fat' -require_relative 'nutrition_facts_label_v1_trans_fat' -require_relative 'nutrition_facts_label_v1_cholesterol' -require_relative 'nutrition_facts_label_v1_total_carbohydrate' -require_relative 'nutrition_facts_label_v1_dietary_fiber' -require_relative 'nutrition_facts_label_v1_total_sugar' -require_relative 'nutrition_facts_label_v1_added_sugar' -require_relative 'nutrition_facts_label_v1_protein' -require_relative 'nutrition_facts_label_v1_sodium' -require_relative 'nutrition_facts_label_v1_nutrient' - -module Mindee - module Product - module NutritionFactsLabel - # The amount of nutrients in the product. - class NutritionFactsLabelV1Nutrients < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - NutritionFactsLabel::NutritionFactsLabelV1Nutrient.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 13}" - out_str << "+#{char * 22}" - out_str << "+#{char * 10}" - out_str << "+#{char * 13}" - out_str << "+#{char * 6}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Daily Value' - out_str << ' | Name ' - out_str << ' | Per 100g' - out_str << ' | Per Serving' - out_str << ' | Unit' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_page.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_page.rb deleted file mode 100644 index 5253ada9e..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'nutrition_facts_label_v1_document' - -module Mindee - module Product - module NutritionFactsLabel - # Nutrition Facts Label API version 1.0 page data. - class NutritionFactsLabelV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - NutritionFactsLabelV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Nutrition Facts Label V1 page prediction. - class NutritionFactsLabelV1PagePrediction < NutritionFactsLabelV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_protein.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_protein.rb deleted file mode 100644 index c6431683a..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_protein.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The amount of protein in the product. - class NutritionFactsLabelV1Protein < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of protein to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of protein per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of protein per serving of the product. - # @return [Float] - attr_reader :per_serving - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_saturated_fat.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_saturated_fat.rb deleted file mode 100644 index d6a5cd3ab..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_saturated_fat.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The amount of saturated fat in the product. - class NutritionFactsLabelV1SaturatedFat < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of saturated fat to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of saturated fat per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of saturated fat per serving of the product. - # @return [Float] - attr_reader :per_serving - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_serving_size.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_serving_size.rb deleted file mode 100644 index 0796094f0..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_serving_size.rb +++ /dev/null @@ -1,47 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The size of a single serving of the product. - class NutritionFactsLabelV1ServingSize < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The amount of a single serving. - # @return [Float] - attr_reader :amount - # The unit for the amount of a single serving. - # @return [String] - attr_reader :unit - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @amount = prediction['amount'] - @unit = prediction['unit'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:amount] = - @amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@amount) - printable[:unit] = format_for_display(@unit) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Amount: #{printable[:amount]}" - out_str << "\n :Unit: #{printable[:unit]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_sodium.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_sodium.rb deleted file mode 100644 index def207dc4..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_sodium.rb +++ /dev/null @@ -1,61 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The amount of sodium in the product. - class NutritionFactsLabelV1Sodium < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of sodium to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of sodium per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of sodium per serving of the product. - # @return [Float] - attr_reader :per_serving - # The unit of measurement for the amount of sodium. - # @return [String] - attr_reader :unit - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @unit = prediction['unit'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable[:unit] = format_for_display(@unit) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str << "\n :Unit: #{printable[:unit]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_carbohydrate.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_carbohydrate.rb deleted file mode 100644 index da21b79b4..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_carbohydrate.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The total amount of carbohydrates in the product. - class NutritionFactsLabelV1TotalCarbohydrate < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of total carbohydrates to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of total carbohydrates per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of total carbohydrates per serving of the product. - # @return [Float] - attr_reader :per_serving - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_fat.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_fat.rb deleted file mode 100644 index ba9732fcd..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_fat.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The total amount of fat in the product. - class NutritionFactsLabelV1TotalFat < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of total fat to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of total fat per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of total fat per serving of the product. - # @return [Float] - attr_reader :per_serving - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_sugar.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_sugar.rb deleted file mode 100644 index e7cde52c8..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_sugar.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The total amount of sugars in the product. - class NutritionFactsLabelV1TotalSugar < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of total sugars to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of total sugars per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of total sugars per serving of the product. - # @return [Float] - attr_reader :per_serving - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_trans_fat.rb b/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_trans_fat.rb deleted file mode 100644 index 9f4d00be8..000000000 --- a/lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_trans_fat.rb +++ /dev/null @@ -1,55 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module NutritionFactsLabel - # The amount of trans fat in the product. - class NutritionFactsLabelV1TransFat < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # DVs are the recommended amounts of trans fat to consume or not to exceed each day. - # @return [Float] - attr_reader :daily_value - # The amount of trans fat per 100g of the product. - # @return [Float] - attr_reader :per_100g - # The amount of trans fat per serving of the product. - # @return [Float] - attr_reader :per_serving - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @daily_value = prediction['daily_value'] - @per_100g = prediction['per_100g'] - @per_serving = prediction['per_serving'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:daily_value] = - @daily_value.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@daily_value) - printable[:per_100g] = - @per_100g.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_100g) - printable[:per_serving] = - @per_serving.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@per_serving) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Daily Value: #{printable[:daily_value]}" - out_str << "\n :Per 100g: #{printable[:per_100g]}" - out_str << "\n :Per Serving: #{printable[:per_serving]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/passport/passport_v1.rb b/lib/mindee/product/passport/passport_v1.rb deleted file mode 100644 index 378029349..000000000 --- a/lib/mindee/product/passport/passport_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'passport_v1_document' -require_relative 'passport_v1_page' - -module Mindee - module Product - # Passport module. - module Passport - # Passport API version 1 inference prediction. - class PassportV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'passport' - @endpoint_version = '1' - @has_async = false - @has_sync = true - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = PassportV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(PassportV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/passport/passport_v1_document.rb b/lib/mindee/product/passport/passport_v1_document.rb deleted file mode 100644 index 0d4f2d882..000000000 --- a/lib/mindee/product/passport/passport_v1_document.rb +++ /dev/null @@ -1,109 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module Passport - # Passport API version 1.1 document data. - class PassportV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The date of birth of the passport holder. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :birth_date - # The place of birth of the passport holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :birth_place - # The country's 3 letter code (ISO 3166-1 alpha-3). - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :country - # The expiry date of the passport. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :expiry_date - # The gender of the passport holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :gender - # The given name(s) of the passport holder. - # @return [Array] - attr_reader :given_names - # The passport's identification number. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :id_number - # The date the passport was issued. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :issuance_date - # Machine Readable Zone, first line - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz1 - # Machine Readable Zone, second line - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :mrz2 - # The surname of the passport holder. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :surname - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @birth_date = Parsing::Standard::DateField.new( - prediction['birth_date'], - page_id - ) - @birth_place = Parsing::Standard::StringField.new( - prediction['birth_place'], - page_id - ) - @country = Parsing::Standard::StringField.new( - prediction['country'], - page_id - ) - @expiry_date = Parsing::Standard::DateField.new( - prediction['expiry_date'], - page_id - ) - @gender = Parsing::Standard::StringField.new( - prediction['gender'], - page_id - ) - @given_names = [] # : Array[Parsing::Standard::StringField] - prediction['given_names'].each do |item| - @given_names.push(Parsing::Standard::StringField.new(item, page_id)) - end - @id_number = Parsing::Standard::StringField.new( - prediction['id_number'], - page_id - ) - @issuance_date = Parsing::Standard::DateField.new( - prediction['issuance_date'], - page_id - ) - @mrz1 = Parsing::Standard::StringField.new(prediction['mrz1'], page_id) - @mrz2 = Parsing::Standard::StringField.new(prediction['mrz2'], page_id) - @surname = Parsing::Standard::StringField.new( - prediction['surname'], - page_id - ) - end - - # @return [String] - def to_s - given_names = @given_names.join("\n #{' ' * 15}") - out_str = String.new - out_str << "\n:Country Code: #{@country}".rstrip - out_str << "\n:ID Number: #{@id_number}".rstrip - out_str << "\n:Given Name(s): #{given_names}".rstrip - out_str << "\n:Surname: #{@surname}".rstrip - out_str << "\n:Date of Birth: #{@birth_date}".rstrip - out_str << "\n:Place of Birth: #{@birth_place}".rstrip - out_str << "\n:Gender: #{@gender}".rstrip - out_str << "\n:Date of Issue: #{@issuance_date}".rstrip - out_str << "\n:Expiry Date: #{@expiry_date}".rstrip - out_str << "\n:MRZ Line 1: #{@mrz1}".rstrip - out_str << "\n:MRZ Line 2: #{@mrz2}".rstrip - out_str[1..].to_s - end - end - end - end -end diff --git a/lib/mindee/product/passport/passport_v1_page.rb b/lib/mindee/product/passport/passport_v1_page.rb deleted file mode 100644 index 5816f85bb..000000000 --- a/lib/mindee/product/passport/passport_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'passport_v1_document' - -module Mindee - module Product - module Passport - # Passport API version 1.1 page data. - class PassportV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - PassportV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Passport V1 page prediction. - class PassportV1PagePrediction < PassportV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/receipt/receipt_v5.rb b/lib/mindee/product/receipt/receipt_v5.rb deleted file mode 100644 index ce1b3c48f..000000000 --- a/lib/mindee/product/receipt/receipt_v5.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'receipt_v5_document' -require_relative 'receipt_v5_page' - -module Mindee - module Product - # Receipt module. - module Receipt - # Receipt API version 5 inference prediction. - class ReceiptV5 < Mindee::Parsing::Common::Inference - @endpoint_name = 'expense_receipts' - @endpoint_version = '5' - @has_async = true - @has_sync = true - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = ReceiptV5Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(ReceiptV5Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/receipt/receipt_v5_document.rb b/lib/mindee/product/receipt/receipt_v5_document.rb deleted file mode 100644 index 4532f8734..000000000 --- a/lib/mindee/product/receipt/receipt_v5_document.rb +++ /dev/null @@ -1,184 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'receipt_v5_line_items' - -module Mindee - module Product - module Receipt - # Receipt API version 5.4 document data. - class ReceiptV5Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The purchase category of the receipt. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :category - # The date the purchase was made. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :date - # The type of receipt: EXPENSE RECEIPT or CREDIT CARD RECEIPT. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :document_type - # List of all line items on the receipt. - # @return [Mindee::Product::Receipt::ReceiptV5LineItems] - attr_reader :line_items - # The locale of the document. - # @return [Mindee::Parsing::Standard::LocaleField] - attr_reader :locale - # The receipt number or identifier. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :receipt_number - # The purchase subcategory of the receipt for transport and food. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :subcategory - # The address of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_address - # List of company registration numbers associated to the supplier. - # @return [Array] - attr_reader :supplier_company_registrations - # The name of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_name - # The phone number of the supplier or merchant. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :supplier_phone_number - # The list of taxes present on the receipt. - # @return [Mindee::Parsing::Standard::Taxes] - attr_reader :taxes - # The time the purchase was made. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :time - # The total amount of tip and gratuity. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :tip - # The total amount paid: includes taxes, discounts, fees, tips, and gratuity. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_amount - # The net amount paid: does not include taxes, fees, and discounts. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_net - # The sum of all taxes. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :total_tax - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @category = Parsing::Standard::ClassificationField.new( - prediction['category'], - page_id - ) - @date = Parsing::Standard::DateField.new(prediction['date'], page_id) - @document_type = Parsing::Standard::ClassificationField.new( - prediction['document_type'], - page_id - ) - @line_items = Product::Receipt::ReceiptV5LineItems.new(prediction['line_items'], page_id) - @locale = Parsing::Standard::LocaleField.new( - prediction['locale'], - page_id - ) - @receipt_number = Parsing::Standard::StringField.new( - prediction['receipt_number'], - page_id - ) - @subcategory = Parsing::Standard::ClassificationField.new( - prediction['subcategory'], - page_id - ) - @supplier_address = Parsing::Standard::StringField.new( - prediction['supplier_address'], - page_id - ) - @supplier_company_registrations = [] # : Array[Parsing::Standard::CompanyRegistrationField] - prediction['supplier_company_registrations'].each do |item| - @supplier_company_registrations.push(Parsing::Standard::CompanyRegistrationField.new(item, page_id)) - end - @supplier_name = Parsing::Standard::StringField.new( - prediction['supplier_name'], - page_id - ) - @supplier_phone_number = Parsing::Standard::StringField.new( - prediction['supplier_phone_number'], - page_id - ) - @taxes = Parsing::Standard::Taxes.new(prediction['taxes'], page_id) - @time = Parsing::Standard::StringField.new(prediction['time'], page_id) - @tip = Parsing::Standard::AmountField.new(prediction['tip'], page_id) - @total_amount = Parsing::Standard::AmountField.new( - prediction['total_amount'], - page_id - ) - @total_net = Parsing::Standard::AmountField.new( - prediction['total_net'], - page_id - ) - @total_tax = Parsing::Standard::AmountField.new( - prediction['total_tax'], - page_id - ) - end - - # @return [String] - def to_s - supplier_company_registrations = @supplier_company_registrations.join("\n #{' ' * 32}") - line_items = line_items_to_s - out_str = String.new - out_str << "\n:Expense Locale: #{@locale}".rstrip - out_str << "\n:Purchase Category: #{@category}".rstrip - out_str << "\n:Purchase Subcategory: #{@subcategory}".rstrip - out_str << "\n:Document Type: #{@document_type}".rstrip - out_str << "\n:Purchase Date: #{@date}".rstrip - out_str << "\n:Purchase Time: #{@time}".rstrip - out_str << "\n:Total Amount: #{@total_amount}".rstrip - out_str << "\n:Total Net: #{@total_net}".rstrip - out_str << "\n:Total Tax: #{@total_tax}".rstrip - out_str << "\n:Tip and Gratuity: #{@tip}".rstrip - out_str << "\n:Taxes:#{@taxes}".rstrip - out_str << "\n:Supplier Name: #{@supplier_name}".rstrip - out_str << "\n:Supplier Company Registrations: #{supplier_company_registrations}".rstrip - out_str << "\n:Supplier Address: #{@supplier_address}".rstrip - out_str << "\n:Supplier Phone Number: #{@supplier_phone_number}".rstrip - out_str << "\n:Receipt Number: #{@receipt_number}".rstrip - out_str << "\n:Line Items:" - out_str << line_items - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def line_items_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 38}" - out_str << "+#{char * 10}" - out_str << "+#{char * 14}" - out_str << "+#{char * 12}" - out_str << '+' - out_str - end - - # @return [String] - def line_items_to_s - return '' if @line_items.empty? - - line_items = @line_items.map(&:to_table_line).join("\n#{line_items_separator('-')}\n ") - out_str = String.new - out_str << "\n#{line_items_separator('-')}" - out_str << "\n |" - out_str << ' Description |' - out_str << ' Quantity |' - out_str << ' Total Amount |' - out_str << ' Unit Price |' - out_str << "\n#{line_items_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{line_items_separator('-')}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/receipt/receipt_v5_line_item.rb b/lib/mindee/product/receipt/receipt_v5_line_item.rb deleted file mode 100644 index afb5f1743..000000000 --- a/lib/mindee/product/receipt/receipt_v5_line_item.rb +++ /dev/null @@ -1,85 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module Receipt - # List of all line items on the receipt. - class ReceiptV5LineItem < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The item description. - # @return [String] - attr_reader :description - # The item quantity. - # @return [Float] - attr_reader :quantity - # The item total amount. - # @return [Float] - attr_reader :total_amount - # The item unit price. - # @return [Float] - attr_reader :unit_price - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @description = prediction['description'] - @quantity = prediction['quantity'] - @total_amount = prediction['total_amount'] - @unit_price = prediction['unit_price'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:description] = format_for_display(@description) - printable[:quantity] = - @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) - printable[:total_amount] = - @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:description] = format_for_display(@description, 36) - printable[:quantity] = - @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) - printable[:total_amount] = - @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) - printable[:unit_price] = - @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 37s', printable[:description]) - out_str << format('| %- 9s', printable[:quantity]) - out_str << format('| %- 13s', printable[:total_amount]) - out_str << format('| %- 11s', printable[:unit_price]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Description: #{printable[:description]}" - out_str << "\n :Quantity: #{printable[:quantity]}" - out_str << "\n :Total Amount: #{printable[:total_amount]}" - out_str << "\n :Unit Price: #{printable[:unit_price]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/receipt/receipt_v5_line_items.rb b/lib/mindee/product/receipt/receipt_v5_line_items.rb deleted file mode 100644 index 18f3729bf..000000000 --- a/lib/mindee/product/receipt/receipt_v5_line_items.rb +++ /dev/null @@ -1,54 +0,0 @@ -# frozen_string_literal: true - -require_relative 'receipt_v5_line_item' - -module Mindee - module Product - module Receipt - # List of all line items on the receipt. - class ReceiptV5LineItems < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - Receipt::ReceiptV5LineItem.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 38}" - out_str << "+#{char * 10}" - out_str << "+#{char * 14}" - out_str << "+#{char * 12}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Description ' - out_str << ' | Quantity' - out_str << ' | Total Amount' - out_str << ' | Unit Price' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/receipt/receipt_v5_page.rb b/lib/mindee/product/receipt/receipt_v5_page.rb deleted file mode 100644 index 45f356e8f..000000000 --- a/lib/mindee/product/receipt/receipt_v5_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'receipt_v5_document' - -module Mindee - module Product - module Receipt - # Receipt API version 5.4 page data. - class ReceiptV5Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - ReceiptV5PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Receipt V5 page prediction. - class ReceiptV5PagePrediction < ReceiptV5Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1.rb b/lib/mindee/product/resume/resume_v1.rb deleted file mode 100644 index 3314ab1cd..000000000 --- a/lib/mindee/product/resume/resume_v1.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'resume_v1_document' -require_relative 'resume_v1_page' - -module Mindee - module Product - # Resume module. - module Resume - # Resume API version 1 inference prediction. - class ResumeV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'resume' - @endpoint_version = '1' - @has_async = true - @has_sync = false - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = ResumeV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(ResumeV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_certificate.rb b/lib/mindee/product/resume/resume_v1_certificate.rb deleted file mode 100644 index c18d2d555..000000000 --- a/lib/mindee/product/resume/resume_v1_certificate.rb +++ /dev/null @@ -1,79 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module Resume - # The list of certificates obtained by the candidate. - class ResumeV1Certificate < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The grade obtained for the certificate. - # @return [String] - attr_reader :grade - # The name of certification. - # @return [String] - attr_reader :name - # The organization or institution that issued the certificate. - # @return [String] - attr_reader :provider - # The year when a certificate was issued or received. - # @return [String] - attr_reader :year - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @grade = prediction['grade'] - @name = prediction['name'] - @provider = prediction['provider'] - @year = prediction['year'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:grade] = format_for_display(@grade) - printable[:name] = format_for_display(@name) - printable[:provider] = format_for_display(@provider) - printable[:year] = format_for_display(@year) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:grade] = format_for_display(@grade, 10) - printable[:name] = format_for_display(@name, 30) - printable[:provider] = format_for_display(@provider, 25) - printable[:year] = format_for_display(@year, nil) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 11s', printable[:grade]) - out_str << format('| %- 31s', printable[:name]) - out_str << format('| %- 26s', printable[:provider]) - out_str << format('| %- 5s', printable[:year]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Grade: #{printable[:grade]}" - out_str << "\n :Name: #{printable[:name]}" - out_str << "\n :Provider: #{printable[:provider]}" - out_str << "\n :Year: #{printable[:year]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_certificates.rb b/lib/mindee/product/resume/resume_v1_certificates.rb deleted file mode 100644 index 076a30320..000000000 --- a/lib/mindee/product/resume/resume_v1_certificates.rb +++ /dev/null @@ -1,58 +0,0 @@ -# frozen_string_literal: true - -require_relative 'resume_v1_social_networks_url' -require_relative 'resume_v1_language' -require_relative 'resume_v1_education' -require_relative 'resume_v1_professional_experience' -require_relative 'resume_v1_certificate' - -module Mindee - module Product - module Resume - # The list of certificates obtained by the candidate. - class ResumeV1Certificates < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - Resume::ResumeV1Certificate.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 12}" - out_str << "+#{char * 32}" - out_str << "+#{char * 27}" - out_str << "+#{char * 6}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Grade ' - out_str << ' | Name ' - out_str << ' | Provider ' - out_str << ' | Year' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_document.rb b/lib/mindee/product/resume/resume_v1_document.rb deleted file mode 100644 index 3cd11331a..000000000 --- a/lib/mindee/product/resume/resume_v1_document.rb +++ /dev/null @@ -1,337 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'resume_v1_social_networks_urls' -require_relative 'resume_v1_languages' -require_relative 'resume_v1_educations' -require_relative 'resume_v1_professional_experiences' -require_relative 'resume_v1_certificates' - -module Mindee - module Product - module Resume - # Resume API version 1.2 document data. - class ResumeV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The location information of the candidate, including city, state, and country. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :address - # The list of certificates obtained by the candidate. - # @return [Mindee::Product::Resume::ResumeV1Certificates] - attr_reader :certificates - # The ISO 639 code of the language in which the document is written. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :document_language - # The type of the document sent. - # @return [Mindee::Parsing::Standard::ClassificationField] - attr_reader :document_type - # The list of the candidate's educational background. - # @return [Mindee::Product::Resume::ResumeV1Educations] - attr_reader :education - # The email address of the candidate. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :email_address - # The candidate's first or given names. - # @return [Array] - attr_reader :given_names - # The list of the candidate's technical abilities and knowledge. - # @return [Array] - attr_reader :hard_skills - # The position that the candidate is applying for. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :job_applied - # The list of languages that the candidate is proficient in. - # @return [Mindee::Product::Resume::ResumeV1Languages] - attr_reader :languages - # The ISO 3166 code for the country of citizenship of the candidate. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :nationality - # The phone number of the candidate. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :phone_number - # The candidate's current profession. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :profession - # The list of the candidate's professional experiences. - # @return [Mindee::Product::Resume::ResumeV1ProfessionalExperiences] - attr_reader :professional_experiences - # The list of social network profiles of the candidate. - # @return [Mindee::Product::Resume::ResumeV1SocialNetworksUrls] - attr_reader :social_networks_urls - # The list of the candidate's interpersonal and communication abilities. - # @return [Array] - attr_reader :soft_skills - # The candidate's last names. - # @return [Array] - attr_reader :surnames - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @address = Parsing::Standard::StringField.new( - prediction['address'], - page_id - ) - @certificates = Product::Resume::ResumeV1Certificates.new(prediction['certificates'], page_id) - @document_language = Parsing::Standard::StringField.new( - prediction['document_language'], - page_id - ) - @document_type = Parsing::Standard::ClassificationField.new( - prediction['document_type'], - page_id - ) - @education = Product::Resume::ResumeV1Educations.new(prediction['education'], page_id) - @email_address = Parsing::Standard::StringField.new( - prediction['email_address'], - page_id - ) - @given_names = [] # : Array[Parsing::Standard::StringField] - prediction['given_names'].each do |item| - @given_names.push(Parsing::Standard::StringField.new(item, page_id)) - end - @hard_skills = [] # : Array[Parsing::Standard::StringField] - prediction['hard_skills'].each do |item| - @hard_skills.push(Parsing::Standard::StringField.new(item, page_id)) - end - @job_applied = Parsing::Standard::StringField.new( - prediction['job_applied'], - page_id - ) - @languages = Product::Resume::ResumeV1Languages.new(prediction['languages'], page_id) - @nationality = Parsing::Standard::StringField.new( - prediction['nationality'], - page_id - ) - @phone_number = Parsing::Standard::StringField.new( - prediction['phone_number'], - page_id - ) - @profession = Parsing::Standard::StringField.new( - prediction['profession'], - page_id - ) - @professional_experiences = Product::Resume::ResumeV1ProfessionalExperiences.new( - prediction['professional_experiences'], page_id - ) - @social_networks_urls = Product::Resume::ResumeV1SocialNetworksUrls.new( - prediction['social_networks_urls'], page_id - ) - @soft_skills = [] # : Array[Parsing::Standard::StringField] - prediction['soft_skills'].each do |item| - @soft_skills.push(Parsing::Standard::StringField.new(item, page_id)) - end - @surnames = [] # : Array[Parsing::Standard::StringField] - prediction['surnames'].each do |item| - @surnames.push(Parsing::Standard::StringField.new(item, page_id)) - end - end - - # @return [String] - def to_s - given_names = @given_names.join("\n #{' ' * 13}") - surnames = @surnames.join("\n #{' ' * 10}") - social_networks_urls = social_networks_urls_to_s - languages = languages_to_s - hard_skills = @hard_skills.join("\n #{' ' * 13}") - soft_skills = @soft_skills.join("\n #{' ' * 13}") - education = education_to_s - professional_experiences = professional_experiences_to_s - certificates = certificates_to_s - out_str = String.new - out_str << "\n:Document Language: #{@document_language}".rstrip - out_str << "\n:Document Type: #{@document_type}".rstrip - out_str << "\n:Given Names: #{given_names}".rstrip - out_str << "\n:Surnames: #{surnames}".rstrip - out_str << "\n:Nationality: #{@nationality}".rstrip - out_str << "\n:Email Address: #{@email_address}".rstrip - out_str << "\n:Phone Number: #{@phone_number}".rstrip - out_str << "\n:Address: #{@address}".rstrip - out_str << "\n:Social Networks:" - out_str << social_networks_urls - out_str << "\n:Profession: #{@profession}".rstrip - out_str << "\n:Job Applied: #{@job_applied}".rstrip - out_str << "\n:Languages:" - out_str << languages - out_str << "\n:Hard Skills: #{hard_skills}".rstrip - out_str << "\n:Soft Skills: #{soft_skills}".rstrip - out_str << "\n:Education:" - out_str << education - out_str << "\n:Professional Experiences:" - out_str << professional_experiences - out_str << "\n:Certificates:" - out_str << certificates - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def social_networks_urls_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 22}" - out_str << "+#{char * 52}" - out_str << '+' - out_str - end - - # @return [String] - def social_networks_urls_to_s - return '' if @social_networks_urls.empty? - - line_items = @social_networks_urls.map(&:to_table_line).join("\n#{social_networks_urls_separator('-')}\n ") - out_str = String.new - out_str << "\n#{social_networks_urls_separator('-')}" - out_str << "\n |" - out_str << ' Name |' - out_str << ' URL |' - out_str << "\n#{social_networks_urls_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{social_networks_urls_separator('-')}" - out_str - end - - # @param char [String] - # @return [String] - def languages_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 10}" - out_str << "+#{char * 22}" - out_str << '+' - out_str - end - - # @return [String] - def languages_to_s - return '' if @languages.empty? - - line_items = @languages.map(&:to_table_line).join("\n#{languages_separator('-')}\n ") - out_str = String.new - out_str << "\n#{languages_separator('-')}" - out_str << "\n |" - out_str << ' Language |' - out_str << ' Level |' - out_str << "\n#{languages_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{languages_separator('-')}" - out_str - end - - # @param char [String] - # @return [String] - def education_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 17}" - out_str << "+#{char * 27}" - out_str << "+#{char * 11}" - out_str << "+#{char * 10}" - out_str << "+#{char * 27}" - out_str << "+#{char * 13}" - out_str << "+#{char * 12}" - out_str << '+' - out_str - end - - # @return [String] - def education_to_s - return '' if @education.empty? - - line_items = @education.map(&:to_table_line).join("\n#{education_separator('-')}\n ") - out_str = String.new - out_str << "\n#{education_separator('-')}" - out_str << "\n |" - out_str << ' Domain |' - out_str << ' Degree |' - out_str << ' End Month |' - out_str << ' End Year |' - out_str << ' School |' - out_str << ' Start Month |' - out_str << ' Start Year |' - out_str << "\n#{education_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{education_separator('-')}" - out_str - end - - # @param char [String] - # @return [String] - def professional_experiences_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 17}" - out_str << "+#{char * 12}" - out_str << "+#{char * 38}" - out_str << "+#{char * 27}" - out_str << "+#{char * 11}" - out_str << "+#{char * 10}" - out_str << "+#{char * 22}" - out_str << "+#{char * 13}" - out_str << "+#{char * 12}" - out_str << '+' - out_str - end - - # @return [String] - def professional_experiences_to_s - return '' if @professional_experiences.empty? - - line_items = @professional_experiences.map(&:to_table_line).join( - "\n#{professional_experiences_separator('-')}\n " - ) - out_str = String.new - out_str << "\n#{professional_experiences_separator('-')}" - out_str << "\n |" - out_str << ' Contract Type |' - out_str << ' Department |' - out_str << ' Description |' - out_str << ' Employer |' - out_str << ' End Month |' - out_str << ' End Year |' - out_str << ' Role |' - out_str << ' Start Month |' - out_str << ' Start Year |' - out_str << "\n#{professional_experiences_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{professional_experiences_separator('-')}" - out_str - end - - # @param char [String] - # @return [String] - def certificates_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 12}" - out_str << "+#{char * 32}" - out_str << "+#{char * 27}" - out_str << "+#{char * 6}" - out_str << '+' - out_str - end - - # @return [String] - def certificates_to_s - return '' if @certificates.empty? - - line_items = @certificates.map(&:to_table_line).join("\n#{certificates_separator('-')}\n ") - out_str = String.new - out_str << "\n#{certificates_separator('-')}" - out_str << "\n |" - out_str << ' Grade |' - out_str << ' Name |' - out_str << ' Provider |' - out_str << ' Year |' - out_str << "\n#{certificates_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{certificates_separator('-')}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_education.rb b/lib/mindee/product/resume/resume_v1_education.rb deleted file mode 100644 index 97da43d11..000000000 --- a/lib/mindee/product/resume/resume_v1_education.rb +++ /dev/null @@ -1,103 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module Resume - # The list of the candidate's educational background. - class ResumeV1Education < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The area of study or specialization. - # @return [String] - attr_reader :degree_domain - # The type of degree obtained, such as Bachelor's, Master's, or Doctorate. - # @return [String] - attr_reader :degree_type - # The month when the education program or course was completed. - # @return [String] - attr_reader :end_month - # The year when the education program or course was completed. - # @return [String] - attr_reader :end_year - # The name of the school. - # @return [String] - attr_reader :school - # The month when the education program or course began. - # @return [String] - attr_reader :start_month - # The year when the education program or course began. - # @return [String] - attr_reader :start_year - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @degree_domain = prediction['degree_domain'] - @degree_type = prediction['degree_type'] - @end_month = prediction['end_month'] - @end_year = prediction['end_year'] - @school = prediction['school'] - @start_month = prediction['start_month'] - @start_year = prediction['start_year'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:degree_domain] = format_for_display(@degree_domain) - printable[:degree_type] = format_for_display(@degree_type) - printable[:end_month] = format_for_display(@end_month) - printable[:end_year] = format_for_display(@end_year) - printable[:school] = format_for_display(@school) - printable[:start_month] = format_for_display(@start_month) - printable[:start_year] = format_for_display(@start_year) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:degree_domain] = format_for_display(@degree_domain, 15) - printable[:degree_type] = format_for_display(@degree_type, 25) - printable[:end_month] = format_for_display(@end_month, nil) - printable[:end_year] = format_for_display(@end_year, nil) - printable[:school] = format_for_display(@school, 25) - printable[:start_month] = format_for_display(@start_month, nil) - printable[:start_year] = format_for_display(@start_year, nil) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 16s', printable[:degree_domain]) - out_str << format('| %- 26s', printable[:degree_type]) - out_str << format('| %- 10s', printable[:end_month]) - out_str << format('| %- 9s', printable[:end_year]) - out_str << format('| %- 26s', printable[:school]) - out_str << format('| %- 12s', printable[:start_month]) - out_str << format('| %- 11s', printable[:start_year]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Domain: #{printable[:degree_domain]}" - out_str << "\n :Degree: #{printable[:degree_type]}" - out_str << "\n :End Month: #{printable[:end_month]}" - out_str << "\n :End Year: #{printable[:end_year]}" - out_str << "\n :School: #{printable[:school]}" - out_str << "\n :Start Month: #{printable[:start_month]}" - out_str << "\n :Start Year: #{printable[:start_year]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_educations.rb b/lib/mindee/product/resume/resume_v1_educations.rb deleted file mode 100644 index 177789ea5..000000000 --- a/lib/mindee/product/resume/resume_v1_educations.rb +++ /dev/null @@ -1,64 +0,0 @@ -# frozen_string_literal: true - -require_relative 'resume_v1_social_networks_url' -require_relative 'resume_v1_language' -require_relative 'resume_v1_education' -require_relative 'resume_v1_professional_experience' -require_relative 'resume_v1_certificate' - -module Mindee - module Product - module Resume - # The list of the candidate's educational background. - class ResumeV1Educations < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - Resume::ResumeV1Education.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 17}" - out_str << "+#{char * 27}" - out_str << "+#{char * 11}" - out_str << "+#{char * 10}" - out_str << "+#{char * 27}" - out_str << "+#{char * 13}" - out_str << "+#{char * 12}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Domain ' - out_str << ' | Degree ' - out_str << ' | End Month' - out_str << ' | End Year' - out_str << ' | School ' - out_str << ' | Start Month' - out_str << ' | Start Year' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_language.rb b/lib/mindee/product/resume/resume_v1_language.rb deleted file mode 100644 index 0e640b752..000000000 --- a/lib/mindee/product/resume/resume_v1_language.rb +++ /dev/null @@ -1,63 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module Resume - # The list of languages that the candidate is proficient in. - class ResumeV1Language < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The language's ISO 639 code. - # @return [String] - attr_reader :language - # The candidate's level for the language. - # @return [String] - attr_reader :level - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @language = prediction['language'] - @level = prediction['level'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:language] = format_for_display(@language) - printable[:level] = format_for_display(@level) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:language] = format_for_display(@language, nil) - printable[:level] = format_for_display(@level, 20) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 9s', printable[:language]) - out_str << format('| %- 21s', printable[:level]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Language: #{printable[:language]}" - out_str << "\n :Level: #{printable[:level]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_languages.rb b/lib/mindee/product/resume/resume_v1_languages.rb deleted file mode 100644 index cbb766f71..000000000 --- a/lib/mindee/product/resume/resume_v1_languages.rb +++ /dev/null @@ -1,54 +0,0 @@ -# frozen_string_literal: true - -require_relative 'resume_v1_social_networks_url' -require_relative 'resume_v1_language' -require_relative 'resume_v1_education' -require_relative 'resume_v1_professional_experience' -require_relative 'resume_v1_certificate' - -module Mindee - module Product - module Resume - # The list of languages that the candidate is proficient in. - class ResumeV1Languages < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - Resume::ResumeV1Language.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 10}" - out_str << "+#{char * 22}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Language' - out_str << ' | Level ' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_page.rb b/lib/mindee/product/resume/resume_v1_page.rb deleted file mode 100644 index 2032a349a..000000000 --- a/lib/mindee/product/resume/resume_v1_page.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'resume_v1_document' - -module Mindee - module Product - module Resume - # Resume API version 1.2 page data. - class ResumeV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - ResumeV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Resume V1 page prediction. - class ResumeV1PagePrediction < ResumeV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_professional_experience.rb b/lib/mindee/product/resume/resume_v1_professional_experience.rb deleted file mode 100644 index 23c5aa5fb..000000000 --- a/lib/mindee/product/resume/resume_v1_professional_experience.rb +++ /dev/null @@ -1,119 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module Resume - # The list of the candidate's professional experiences. - class ResumeV1ProfessionalExperience < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The type of contract for the professional experience. - # @return [String] - attr_reader :contract_type - # The specific department or division within the company. - # @return [String] - attr_reader :department - # The description of the professional experience as written in the document. - # @return [String] - attr_reader :description - # The name of the company or organization. - # @return [String] - attr_reader :employer - # The month when the professional experience ended. - # @return [String] - attr_reader :end_month - # The year when the professional experience ended. - # @return [String] - attr_reader :end_year - # The position or job title held by the candidate. - # @return [String] - attr_reader :role - # The month when the professional experience began. - # @return [String] - attr_reader :start_month - # The year when the professional experience began. - # @return [String] - attr_reader :start_year - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @contract_type = prediction['contract_type'] - @department = prediction['department'] - @description = prediction['description'] - @employer = prediction['employer'] - @end_month = prediction['end_month'] - @end_year = prediction['end_year'] - @role = prediction['role'] - @start_month = prediction['start_month'] - @start_year = prediction['start_year'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:contract_type] = format_for_display(@contract_type) - printable[:department] = format_for_display(@department) - printable[:description] = format_for_display(@description) - printable[:employer] = format_for_display(@employer) - printable[:end_month] = format_for_display(@end_month) - printable[:end_year] = format_for_display(@end_year) - printable[:role] = format_for_display(@role) - printable[:start_month] = format_for_display(@start_month) - printable[:start_year] = format_for_display(@start_year) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:contract_type] = format_for_display(@contract_type, 15) - printable[:department] = format_for_display(@department, 10) - printable[:description] = format_for_display(@description, 36) - printable[:employer] = format_for_display(@employer, 25) - printable[:end_month] = format_for_display(@end_month, nil) - printable[:end_year] = format_for_display(@end_year, nil) - printable[:role] = format_for_display(@role, 20) - printable[:start_month] = format_for_display(@start_month, nil) - printable[:start_year] = format_for_display(@start_year, nil) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 16s', printable[:contract_type]) - out_str << format('| %- 11s', printable[:department]) - out_str << format('| %- 37s', printable[:description]) - out_str << format('| %- 26s', printable[:employer]) - out_str << format('| %- 10s', printable[:end_month]) - out_str << format('| %- 9s', printable[:end_year]) - out_str << format('| %- 21s', printable[:role]) - out_str << format('| %- 12s', printable[:start_month]) - out_str << format('| %- 11s', printable[:start_year]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Contract Type: #{printable[:contract_type]}" - out_str << "\n :Department: #{printable[:department]}" - out_str << "\n :Description: #{printable[:description]}" - out_str << "\n :Employer: #{printable[:employer]}" - out_str << "\n :End Month: #{printable[:end_month]}" - out_str << "\n :End Year: #{printable[:end_year]}" - out_str << "\n :Role: #{printable[:role]}" - out_str << "\n :Start Month: #{printable[:start_month]}" - out_str << "\n :Start Year: #{printable[:start_year]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_professional_experiences.rb b/lib/mindee/product/resume/resume_v1_professional_experiences.rb deleted file mode 100644 index 4e0bcab0e..000000000 --- a/lib/mindee/product/resume/resume_v1_professional_experiences.rb +++ /dev/null @@ -1,68 +0,0 @@ -# frozen_string_literal: true - -require_relative 'resume_v1_social_networks_url' -require_relative 'resume_v1_language' -require_relative 'resume_v1_education' -require_relative 'resume_v1_professional_experience' -require_relative 'resume_v1_certificate' - -module Mindee - module Product - module Resume - # The list of the candidate's professional experiences. - class ResumeV1ProfessionalExperiences < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - Resume::ResumeV1ProfessionalExperience.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 17}" - out_str << "+#{char * 12}" - out_str << "+#{char * 38}" - out_str << "+#{char * 27}" - out_str << "+#{char * 11}" - out_str << "+#{char * 10}" - out_str << "+#{char * 22}" - out_str << "+#{char * 13}" - out_str << "+#{char * 12}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Contract Type ' - out_str << ' | Department' - out_str << ' | Description ' - out_str << ' | Employer ' - out_str << ' | End Month' - out_str << ' | End Year' - out_str << ' | Role ' - out_str << ' | Start Month' - out_str << ' | Start Year' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_social_networks_url.rb b/lib/mindee/product/resume/resume_v1_social_networks_url.rb deleted file mode 100644 index 063b4cbfd..000000000 --- a/lib/mindee/product/resume/resume_v1_social_networks_url.rb +++ /dev/null @@ -1,63 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module Resume - # The list of social network profiles of the candidate. - class ResumeV1SocialNetworksUrl < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The name of the social network. - # @return [String] - attr_reader :name - # The URL of the social network. - # @return [String] - attr_reader :url - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @name = prediction['name'] - @url = prediction['url'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:name] = format_for_display(@name) - printable[:url] = format_for_display(@url) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:name] = format_for_display(@name, 20) - printable[:url] = format_for_display(@url, 50) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 21s', printable[:name]) - out_str << format('| %- 51s', printable[:url]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Name: #{printable[:name]}" - out_str << "\n :URL: #{printable[:url]}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/resume/resume_v1_social_networks_urls.rb b/lib/mindee/product/resume/resume_v1_social_networks_urls.rb deleted file mode 100644 index 3f8e18839..000000000 --- a/lib/mindee/product/resume/resume_v1_social_networks_urls.rb +++ /dev/null @@ -1,54 +0,0 @@ -# frozen_string_literal: true - -require_relative 'resume_v1_social_networks_url' -require_relative 'resume_v1_language' -require_relative 'resume_v1_education' -require_relative 'resume_v1_professional_experience' -require_relative 'resume_v1_certificate' - -module Mindee - module Product - module Resume - # The list of social network profiles of the candidate. - class ResumeV1SocialNetworksUrls < Array - # Entries. - # @return [Array] - attr_reader :entries - - # @param prediction [Array] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - entries = prediction.map do |entry| - Resume::ResumeV1SocialNetworksUrl.new(entry, page_id) - end - super(entries) - end - - # Creates a line of rST table-compliant string separators. - # @param char [String] Character to use as a separator. - # @return [String] - def self.line_items_separator(char) - out_str = String.new - out_str << "+#{char * 22}" - out_str << "+#{char * 52}" - out_str - end - - # @return [String] - def to_s - return '' if empty? - - lines = map do |entry| - "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" - end.join - out_str = String.new - out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Name ' - out_str << ' | URL ' - out_str << " |\n#{self.class.line_items_separator('=')}" - out_str + lines - end - end - end - end -end diff --git a/lib/mindee/product/universal/universal.rb b/lib/mindee/product/universal/universal.rb deleted file mode 100644 index 7869bfb66..000000000 --- a/lib/mindee/product/universal/universal.rb +++ /dev/null @@ -1,46 +0,0 @@ -# frozen_string_literal: true - -require_relative 'universal_document' -require_relative 'universal_page' - -module Mindee - module Product - # Universal product module. - module Universal - # Universal Document V1 prediction inference. - class Universal < Mindee::Parsing::Common::Inference - @endpoint_name = '' - @endpoint_version = '' - @has_sync = true - @has_async = true - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = UniversalDocument.new(prediction['prediction']) - @pages = [] # : Array[Mindee::Parsing::Common::Page] - prediction['pages'].each do |page| - if page.key?('prediction') && !page['prediction'].nil? && !page['prediction'].empty? - @pages.push(UniversalPage.new(page)) - end - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end -end diff --git a/lib/mindee/product/universal/universal_document.rb b/lib/mindee/product/universal/universal_document.rb deleted file mode 100644 index 7ea2e9ff5..000000000 --- a/lib/mindee/product/universal/universal_document.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'universal_prediction' - -module Mindee - module Product - module Universal - # Universal Document V1 prediction - class UniversalDocument < Mindee::Product::Universal::UniversalPrediction - include Mindee::Parsing::Standard - # @param raw_prediction [Hash] - def initialize(raw_prediction) - super - raw_prediction.each do |field_name, field_contents| - if field_contents.is_a?(Array) - @fields[field_name] = Parsing::Universal::UniversalListField.new(field_contents) - elsif field_contents.is_a?(Hash) && Parsing::Universal.universal_object?(field_contents) - @fields[field_name] = Parsing::Universal::UniversalObjectField.new(field_contents) - else - field_contents_str = field_contents.dup - if field_contents_str.key?('value') && field_contents_str['value'].nil? == false - field_contents_str['value'] = field_contents_str['value'].to_s - end - @fields[field_name] = Mindee::Parsing::Standard::StringField.new(field_contents_str) - end - end - end - end - end - end -end diff --git a/lib/mindee/product/universal/universal_page.rb b/lib/mindee/product/universal/universal_page.rb deleted file mode 100644 index 7da359e58..000000000 --- a/lib/mindee/product/universal/universal_page.rb +++ /dev/null @@ -1,51 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' -require_relative 'universal_prediction' - -module Mindee - module Product - module Universal - # Universal Document V1 page. - class UniversalPage < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = UniversalPagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - - # Universal Document V1 page prediction. - class UniversalPagePrediction < UniversalPrediction - include Mindee::Parsing::Standard - include Mindee::Parsing::Universal - def initialize(raw_prediction, page_id = nil) - super(raw_prediction) - raw_prediction.each do |field_name, field_contents| - if field_contents.is_a?(Array) - @fields[field_name] = Mindee::Parsing::Universal::UniversalListField.new(field_contents, page_id) - elsif field_contents.is_a?(Hash) && Parsing::Universal.universal_object?(field_contents) - @fields[field_name] = Mindee::Parsing::Universal::UniversalObjectField.new(field_contents, page_id) - else - field_contents_str = field_contents.dup - if field_contents_str.key?('value') && !field_contents_str['value'].nil? - field_contents_str['value'] = field_contents_str['value'].to_s - end - @fields[field_name] = Mindee::Parsing::Standard::StringField.new(field_contents_str, page_id) - end - end - end - - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end -end diff --git a/lib/mindee/product/universal/universal_prediction.rb b/lib/mindee/product/universal/universal_prediction.rb deleted file mode 100644 index b933984cd..000000000 --- a/lib/mindee/product/universal/universal_prediction.rb +++ /dev/null @@ -1,122 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../parsing' - -module Mindee - module Product - module Universal - # Universal Document V1 page. - class UniversalPrediction < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Common - include Mindee::Parsing::Standard - include Mindee::Parsing::Universal - # All value fields in the document - # @return [Hash] - attr_reader :fields - - def initialize(_ = nil) - super - @fields = {} # : Hash[String | Symbol, untyped] - end - - # String representation. - def to_s - out_str = '' - pattern = %r{^(\n* *)( {2}):} - @fields.each do |field_name, field_value| - str_value = if field_value.is_a?( - Mindee::Parsing::Universal::UniversalListField - ) && field_value.values.length.positive? - generate_field_string(field_name, field_value, pattern) - else - field_value.to_s - end - out_str += "\n:#{field_name}:" - - out_str += " #{str_value}".sub(%r{^\s+\n}, "\n") if str_value.length.positive? - end - out_str.sub("\n", '') - end - - private - - def generate_field_string(field_name, field_value, pattern) - values = field_value.values - return '' if values.nil? || values.empty? - - str_value = '' - first_value = values[0] - str_value += if first_value.is_a?(Parsing::Universal::UniversalObjectField) - first_value.str_level(1).sub(pattern, '\\1* :') - else - "#{first_value.to_s.sub(pattern, '\\1* :')}\n" - end - Array(values[1..]).each do |sub_value| - str_value += if sub_value.is_a?(Parsing::Universal::UniversalObjectField) - sub_value.str_level(1).sub(pattern, '\\1* :') - else - "#{' ' * (field_name.length + 2)} #{sub_value}\n" - end - end - - str_value.rstrip - end - - def generate_list_field_string(field_name, field_value, pattern) - str_value = '' - field_value.each_value do |sub_value| - str_value += generate_sub_value_string(field_name, sub_value, pattern) - end - str_value.rstrip - end - - def generate_sub_value_string(field_name, sub_value, pattern) - if sub_value.is_a?(Mindee::Parsing::Universal::UniversalObjectField) - sub_value.str_level(1).gsub(pattern, '\1* :') - else - (' ' * (field_name.length + 2)) + "#{sub_value}\n" - end - end - - # Returns a hash of all fields that aren't a collection - # @return [Hash] - def single_fields - single_fields = {} # : Hash[String | Symbol, untyped] - @fields.each do |field_name, field_value| - single_fields[field_name] = field_value if field_value.is_a?(Mindee::Parsing::Standard::StringField) - end - single_fields - end - - # Returns a hash of all list-like fields - # @return [Hash] - def list_fields - list_fields = {} # : Hash[String | Symbol, Mindee::Parsing::Universal::UniversalListField] - @fields.each do |field_name, field_value| - list_fields[field_name] = field_value if field_value.is_a?(Mindee::Parsing::Universal::UniversalListField) - end - list_fields - end - - # Returns a hash of all object-like fields - # @return [Hash] - def object_fields - object_fields = {} # : Hash[String | Symbol, untyped] - @fields.each do |field_name, field_value| - if field_value.is_a?(Mindee::Parsing::Universal::UniversalObjectField) - object_fields[field_name] = - field_value - end - end - object_fields - end - - # Lists names of all top-level field keys - # @return [Array] - def list_field_names - @fields.keys.map(&:to_s) - end - end - end - end -end diff --git a/lib/mindee/product/us/bank_check/bank_check_v1_document.rb b/lib/mindee/product/us/bank_check/bank_check_v1_document.rb deleted file mode 100644 index 2d3064f24..000000000 --- a/lib/mindee/product/us/bank_check/bank_check_v1_document.rb +++ /dev/null @@ -1,74 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module US - module BankCheck - # Bank Check API version 1.1 document data. - class BankCheckV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The check payer's account number. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :account_number - # The amount of the check. - # @return [Mindee::Parsing::Standard::AmountField] - attr_reader :amount - # The issuer's check number. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :check_number - # The date the check was issued. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :date - # List of the check's payees (recipients). - # @return [Array] - attr_reader :payees - # The check issuer's routing number. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :routing_number - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @account_number = Parsing::Standard::StringField.new( - prediction['account_number'], - page_id - ) - @amount = Parsing::Standard::AmountField.new( - prediction['amount'], - page_id - ) - @check_number = Parsing::Standard::StringField.new( - prediction['check_number'], - page_id - ) - @date = Parsing::Standard::DateField.new(prediction['date'], page_id) - @payees = [] # : Array[Parsing::Standard::StringField] - prediction['payees'].each do |item| - @payees.push(Parsing::Standard::StringField.new(item, page_id)) - end - @routing_number = Parsing::Standard::StringField.new( - prediction['routing_number'], - page_id - ) - end - - # @return [String] - def to_s - payees = @payees.join("\n #{' ' * 8}") - out_str = String.new - out_str << "\n:Check Issue Date: #{@date}".rstrip - out_str << "\n:Amount: #{@amount}".rstrip - out_str << "\n:Payees: #{payees}".rstrip - out_str << "\n:Routing Number: #{@routing_number}".rstrip - out_str << "\n:Account Number: #{@account_number}".rstrip - out_str << "\n:Check Number: #{@check_number}".rstrip - out_str[1..].to_s - end - end - end - end - end -end diff --git a/lib/mindee/product/us/bank_check/bank_check_v1_page.rb b/lib/mindee/product/us/bank_check/bank_check_v1_page.rb deleted file mode 100644 index 780132247..000000000 --- a/lib/mindee/product/us/bank_check/bank_check_v1_page.rb +++ /dev/null @@ -1,64 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'bank_check_v1_document' - -module Mindee - module Product - module US - module BankCheck - # Bank Check API version 1.1 page data. - class BankCheckV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - BankCheckV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Bank Check V1 page prediction. - class BankCheckV1PagePrediction < BankCheckV1Document - include Mindee::Parsing::Standard - - # The position of the check on the document. - # @return [Mindee::Parsing::Standard::PositionField] - attr_reader :check_position - # List of signature positions - # @return [Array] - attr_reader :signatures_positions - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - @check_position = Parsing::Standard::PositionField.new( - prediction['check_position'], - page_id - ) - @signatures_positions = [] - prediction['signatures_positions'].each do |item| - @signatures_positions.push(Parsing::Standard::PositionField.new(item, page_id)) - end - super - end - - # @return [String] - def to_s - signatures_positions = @signatures_positions.join("\n #{' ' * 21}") - out_str = String.new - out_str << "\n:Check Position: #{@check_position}".rstrip - out_str << "\n:Signature Positions: #{signatures_positions}".rstrip - out_str << "\n#{super}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/us/healthcare_card/healthcare_card_v1.rb b/lib/mindee/product/us/healthcare_card/healthcare_card_v1.rb deleted file mode 100644 index 75c0bcd3e..000000000 --- a/lib/mindee/product/us/healthcare_card/healthcare_card_v1.rb +++ /dev/null @@ -1,47 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'healthcare_card_v1_document' -require_relative 'healthcare_card_v1_page' - -module Mindee - module Product - module US - # Healthcare Card module. - module HealthcareCard - # Healthcare Card API version 1 inference prediction. - class HealthcareCardV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'us_healthcare_cards' - @endpoint_version = '1' - @has_async = true - @has_sync = false - - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = HealthcareCardV1Document.new(prediction['prediction'], nil) - @pages = [] - prediction['pages'].each do |page| - @pages.push(HealthcareCardV1Page.new(page)) - end - end - - class << self - # Name of the endpoint for this product. - # @return [String] - attr_reader :endpoint_name - # Version for this product. - # @return [String] - attr_reader :endpoint_version - # Whether this product has access to an asynchronous endpoint. - # @return [bool] - attr_reader :has_async - # Whether this product has access to synchronous endpoint. - # @return [bool] - attr_reader :has_sync - end - end - end - end - end -end diff --git a/lib/mindee/product/us/healthcare_card/healthcare_card_v1_copay.rb b/lib/mindee/product/us/healthcare_card/healthcare_card_v1_copay.rb deleted file mode 100644 index fe71109ca..000000000 --- a/lib/mindee/product/us/healthcare_card/healthcare_card_v1_copay.rb +++ /dev/null @@ -1,67 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module US - module HealthcareCard - # Copayments for covered services. - class HealthcareCardV1Copay < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The price of the service. - # @return [Float] - attr_reader :service_fees - # The name of the service. - # @return [String] - attr_reader :service_name - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @service_fees = prediction['service_fees'] - @service_name = prediction['service_name'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:service_fees] = - @service_fees.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@service_fees) - printable[:service_name] = format_for_display(@service_name) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:service_fees] = - @service_fees.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@service_fees) - printable[:service_name] = format_for_display(@service_name, 20) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 13s', printable[:service_fees]) - out_str << format('| %- 21s', printable[:service_name]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :Service Fees: #{printable[:service_fees]}" - out_str << "\n :Service Name: #{printable[:service_name]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/us/healthcare_card/healthcare_card_v1_document.rb b/lib/mindee/product/us/healthcare_card/healthcare_card_v1_document.rb deleted file mode 100644 index ff7568d22..000000000 --- a/lib/mindee/product/us/healthcare_card/healthcare_card_v1_document.rb +++ /dev/null @@ -1,167 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'healthcare_card_v1_copays' - -module Mindee - module Product - module US - module HealthcareCard - # Healthcare Card API version 1.3 document data. - class HealthcareCardV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The name of the company that provides the healthcare plan. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :company_name - # Copayments for covered services. - # @return [Mindee::Product::US::HealthcareCard::HealthcareCardV1Copays] - attr_reader :copays - # The list of dependents covered by the healthcare plan. - # @return [Array] - attr_reader :dependents - # The date when the member enrolled in the healthcare plan. - # @return [Mindee::Parsing::Standard::DateField] - attr_reader :enrollment_date - # The group number associated with the healthcare plan. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :group_number - # The organization that issued the healthcare plan. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :issuer80840 - # The unique identifier for the member in the healthcare system. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :member_id - # The name of the member covered by the healthcare plan. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :member_name - # The unique identifier for the payer in the healthcare system. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :payer_id - # The name of the healthcare plan. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :plan_name - # The BIN number for prescription drug coverage. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :rx_bin - # The group number for prescription drug coverage. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :rx_grp - # The ID number for prescription drug coverage. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :rx_id - # The PCN number for prescription drug coverage. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :rx_pcn - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @company_name = Parsing::Standard::StringField.new( - prediction['company_name'], - page_id - ) - @copays = Product::US::HealthcareCard::HealthcareCardV1Copays.new(prediction['copays'], page_id) - @dependents = [] # : Array[Parsing::Standard::StringField] - prediction['dependents'].each do |item| - @dependents.push(Parsing::Standard::StringField.new(item, page_id)) - end - @enrollment_date = Parsing::Standard::DateField.new( - prediction['enrollment_date'], - page_id - ) - @group_number = Parsing::Standard::StringField.new( - prediction['group_number'], - page_id - ) - @issuer80840 = Parsing::Standard::StringField.new( - prediction['issuer_80840'], - page_id - ) - @member_id = Parsing::Standard::StringField.new( - prediction['member_id'], - page_id - ) - @member_name = Parsing::Standard::StringField.new( - prediction['member_name'], - page_id - ) - @payer_id = Parsing::Standard::StringField.new( - prediction['payer_id'], - page_id - ) - @plan_name = Parsing::Standard::StringField.new( - prediction['plan_name'], - page_id - ) - @rx_bin = Parsing::Standard::StringField.new( - prediction['rx_bin'], - page_id - ) - @rx_grp = Parsing::Standard::StringField.new( - prediction['rx_grp'], - page_id - ) - @rx_id = Parsing::Standard::StringField.new(prediction['rx_id'], page_id) - @rx_pcn = Parsing::Standard::StringField.new( - prediction['rx_pcn'], - page_id - ) - end - - # @return [String] - def to_s - dependents = @dependents.join("\n #{' ' * 12}") - copays = copays_to_s - out_str = String.new - out_str << "\n:Company Name: #{@company_name}".rstrip - out_str << "\n:Plan Name: #{@plan_name}".rstrip - out_str << "\n:Member Name: #{@member_name}".rstrip - out_str << "\n:Member ID: #{@member_id}".rstrip - out_str << "\n:Issuer 80840: #{@issuer80840}".rstrip - out_str << "\n:Dependents: #{dependents}".rstrip - out_str << "\n:Group Number: #{@group_number}".rstrip - out_str << "\n:Payer ID: #{@payer_id}".rstrip - out_str << "\n:RX BIN: #{@rx_bin}".rstrip - out_str << "\n:RX ID: #{@rx_id}".rstrip - out_str << "\n:RX GRP: #{@rx_grp}".rstrip - out_str << "\n:RX PCN: #{@rx_pcn}".rstrip - out_str << "\n:Copays:" - out_str << copays - out_str << "\n:Enrollment Date: #{@enrollment_date}".rstrip - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def copays_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 14}" - out_str << "+#{char * 22}" - out_str << '+' - out_str - end - - # @return [String] - def copays_to_s - return '' if @copays.empty? - - line_items = @copays.map(&:to_table_line).join("\n#{copays_separator('-')}\n ") - out_str = String.new - out_str << "\n#{copays_separator('-')}" - out_str << "\n |" - out_str << ' Service Fees |' - out_str << ' Service Name |' - out_str << "\n#{copays_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{copays_separator('-')}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/us/healthcare_card/healthcare_card_v1_page.rb b/lib/mindee/product/us/healthcare_card/healthcare_card_v1_page.rb deleted file mode 100644 index f20e532bb..000000000 --- a/lib/mindee/product/us/healthcare_card/healthcare_card_v1_page.rb +++ /dev/null @@ -1,38 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'healthcare_card_v1_document' - -module Mindee - module Product - module US - module HealthcareCard - # Healthcare Card API version 1.3 page data. - class HealthcareCardV1Page < Mindee::Parsing::Common::Page - # @param prediction [Hash] - def initialize(prediction) - super - @prediction = if prediction['prediction'].empty? - nil - else - HealthcareCardV1PagePrediction.new( - prediction['prediction'], - prediction['id'] - ) - end - end - end - - # Healthcare Card V1 page prediction. - class HealthcareCardV1PagePrediction < HealthcareCardV1Document - # @return [String] - def to_s - out_str = String.new - out_str << "\n#{super}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/us/us_mail/us_mail_v3_document.rb b/lib/mindee/product/us/us_mail/us_mail_v3_document.rb deleted file mode 100644 index 99f81a507..000000000 --- a/lib/mindee/product/us/us_mail/us_mail_v3_document.rb +++ /dev/null @@ -1,115 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' -require_relative 'us_mail_v3_sender_address' -require_relative 'us_mail_v3_recipient_addresses' - -module Mindee - module Product - module US - module UsMail - # US Mail API version 3.0 document data. - class UsMailV3Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # Whether the mailing is marked as return to sender. - # @return [Mindee::Parsing::Standard::BooleanField] - attr_reader :is_return_to_sender - # The addresses of the recipients. - # @return [Mindee::Product::US::UsMail::UsMailV3RecipientAddresses] - attr_reader :recipient_addresses - # The names of the recipients. - # @return [Array] - attr_reader :recipient_names - # The address of the sender. - # @return [Mindee::Product::US::UsMail::UsMailV3SenderAddress] - attr_reader :sender_address - # The name of the sender. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :sender_name - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @is_return_to_sender = Parsing::Standard::BooleanField.new( - prediction['is_return_to_sender'], - page_id - ) - @recipient_addresses = Product::US::UsMail::UsMailV3RecipientAddresses.new( - prediction['recipient_addresses'], page_id - ) - @recipient_names = [] # : Array[Parsing::Standard::StringField] - prediction['recipient_names'].each do |item| - @recipient_names.push(Parsing::Standard::StringField.new(item, page_id)) - end - @sender_address = Product::US::UsMail::UsMailV3SenderAddress.new( - prediction['sender_address'], - page_id - ) - @sender_name = Parsing::Standard::StringField.new( - prediction['sender_name'], - page_id - ) - end - - # @return [String] - def to_s - sender_address = @sender_address.to_s - recipient_names = @recipient_names.join("\n #{' ' * 17}") - recipient_addresses = recipient_addresses_to_s - out_str = String.new - out_str << "\n:Sender Name: #{@sender_name}".rstrip - out_str << "\n:Sender Address:" - out_str << sender_address - out_str << "\n:Recipient Names: #{recipient_names}".rstrip - out_str << "\n:Recipient Addresses:" - out_str << recipient_addresses - out_str << "\n:Return to Sender: #{@is_return_to_sender}".rstrip - out_str[1..].to_s - end - - private - - # @param char [String] - # @return [String] - def recipient_addresses_separator(char) - out_str = String.new - out_str << ' ' - out_str << "+#{char * 17}" - out_str << "+#{char * 37}" - out_str << "+#{char * 19}" - out_str << "+#{char * 13}" - out_str << "+#{char * 24}" - out_str << "+#{char * 7}" - out_str << "+#{char * 27}" - out_str << "+#{char * 17}" - out_str << '+' - out_str - end - - # @return [String] - def recipient_addresses_to_s - return '' if @recipient_addresses.empty? - - line_items = @recipient_addresses.map(&:to_table_line).join("\n#{recipient_addresses_separator('-')}\n ") - out_str = String.new - out_str << "\n#{recipient_addresses_separator('-')}" - out_str << "\n |" - out_str << ' City |' - out_str << ' Complete Address |' - out_str << ' Is Address Change |' - out_str << ' Postal Code |' - out_str << ' Private Mailbox Number |' - out_str << ' State |' - out_str << ' Street |' - out_str << ' Unit |' - out_str << "\n#{recipient_addresses_separator('=')}" - out_str << "\n #{line_items}" - out_str << "\n#{recipient_addresses_separator('-')}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/us/us_mail/us_mail_v3_recipient_address.rb b/lib/mindee/product/us/us_mail/us_mail_v3_recipient_address.rb deleted file mode 100644 index f2b109e41..000000000 --- a/lib/mindee/product/us/us_mail/us_mail_v3_recipient_address.rb +++ /dev/null @@ -1,113 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module US - module UsMail - # The addresses of the recipients. - class UsMailV3RecipientAddress < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The city of the recipient's address. - # @return [String] - attr_reader :city - # The complete address of the recipient. - # @return [String] - attr_reader :complete - # Indicates if the recipient's address is a change of address. - # @return [bool] - attr_reader :is_address_change - # The postal code of the recipient's address. - # @return [String] - attr_reader :postal_code - # The private mailbox number of the recipient's address. - # @return [String] - attr_reader :private_mailbox_number - # Second part of the ISO 3166-2 code, consisting of two letters indicating the US State. - # @return [String] - attr_reader :state - # The street of the recipient's address. - # @return [String] - attr_reader :street - # The unit number of the recipient's address. - # @return [String] - attr_reader :unit - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @city = prediction['city'] - @complete = prediction['complete'] - @is_address_change = prediction['is_address_change'] - @postal_code = prediction['postal_code'] - @private_mailbox_number = prediction['private_mailbox_number'] - @state = prediction['state'] - @street = prediction['street'] - @unit = prediction['unit'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:city] = format_for_display(@city) - printable[:complete] = format_for_display(@complete) - printable[:is_address_change] = format_for_display(@is_address_change) - printable[:postal_code] = format_for_display(@postal_code) - printable[:private_mailbox_number] = format_for_display(@private_mailbox_number) - printable[:state] = format_for_display(@state) - printable[:street] = format_for_display(@street) - printable[:unit] = format_for_display(@unit) - printable - end - - # @return [Hash] - def table_printable_values - printable = {} - printable[:city] = format_for_display(@city, 15) - printable[:complete] = format_for_display(@complete, 35) - printable[:is_address_change] = format_for_display(@is_address_change, nil) - printable[:postal_code] = format_for_display(@postal_code, nil) - printable[:private_mailbox_number] = format_for_display(@private_mailbox_number, nil) - printable[:state] = format_for_display(@state, nil) - printable[:street] = format_for_display(@street, 25) - printable[:unit] = format_for_display(@unit, 15) - printable - end - - # @return [String] - def to_table_line - printable = table_printable_values - out_str = String.new - out_str << format('| %- 16s', printable[:city]) - out_str << format('| %- 36s', printable[:complete]) - out_str << format('| %- 18s', printable[:is_address_change]) - out_str << format('| %- 12s', printable[:postal_code]) - out_str << format('| %- 23s', printable[:private_mailbox_number]) - out_str << format('| %- 6s', printable[:state]) - out_str << format('| %- 26s', printable[:street]) - out_str << format('| %- 16s', printable[:unit]) - out_str << '|' - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :City: #{printable[:city]}" - out_str << "\n :Complete Address: #{printable[:complete]}" - out_str << "\n :Is Address Change: #{printable[:is_address_change]}" - out_str << "\n :Postal Code: #{printable[:postal_code]}" - out_str << "\n :Private Mailbox Number: #{printable[:private_mailbox_number]}" - out_str << "\n :State: #{printable[:state]}" - out_str << "\n :Street: #{printable[:street]}" - out_str << "\n :Unit: #{printable[:unit]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/product/us/us_mail/us_mail_v3_sender_address.rb b/lib/mindee/product/us/us_mail/us_mail_v3_sender_address.rb deleted file mode 100644 index 0777c21ff..000000000 --- a/lib/mindee/product/us/us_mail/us_mail_v3_sender_address.rb +++ /dev/null @@ -1,66 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../parsing' - -module Mindee - module Product - module US - module UsMail - # The address of the sender. - class UsMailV3SenderAddress < Mindee::Parsing::Standard::FeatureField - include Mindee::Parsing::Standard - # The city of the sender's address. - # @return [String] - attr_reader :city - # The complete address of the sender. - # @return [String] - attr_reader :complete - # The postal code of the sender's address. - # @return [String] - attr_reader :postal_code - # Second part of the ISO 3166-2 code, consisting of two letters indicating the US State. - # @return [String] - attr_reader :state - # The street of the sender's address. - # @return [String] - attr_reader :street - - # @param prediction [Hash] - # @param page_id [Integer, nil] - def initialize(prediction, page_id) - super - @city = prediction['city'] - @complete = prediction['complete'] - @postal_code = prediction['postal_code'] - @state = prediction['state'] - @street = prediction['street'] - @page_id = page_id - end - - # @return [Hash] - def printable_values - printable = {} - printable[:city] = format_for_display(@city) - printable[:complete] = format_for_display(@complete) - printable[:postal_code] = format_for_display(@postal_code) - printable[:state] = format_for_display(@state) - printable[:street] = format_for_display(@street) - printable - end - - # @return [String] - def to_s - printable = printable_values - out_str = String.new - out_str << "\n :City: #{printable[:city]}" - out_str << "\n :Complete Address: #{printable[:complete]}" - out_str << "\n :Postal Code: #{printable[:postal_code]}" - out_str << "\n :State: #{printable[:state]}" - out_str << "\n :Street: #{printable[:street]}" - out_str - end - end - end - end - end -end diff --git a/lib/mindee/v1.rb b/lib/mindee/v1.rb new file mode 100644 index 000000000..9214cafb8 --- /dev/null +++ b/lib/mindee/v1.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +require_relative 'v1/client' +require_relative 'v1/extraction' if Mindee::Dependency.all_deps_available? +require_relative 'v1/http' +require_relative 'v1/parsing' +require_relative 'v1/product' diff --git a/lib/mindee/v1/client.rb b/lib/mindee/v1/client.rb new file mode 100644 index 000000000..96319a263 --- /dev/null +++ b/lib/mindee/v1/client.rb @@ -0,0 +1,490 @@ +# frozen_string_literal: true + +require_relative '../input' +require_relative 'http' +require_relative '../logging' +require_relative '../page_options' +require_relative 'parsing/common/api_response' +require_relative 'parsing/common/job' +require_relative 'parsing/common/workflow_response' +require_relative 'product' + +# Default owner for products. +OTS_OWNER = 'mindee' + +module Mindee + module V1 + # Class for configuration options in parse calls. + # + # @!attribute all_words [bool] Whether to include the full text for each page. + # This performs a full OCR operation on the server and will increase response time. + # @!attribute full_text [bool] Whether to include the full OCR text response in compatible APIs. + # This performs a full OCR operation on the server and may increase response time. + # @!attribute close_file [bool] Whether to `close()` the file after parsing it. + # Set to false if you need to access the file after this operation. + # @!attribute page_options [PageOptions, Hash, nil] Page cutting/merge options: + # * `:page_indexes` Zero-based list of page indexes. + # * `:operation` Operation to apply on the document, given the specified page indexes: + # * `:KEEP_ONLY` - keep only the specified pages, and remove all others. + # * `:REMOVE` - remove the specified pages, and keep all others. + # * `:on_min_pages` Apply the operation only if the document has at least this many pages. + # @!attribute cropper [bool] Whether to include cropper results for each page. + # This performs a cropping operation on the server and will increase response time. + # @!attribute initial_delay_sec [Numeric] Initial delay before polling. Defaults to 2. + # @!attribute delay_sec [Numeric] Delay between polling attempts. Defaults to 1.5. + # @!attribute max_retries [Integer] Maximum number of retries. Defaults to 80. + class ParseOptions + attr_accessor :all_words, :full_text, :close_file, :page_options, :cropper, :rag, + :workflow_id, :initial_delay_sec, :delay_sec, :max_retries + + def initialize(params: {}) + params = params.transform_keys(&:to_sym) + @all_words = params.fetch(:all_words, false) + @full_text = params.fetch(:full_text, false) + @close_file = params.fetch(:close_file, true) + raw_page_options = params.fetch(:page_options, nil) + raw_page_options = PageOptions.new(params: raw_page_options) unless raw_page_options.is_a?(PageOptions) + @page_options = raw_page_options + @cropper = params.fetch(:cropper, false) + @rag = params.fetch(:rag, false) + @workflow_id = params.fetch(:workflow_id, nil) + @initial_delay_sec = params.fetch(:initial_delay_sec, 2) + @delay_sec = params.fetch(:delay_sec, 1.5) + @max_retries = params.fetch(:max_retries, 80) + end + end + + # Class for configuration options in workflow executions. + # + # @!attribute document_alias [String, nil] Alias to give to the document. + # @!attribute priority [Symbol, nil] Priority to give to the document. + # @!attribute full_text [bool] Whether to include the full OCR text response in compatible APIs. + # This performs a full OCR operation on the server and may increase response time. + # @!attribute public_url [String, nil] A unique, encrypted URL for accessing the document validation interface + # without requiring authentication. + # @!attribute rag [bool, nil] Whether to enable Retrieval-Augmented Generation. + # @!attribute page_options [PageOptions, Hash, nil] Page cutting/merge options: + # * `:page_indexes` Zero-based list of page indexes. + # * `:operation` Operation to apply on the document, given the specified page indexes: + # * `:KEEP_ONLY` - keep only the specified pages, and remove all others. + # * `:REMOVE` - remove the specified pages, and keep all others. + # * `:on_min_pages` Apply the operation only if the document has at least this many pages. + # @!attribute close_file [bool, nil] Whether to close the file after sending it. Defaults to true. + class WorkflowOptions + attr_accessor :document_alias, :priority, :full_text, :public_url, :page_options, :rag, :close_file + + def initialize(params: {}) + params = params.transform_keys(&:to_sym) + @document_alias = params.fetch(:document_alias, nil) + @priority = params.fetch(:priority, nil) + @full_text = params.fetch(:full_text, false) + @public_url = params.fetch(:public_url, nil) + @rag = params.fetch(:rag, nil) + raw_page_options = params.fetch(:page_options, nil) + raw_page_options = PageOptions.new(params: raw_page_options) unless raw_page_options.is_a?(PageOptions) + @page_options = raw_page_options + @close_file = params.fetch(:close_file, true) + end + end + + # Mindee API Client. + # See: https://developers.mindee.com/docs + class Client + # @param api_key [String] + def initialize(api_key: '') + @api_key = api_key + end + + # Enqueue a document for parsing and automatically try to retrieve it if needed. + # + # Accepts options either as a Hash or as a ParseOptions struct. + # + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param product_class [Mindee::Inference] The class of the product. + # @param endpoint [Mindee::V1::HTTP::Endpoint, nil] Endpoint of the API. + # @param options [Hash] A hash of options to configure the parsing behavior. Possible keys: + # * `:all_words` [bool] Whether to extract all the words on each page. + # This performs a full OCR operation on the server and will increase response time. + # * `:full_text` [bool] Whether to include the full OCR text response in compatible APIs. + # This performs a full OCR operation on the server and may increase response time. + # * `:close_file` [bool] Whether to `close()` the file after parsing it. + # Set to false if you need to access the file after this operation. + # * `:page_options` [Hash, nil] Page cutting/merge options: + # - `:page_indexes` [Array] Zero-based list of page indexes. + # - `:operation` [Symbol] Operation to apply on the document, given the `page_indexes` specified: + # - `:KEEP_ONLY` - keep only the specified pages, and remove all others. + # - `:REMOVE` - remove the specified pages, and keep all others. + # - `:on_min_pages` [Integer] Apply the operation only if the document has at least this many pages. + # * `:cropper` [bool, nil] Whether to include cropper results for each page. + # This performs a cropping operation on the server and will increase response time. + # * `:initial_delay_sec` [Numeric] Initial delay before polling. Defaults to 2. + # * `:delay_sec` [Numeric] Delay between polling attempts. Defaults to 1.5. + # * `:max_retries` [Integer] Maximum number of retries. Defaults to 80. + # @param enqueue [bool] Whether to enqueue the file. + # @return [Mindee::V1::Parsing::Common::ApiResponse] + def parse(input_source, product_class, endpoint: nil, options: {}, enqueue: true) + opts = normalize_parse_options(options) + process_pdf_if_required(input_source, opts) if input_source.is_a?(Input::Source::LocalInputSource) + endpoint ||= initialize_endpoint(product_class) + + if enqueue && product_class.has_async + enqueue_and_parse(input_source, product_class, endpoint, opts) + else + parse_sync(input_source, product_class, endpoint, opts) + end + end + + # Call prediction API on a document and parse the results. + # + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param product_class [Mindee::Inference] class of the product + # @param endpoint [Mindee::V1::HTTP::Endpoint, nil] Endpoint of the API. + # @param options [Hash] A hash of options to configure the parsing behavior. Possible keys: + # * `:all_words` [bool] Whether to extract all the words on each page. + # This performs a full OCR operation on the server and will increase response time. + # * `:full_text` [bool] Whether to include the full OCR text response in compatible APIs. + # This performs a full OCR operation on the server and may increase response time. + # * `:close_file` [bool] Whether to `close()` the file after parsing it. + # Set to false if you need to access the file after this operation. + # * `:page_options` [Hash, nil] Page cutting/merge options: + # - `:page_indexes` [Array] Zero-based list of page indexes. + # - `:operation` [Symbol] Operation to apply on the document, given the `page_indexes` specified: + # - `:KEEP_ONLY` - keep only the specified pages, and remove all others. + # - `:REMOVE` - remove the specified pages, and keep all others. + # - `:on_min_pages` [Integer] Apply the operation only if the document has at least this many pages. + # * `:cropper` [bool, nil] Whether to include cropper results for each page. + # This performs a cropping operation on the server and will increase response time. + # @return [Mindee::V1::Parsing::Common::ApiResponse] + def parse_sync(input_source, product_class, endpoint, options) + logger.debug("Parsing document as '#{endpoint.url_root}'") + + prediction, raw_http = endpoint.predict( + input_source, + options + ) + + Mindee::V1::Parsing::Common::ApiResponse.new(product_class, prediction, raw_http) + end + + # Enqueue a document for async parsing + # + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # The source of the input document (local file or URL). + # @param product_class [Mindee::Inference] The class of the product. + # @param options [Hash] A hash of options to configure the enqueue behavior. Possible keys: + # * `:endpoint` [V1::HTTP::Endpoint, nil] Endpoint of the API. + # Doesn't need to be set in the case of OTS APIs. + # * `:all_words` [bool] Whether to extract all the words on each page. + # This performs a full OCR operation on the server and will increase response time. + # * `:full_text` [bool] Whether to include the full OCR text response in compatible APIs. + # This performs a full OCR operation on the server and may increase response time. + # * `:close_file` [bool] Whether to `close()` the file after parsing it. + # Set to false if you need to access the file after this operation. + # * `:page_options` [Hash, nil] Page cutting/merge options: + # - `:page_indexes` [Array] Zero-based list of page indexes. + # - `:operation` [Symbol] Operation to apply on the document, given the `page_indexes` specified: + # - `:KEEP_ONLY` - keep only the specified pages, and remove all others. + # - `:REMOVE` - remove the specified pages, and keep all others. + # - `:on_min_pages` [Integer] Apply the operation only if the document has at least this many pages. + # * `:cropper` [bool] Whether to include cropper results for each page. + # This performs a cropping operation on the server and will increase response time. + # * `:rag` [bool] Whether to enable Retrieval-Augmented Generation. Only works if a Workflow ID is provided. + # * `:workflow_id` [String, nil] ID of the workflow to use. + # @param endpoint [Mindee::V1::HTTP::Endpoint] Endpoint of the API. + # @return [Mindee::V1::Parsing::Common::ApiResponse] + def enqueue(input_source, product_class, endpoint: nil, options: {}) + opts = normalize_parse_options(options) + endpoint ||= initialize_endpoint(product_class) + logger.debug("Enqueueing document as '#{endpoint.url_root}'") + + prediction, raw_http = endpoint.predict_async( + input_source, + opts + ) + Mindee::V1::Parsing::Common::ApiResponse.new(product_class, prediction, raw_http) + end + + # Parses a queued document + # + # @param job_id [String] ID of the job (queue) to poll from + # @param product_class [Mindee::Inference] class of the product + # @param endpoint [V1::HTTP::Endpoint, nil] Endpoint of the API + # Doesn't need to be set in the case of OTS APIs. + # + # @return [Mindee::V1::Parsing::Common::ApiResponse] + def parse_queued(job_id, product_class, endpoint: nil) + endpoint = initialize_endpoint(product_class) if endpoint.nil? + logger.debug("Fetching queued document as '#{endpoint.url_root}'") + prediction, raw_http = endpoint.parse_async(job_id) + Mindee::V1::Parsing::Common::ApiResponse.new(product_class, prediction, raw_http) + end + + # Enqueue a document for async parsing and automatically try to retrieve it + # + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # The source of the input document (local file or URL). + # @param product_class [Mindee::Inference] The class of the product. + # @param options [Hash] A hash of options to configure the parsing behavior. Possible keys: + # * `:endpoint` [V1::HTTP::Endpoint, nil] Endpoint of the API. + # Doesn't need to be set in the case of OTS APIs. + # * `:all_words` [bool] Whether to extract all the words on each page. + # This performs a full OCR operation on the server and will increase response time. + # * `:full_text` [bool] Whether to include the full OCR text response in compatible APIs. + # This performs a full OCR operation on the server and may increase response time. + # * `:close_file` [bool] Whether to `close()` the file after parsing it. + # Set to false if you need to access the file after this operation. + # * `:page_options` [Hash, nil] Page cutting/merge options: + # - `:page_indexes` [Array] Zero-based list of page indexes. + # - `:operation` [Symbol] Operation to apply on the document, given the `page_indexes` specified: + # - `:KEEP_ONLY` - keep only the specified pages, and remove all others. + # - `:REMOVE` - remove the specified pages, and keep all others. + # - `:on_min_pages` [Integer] Apply the operation only if the document has at least this many pages. + # * `:cropper` [bool, nil] Whether to include cropper results for each page. + # This performs a cropping operation on the server and will increase response time. + # * `:rag` [bool] Whether to enable Retrieval-Augmented Generation. Only works if a Workflow ID is provided. + # * `:workflow_id` [String, nil] ID of the workflow to use. + # * `:initial_delay_sec` [Numeric] Initial delay before polling. Defaults to 2. + # * `:delay_sec` [Numeric] Delay between polling attempts. Defaults to 1.5. + # * `:max_retries` [Integer] Maximum number of retries. Defaults to 80. + # @param endpoint [Mindee::V1::HTTP::Endpoint] Endpoint of the API. + # @return [Mindee::V1::Parsing::Common::ApiResponse] + def enqueue_and_parse(input_source, product_class, endpoint, options) + validate_async_params(options.initial_delay_sec, options.delay_sec, options.max_retries) + enqueue_res = enqueue(input_source, product_class, endpoint: endpoint, options: options) + job = enqueue_res.job or raise Error::MindeeAPIError, 'Expected job to be present' + job_id = job.id + + sleep(options.initial_delay_sec) + polling_attempts = 1 + logger.debug("Successfully enqueued document with job id: '#{job_id}'") + queue_res = parse_queued(job_id, product_class, endpoint: endpoint) + queue_res_job = queue_res.job or raise Error::MindeeAPIError, 'Expected job to be present' + valid_statuses = [ + Mindee::V1::Parsing::Common::JobStatus::WAITING, + Mindee::V1::Parsing::Common::JobStatus::PROCESSING, + ] + # @type var valid_statuses: Array[(:waiting | :processing | :completed | :failed)] + while valid_statuses.include?(queue_res_job.status) && polling_attempts < options.max_retries + logger.debug("Polling server for parsing result with job id: '#{job_id}'. Attempt #{polling_attempts}") + sleep(options.delay_sec) + queue_res = parse_queued(job_id, product_class, endpoint: endpoint) + queue_res_job = queue_res.job or raise Error::MindeeAPIError, 'Expected job to be present' + polling_attempts += 1 + end + + if queue_res_job.status != Mindee::V1::Parsing::Common::JobStatus::COMPLETED + elapsed = options.initial_delay_sec + (polling_attempts * options.delay_sec.to_f) + raise Error::MindeeAPIError, + "Asynchronous parsing request timed out after #{elapsed} seconds (#{polling_attempts} tries)" + end + + queue_res + end + + # Sends a document to a workflow. + # + # Accepts options either as a Hash or as a WorkflowOptions struct. + # + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param workflow_id [String] + # @param options [Hash, WorkflowOptions] Options to configure workflow behavior. Possible keys: + # * `document_alias` [String, nil] Alias to give to the document. + # * `priority` [Symbol, nil] Priority to give to the document. + # * `full_text` [bool] Whether to include the full OCR text response in compatible APIs. + # * `rag` [bool, nil] Whether to enable Retrieval-Augmented Generation. + # + # * `public_url` [String, nil] A unique, encrypted URL for accessing the document validation interface without + # requiring authentication. + # * `page_options` [Hash, nil] Page cutting/merge options: + # * `:page_indexes` Zero-based list of page indexes. + # * `:operation` Operation to apply on the document, given the `page_indexes specified: + # * `:KEEP_ONLY` - keep only the specified pages, and remove all others. + # * `:REMOVE` - remove the specified pages, and keep all others. + # * `:on_min_pages` Apply the operation only if document has at least this many pages. + # @return [Mindee::V1::Parsing::Common::WorkflowResponse] + def execute_workflow(input_source, workflow_id, options: {}) + opts = options.is_a?(WorkflowOptions) ? options : WorkflowOptions.new(params: options) + if opts.respond_to?(:page_options) && input_source.is_a?(Input::Source::LocalInputSource) + process_pdf_if_required(input_source, opts) + end + + workflow_endpoint = V1::HTTP::WorkflowEndpoint.new(workflow_id, api_key: @api_key.to_s) + logger.debug("Sending document to workflow '#{workflow_id}'") + + prediction, raw_http = workflow_endpoint.execute_workflow( + input_source, + opts + ) + + Mindee::V1::Parsing::Common::WorkflowResponse.new(V1::Product::Universal::Universal, prediction, raw_http) + end + + # Load a prediction. + # + # @param product_class [Mindee::Inference] class of the product + # @param local_response [Mindee::Input::LocalResponse] + # @return [Mindee::V1::Parsing::Common::ApiResponse] + def load_prediction(product_class, local_response) + raise Error::MindeeAPIError, 'Expected LocalResponse to not be nil.' if local_response.nil? + + response_hash = local_response.as_hash || {} + raise Error::MindeeAPIError, 'Expected LocalResponse#as_hash to return a hash.' if response_hash.nil? + + Mindee::V1::Parsing::Common::ApiResponse.new(product_class, response_hash, response_hash.to_json) + rescue KeyError, Error::MindeeAPIError + raise Error::MindeeInputError, 'No prediction found in local response.' + end + + # Load a document from an absolute path, as a string. + # @param input_path [String] Path of file to open + # @param repair_pdf [bool] Attempts to fix broken pdf if true + # @return [Mindee::Input::Source::PathInputSource] + def source_from_path(input_path, repair_pdf: false) + Input::Source::PathInputSource.new(input_path, repair_pdf: repair_pdf) + end + + # Load a document from raw bytes. + # @param input_bytes [String] Encoding::BINARY byte input + # @param filename [String] The name of the file (without the path) + # @param repair_pdf [bool] Attempts to fix broken pdf if true + # @return [Mindee::Input::Source::BytesInputSource] + def source_from_bytes(input_bytes, filename, repair_pdf: false) + Input::Source::BytesInputSource.new(input_bytes, filename, repair_pdf: repair_pdf) + end + + # Load a document from a base64 encoded string. + # @param base64_string [String] Input to parse as base64 string + # @param filename [String] The name of the file (without the path) + # @param repair_pdf [bool] Attempts to fix broken pdf if true + # @return [Mindee::Input::Source::Base64InputSource] + def source_from_b64string(base64_string, filename, repair_pdf: false) + Input::Source::Base64InputSource.new(base64_string, filename, repair_pdf: repair_pdf) + end + + # Load a document from a normal Ruby `File`. + # @param input_file [File] Input file handle + # @param filename [String] The name of the file (without the path) + # @param repair_pdf [bool] Attempts to fix broken pdf if true + # @return [Mindee::Input::Source::FileInputSource] + def source_from_file(input_file, filename, repair_pdf: false) + Input::Source::FileInputSource.new(input_file, filename, repair_pdf: repair_pdf) + end + + # Load a document from a secure remote source (HTTPS). + # @param url [String] URL of the file + # @return [Mindee::Input::Source::URLInputSource] + def source_from_url(url) + Input::Source::URLInputSource.new(url) + end + + # Creates a custom endpoint with the given values. + # Do not set for standard (off the shelf) endpoints. + # + # @param endpoint_name [String] For custom endpoints, the "API name" field in the "Settings" page of the + # API Builder. Do not set for standard (off the shelf) endpoints. + # + # @param account_name [String] For custom endpoints, your account or organization username on the API Builder. + # This is normally not required unless you have a custom endpoint which has the same name as a + # standard (off the shelf) endpoint. + # @param version [String] For custom endpoints, version of the product + # @return [Mindee::V1::HTTP::Endpoint] + def create_endpoint(endpoint_name: '', account_name: '', version: '') + initialize_endpoint( + Mindee::V1::Product::Universal::Universal, + endpoint_name: endpoint_name, + account_name: account_name, + version: version + ) + end + + # Validates the parameters for async auto-polling + # @param initial_delay_sec [Numeric] initial delay before polling + # @param delay_sec [Numeric] delay between polling attempts + # @param max_retries [Integer, nil] maximum amount of retries. + def validate_async_params(initial_delay_sec, delay_sec, max_retries) + min_delay_sec = 1 + min_initial_delay_sec = 1 + min_retries = 2 + + if delay_sec < min_delay_sec + raise ArgumentError, + "Cannot set auto-poll delay to less than #{min_delay_sec} second(s)" + end + if initial_delay_sec < min_initial_delay_sec + raise ArgumentError, + "Cannot set initial parsing delay to less than #{min_initial_delay_sec} second(s)" + end + raise ArgumentError, "Cannot set auto-poll retries to less than #{min_retries}" if max_retries < min_retries + end + + # Creates an endpoint with the given values. Raises an error if the endpoint is invalid. + # @param product_class [Mindee::V1::Parsing::Common::Inference] class of the product + # + # @param endpoint_name [String] For custom endpoints, the "API name" field in the "Settings" page of the + # API Builder. Do not set for standard (off the shelf) endpoints. + # + # @param account_name [String] For custom endpoints, your account or organization username on the API Builder. + # This is normally not required unless you have a custom endpoint which has the same name as a + # standard (off the shelf) endpoint. + # @param version [String] For custom endpoints, version of the product. + # @return [Mindee::V1::HTTP::Endpoint] + def initialize_endpoint(product_class, endpoint_name: '', account_name: '', version: '') + if (endpoint_name.nil? || endpoint_name.empty?) && product_class == Mindee::V1::Product::Universal::Universal + raise Mindee::Error::MindeeConfigurationError, 'Missing argument endpoint_name when using custom class' + end + + endpoint_name = fix_endpoint_name(product_class, endpoint_name) + account_name = fix_account_name(account_name) + version = fix_version(product_class, version) + + V1::HTTP::Endpoint.new(account_name, endpoint_name, version, api_key: @api_key.to_s) + end + + def fix_endpoint_name(product_class, endpoint_name) + endpoint_name.nil? || endpoint_name.empty? ? product_class.endpoint_name.to_s : endpoint_name.to_s + end + + def fix_account_name(account_name) + if account_name.nil? || account_name.empty? + logger.info("No account name provided, #{OTS_OWNER} will be used by default.") + return OTS_OWNER + end + + account_name + end + + def fix_version(product_class, version) + return version unless version.nil? || version.empty? + + if product_class.endpoint_version.nil? || product_class.endpoint_version.to_s.empty? + logger.debug('No version provided for a custom build, will attempt to poll version 1 by default.') + return '1' + end + product_class.endpoint_version || '' + end + + # If needed, converts the parsing options provided as a hash into a proper ParseOptions object. + # @param options [Hash, ParseOptions] Options. + # @return [ParseOptions] + def normalize_parse_options(options) + return options if options.is_a?(ParseOptions) + + ParseOptions.new(params: options) + end + + # Processes a PDF if parameters were provided. + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param opts [ParseOptions] + def process_pdf_if_required(input_source, opts) + return unless input_source.is_a?(Mindee::Input::Source::LocalInputSource) && + opts.page_options.on_min_pages && + input_source.pdf? + + input_source.process_pdf(opts.page_options) + end + + private :parse_sync, :validate_async_params, :initialize_endpoint, :fix_endpoint_name, :fix_version, + :fix_account_name, :process_pdf_if_required, :normalize_parse_options + end + end +end diff --git a/lib/mindee/extraction.rb b/lib/mindee/v1/extraction.rb similarity index 100% rename from lib/mindee/extraction.rb rename to lib/mindee/v1/extraction.rb diff --git a/lib/mindee/v1/extraction/multi_receipts_extractor.rb b/lib/mindee/v1/extraction/multi_receipts_extractor.rb new file mode 100644 index 000000000..fad71dbb3 --- /dev/null +++ b/lib/mindee/v1/extraction/multi_receipts_extractor.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +module Mindee + module V1 + # Custom extraction module + module Extraction + # Multi-receipts extraction + # Extracts individual receipts from multi-receipts documents. + # + # @param input_source [LocalInputSource] Local Input Source to extract sub-receipts from. + # @param inference [Inference] Results of the inference. + # @return [Array] Individual extracted receipts as an array of ExtractedMultiReceiptsImage. + def self.extract_receipts(input_source, inference) + images = [] # @type var images: Array[Image::ExtractedImage] + unless inference.prediction.receipts + raise Error::MindeeInputError, + 'No possible receipts candidates found for Multi-Receipts extraction.' + end + + (0...input_source.page_count).each do |page_id| + receipt_positions = inference.pages[page_id].prediction.receipts.map(&:bounding_box) + images.concat( + Mindee::Image::ImageExtractor.extract_multiple_images_from_source(input_source, page_id + 1, + receipt_positions) + ) + end + + images + end + end + end +end diff --git a/lib/mindee/v1/http.rb b/lib/mindee/v1/http.rb new file mode 100644 index 000000000..ed4603b25 --- /dev/null +++ b/lib/mindee/v1/http.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +require_relative 'http/workflow_endpoint' +require_relative 'http/endpoint' diff --git a/lib/mindee/v1/http/.rubocop.yml b/lib/mindee/v1/http/.rubocop.yml new file mode 100644 index 000000000..acea271ec --- /dev/null +++ b/lib/mindee/v1/http/.rubocop.yml @@ -0,0 +1,7 @@ +inherit_from: ../../../../.rubocop.yml + +Metrics/CyclomaticComplexity: + Max: 10 + +Metrics/PerceivedComplexity: + Max: 10 diff --git a/lib/mindee/v1/http/endpoint.rb b/lib/mindee/v1/http/endpoint.rb new file mode 100644 index 000000000..9465e93c7 --- /dev/null +++ b/lib/mindee/v1/http/endpoint.rb @@ -0,0 +1,221 @@ +# frozen_string_literal: true + +require 'json' +require 'net/http' +require_relative '../../http/http_error_handler' +require_relative '../../version' +require_relative '../../http/response_validation' + +module Mindee + # Mindee internal HTTP module. + module V1 + module HTTP + # API key's default environment key name. + API_KEY_ENV_NAME = 'MINDEE_API_KEY' + # API key's default value. + API_KEY_DEFAULT = nil + + # Base URL default environment key name. + BASE_URL_ENV_NAME = 'MINDEE_BASE_URL' + # Base URL's default value. + BASE_URL_DEFAULT = 'https://api.mindee.net/v1' + + # HTTP request timeout default environment key name. + REQUEST_TIMEOUT_ENV_NAME = 'MINDEE_REQUEST_TIMEOUT' + # HTTP request timeout default value. + TIMEOUT_DEFAULT = 120 + + # Default value for the user agent. + USER_AGENT = "mindee-api-ruby@v#{Mindee::VERSION} ruby-v#{RUBY_VERSION} #{Mindee::PLATFORM}".freeze + + # Generic API endpoint for a product. + class Endpoint + # @return [String] + attr_reader :api_key + # @return [Integer] + attr_reader :request_timeout + # @return [String] + attr_reader :url_root + # @return [String] + attr_reader :base_url + + def initialize(owner, url_name, version, api_key: '') + @owner = owner + @url_name = url_name + @version = version + @request_timeout = ENV.fetch(REQUEST_TIMEOUT_ENV_NAME, TIMEOUT_DEFAULT).to_i + if api_key.nil? && !ENV.fetch(API_KEY_ENV_NAME, API_KEY_DEFAULT).to_s.empty? + logger.debug('API key set from environment') + end + @api_key = api_key.nil? || api_key.empty? ? ENV.fetch(API_KEY_ENV_NAME, API_KEY_DEFAULT) : api_key + @base_url = ENV.fetch(BASE_URL_ENV_NAME, BASE_URL_DEFAULT).chomp('/') + @url_root = "#{@base_url}/products/#{@owner}/#{@url_name}/v#{@version}" + end + + # Call the prediction API. + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param opts [ParseOptions] Parse options. + # @return [Array] + def predict(input_source, opts) + check_api_key + response = predict_req_post( + input_source, + opts + ) + if !response.nil? && response.respond_to?(:body) + hashed_response = JSON.parse(response.body, object_class: Hash) + return [hashed_response, response.body] if Mindee::HTTP::ResponseValidation.valid_sync_response?(response) + + Mindee::HTTP::ResponseValidation.clean_request!(response) + end + + raise Error::MindeeError, 'Could not resolve server response.' if response.nil? + + error = Mindee::HTTP::ErrorHandler.handle_error(@url_name, response) + raise error + end + + # Call the prediction API. + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param opts [ParseOptions, Hash] Parse options. + # @return [Array] + def predict_async(input_source, opts) + check_api_key + response = document_queue_req_post(input_source, opts) + if !response.nil? && response.respond_to?(:body) + hashed_response = JSON.parse(response.body, object_class: Hash) + return [hashed_response, response.body] if Mindee::HTTP::ResponseValidation.valid_async_response?(response) + + Mindee::HTTP::ResponseValidation.clean_request!(response) + end + + raise Error::MindeeError, 'Could not resolve server response.' if response.nil? + + raise Mindee::HTTP::ErrorHandler.handle_error(@url_name, response) + end + + # Calls the parsed async doc. + # @param job_id [String] + # @return [Array] + def parse_async(job_id) + check_api_key + response = document_queue_req_get(job_id) + hashed_response = JSON.parse(response.body, object_class: Hash) + return [hashed_response, response.body] if Mindee::HTTP::ResponseValidation.valid_async_response?(response) + + Mindee::HTTP::ResponseValidation.clean_request!(response) + error = Mindee::HTTP::ErrorHandler.handle_error(@url_name, response) + raise error + end + + private + + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param opts [ParseOptions] Parse options. + # @return [Net::HTTPResponse, nil] + def predict_req_post(input_source, opts) + uri = URI("#{@url_root}/predict") + + params = {} # : Hash[String | Symbol, untyped] + params[:cropper] = 'true' if opts.cropper + params[:full_text_ocr] = 'true' if opts.full_text + uri.query = URI.encode_www_form(params) + + headers = { + 'Authorization' => "Token #{@api_key}", + 'User-Agent' => USER_AGENT, + } + req = Net::HTTP::Post.new(uri, headers) + form_data = if input_source.is_a?(Mindee::Input::Source::URLInputSource) + [['document', input_source.url]] # : Array[untyped] + else + [['document', *input_source.read_contents(close: opts.close_file)]] # : Array[untyped] + end + form_data.push ['include_mvision', 'true'] if opts.all_words + + req.set_form(form_data, 'multipart/form-data') + req['Transfer-Encoding'] = 'chunked' + + Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @request_timeout) do |http| + return http.request(req) + end + raise Mindee::Error::MindeeError, 'Could not resolve server response.' + end + + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param opts [ParseOptions] Parse options. + # @return [Net::HTTPResponse] + def document_queue_req_post(input_source, opts) + uri = if opts.workflow_id + URI("#{@base_url}/workflows/#{opts.workflow_id}/predict_async") + else + URI("#{@url_root}/predict_async") + end + + params = {} # : Hash[String | Symbol, untyped] + params[:cropper] = 'true' if opts.cropper + params[:full_text_ocr] = 'true' if opts.full_text + params[:rag] = 'true' if opts.rag + uri.query = URI.encode_www_form(params) + + headers = { + 'Authorization' => "Token #{@api_key}", + 'User-Agent' => USER_AGENT, + } + req = Net::HTTP::Post.new(uri, headers) + form_data = if input_source.is_a?(Mindee::Input::Source::URLInputSource) + [['document', input_source.url]] # : Array[untyped] + else + [['document', *input_source.read_contents(close: opts.close_file)]] # : Array[untyped] + end + form_data.push ['include_mvision', 'true'] if opts.all_words + + req.set_form(form_data, 'multipart/form-data') + req['Transfer-Encoding'] = 'chunked' + + Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @request_timeout) do |http| + return http.request(req) + end + raise Mindee::Error::MindeeError, 'Could not resolve server response.' + end + + # @param job_id [String] + # @return [Net::HTTPResponse, nil] + def document_queue_req_get(job_id) + uri = URI("#{@url_root}/documents/queue/#{job_id}") + + headers = { + 'Authorization' => "Token #{@api_key}", + 'User-Agent' => USER_AGENT, + } + + req = Net::HTTP::Get.new(uri, headers) + + response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @request_timeout) do |http| + http.request(req) + end + + raise Error::MindeeError, 'Could not resolve server response.' if response.nil? + + if response.code.to_i > 299 && response.code.to_i < 400 + req = Net::HTTP::Get.new(response['location'], headers) + Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @request_timeout) do |http| + response = http.request(req) + end + end + response + end + + # Checks API key + def check_api_key + return unless @api_key.nil? || @api_key.empty? + + raise Error::MindeeAPIError, + "Missing API key for product \"'#{@url_name}' v#{@version}\" (belonging to \"#{@owner}\"), " \ + "check your Client Configuration.\nYou can set this using the " \ + "'#{HTTP::API_KEY_ENV_NAME}' environment variable." + end + end + end + end +end diff --git a/lib/mindee/v1/http/workflow_endpoint.rb b/lib/mindee/v1/http/workflow_endpoint.rb new file mode 100644 index 000000000..46d55cf65 --- /dev/null +++ b/lib/mindee/v1/http/workflow_endpoint.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true + +require 'json' +require 'net/http' +require_relative '../../http/http_error_handler' + +module Mindee + module V1 + module HTTP + # Handles the routing for workflow calls. + class WorkflowEndpoint + # @return [String] + attr_reader :api_key + # @return [Integer] + attr_reader :request_timeout + # @return [String] + attr_reader :url + + def initialize(workflow_id, api_key: '') + @request_timeout = ENV.fetch(REQUEST_TIMEOUT_ENV_NAME, TIMEOUT_DEFAULT).to_i + @api_key = api_key.nil? || api_key.empty? ? ENV.fetch(API_KEY_ENV_NAME, API_KEY_DEFAULT) : api_key + base_url = ENV.fetch(BASE_URL_ENV_NAME, BASE_URL_DEFAULT) + @url = "#{base_url.chomp('/')}/workflows/#{workflow_id}/executions" + end + + # Sends a document to the workflow. + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param opts [WorkflowOptions] Options to configure workflow execution behavior. + # @return [Array] + def execute_workflow(input_source, opts) + check_api_key + response = workflow_execution_req_post(input_source, opts) + if response.nil? + raise Mindee::Error::MindeeHTTPError.new( + { code: 0, details: 'Server response was nil.', message: 'Unknown error.' }, @url, 0 + ) + end + + hashed_response = JSON.parse(response.body, object_class: Hash) + return [hashed_response, response.body] if Mindee::HTTP::ResponseValidation.valid_async_response?(response) + + Mindee::HTTP::ResponseValidation.clean_request!(response) + error = Mindee::HTTP::ErrorHandler.handle_error(@url_name, response) + raise error + end + + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param opts [WorkflowOptions] Options to configure workflow execution behavior. + # @return [Net::HTTPResponse, nil] + def workflow_execution_req_post(input_source, opts) + uri = URI(@url) + params = {} # : Hash[String | Symbol, untyped] + params[:full_text_ocr] = 'true' if opts.full_text + params[:rag] = 'true' if opts.rag + uri.query = URI.encode_www_form(params) if params.any? + + headers = { + 'Authorization' => "Token #{@api_key}", + 'User-Agent' => USER_AGENT, + } + req = Net::HTTP::Post.new(uri, headers) + form_data = [] # : Array[untyped] + if input_source.is_a?(Mindee::Input::Source::URLInputSource) + form_data.push ['document', input_source.url] + else + form_data.push ['document', *input_source.read_contents(close: opts.close_file)] + end + form_data.push ['alias', opts.document_alias] if opts.document_alias + form_data.push ['public_url', opts.public_url] if opts.public_url + form_data.push ['priority', opts.priority.to_s] if opts.priority + + req.set_form(form_data, 'multipart/form-data') + req['Transfer-Encoding'] = 'chunked' + + response = nil + Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @request_timeout) do |http| + response = http.request(req) + end + response + end + + # Checks API key + def check_api_key + return unless @api_key.nil? || @api_key.empty? + + raise Error::MindeeConfigurationError, "Missing API key. Check your Client Configuration.\n" \ + "You can set this using the '#{HTTP::API_KEY_ENV_NAME}'" \ + 'environment variable.' + end + end + end + end +end diff --git a/lib/mindee/parsing.rb b/lib/mindee/v1/parsing.rb similarity index 100% rename from lib/mindee/parsing.rb rename to lib/mindee/v1/parsing.rb diff --git a/lib/mindee/parsing/common.rb b/lib/mindee/v1/parsing/common.rb similarity index 100% rename from lib/mindee/parsing/common.rb rename to lib/mindee/v1/parsing/common.rb diff --git a/lib/mindee/v1/parsing/common/api_request.rb b/lib/mindee/v1/parsing/common/api_request.rb new file mode 100644 index 000000000..f5ce0adf4 --- /dev/null +++ b/lib/mindee/v1/parsing/common/api_request.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Common + # HTTP request response. + class ApiRequest + # @return [Hash] + attr_reader :error + # @return [Array] + attr_reader :resources + # @return [RequestStatus, Symbol] + attr_reader :status + # @return [Integer] + attr_reader :status_code + # @return [String] + attr_reader :url + + def initialize(server_response) + @error = server_response['error'] + @resources = server_response['resources'] + + @status = if server_response['status'] == 'failure' + RequestStatus::FAILURE + elsif server_response['status'] == 'success' + RequestStatus::SUCCESS + else + server_response['status']&.to_sym + end + @status_code = server_response['status_code'] + @url = server_response['url'] + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/api_response.rb b/lib/mindee/v1/parsing/common/api_response.rb new file mode 100644 index 000000000..e1b166589 --- /dev/null +++ b/lib/mindee/v1/parsing/common/api_response.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +require_relative 'document' +require_relative '../../../logging' + +module Mindee + module V1 + module Parsing + module Common + # Potential values for queue in asynchronous calls. + module JobStatus + # Job is waiting. + WAITING = :waiting + # Job is processing. + PROCESSING = :processing + # Job is done. + COMPLETED = :completed + # Job failed. + FAILURE = :failed + end + + # Potential values for requests. + module RequestStatus + # Failed. + FAILURE = :failure + # Success. + SUCCESS = :success + end + + # Wrapper class for all predictions (synchronous and asynchronous) + class ApiResponse + # @return [Mindee::V1::Parsing::Common::Document, nil] + attr_reader :document + # @return [Mindee::V1::Parsing::Common::Job, nil] + attr_reader :job + # @return [Mindee::V1::Parsing::Common::ApiRequest] + attr_reader :api_request + # @return [String] + attr_reader :raw_http + + # @param product_class [Mindee::Inference] + # @param http_response [Hash] + # @param raw_http [String] + def initialize(product_class, http_response, raw_http) + logger.debug('Handling API response') + @raw_http = raw_http + raise Error::MindeeAPIError, 'Invalid response format.' unless http_response.key?('api_request') + + @api_request = Mindee::V1::Parsing::Common::ApiRequest.new(http_response['api_request']) + + if http_response.key?('document') && + (!http_response.key?('job') || + http_response['job']['status'] == 'completed') && + @api_request.status == RequestStatus::SUCCESS + @document = Mindee::V1::Parsing::Common::Document.new(product_class, http_response['document']) + end + @job = Mindee::V1::Parsing::Common::Job.new(http_response['job']) if http_response.key?('job') + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/document.rb b/lib/mindee/v1/parsing/common/document.rb new file mode 100644 index 000000000..e1e92cb52 --- /dev/null +++ b/lib/mindee/v1/parsing/common/document.rb @@ -0,0 +1,86 @@ +# frozen_string_literal: true + +require_relative 'inference' +require_relative 'extras' + +module Mindee + module V1 + module Parsing + module Common + # Stores all response attributes. + class Document + # @return [Mindee::Inference] + attr_reader :inference + # @return [String] Filename sent to the API + attr_reader :name + # @return [String] Mindee ID of the document + attr_reader :id + # @return [Mindee::V1::Parsing::Common::Extras::Extras] Potential Extras fields sent back along the prediction + attr_reader :extras + # @return [Mindee::V1::Parsing::Common::OCR::OCR, nil] OCR text results (limited availability) + attr_reader :ocr + # @return [Integer] Amount of pages of the document + attr_reader :n_pages + + # Loads the MVision OCR response. + # @param http_response [Hash] Full HTTP contents of the response. + # @return [Mindee::V1::Parsing::Common::OCR::OCR] + def self.load_ocr(http_response) + ocr_prediction = http_response.fetch('ocr', nil) + return nil if ocr_prediction.nil? || ocr_prediction.fetch('mvision-v1', nil).nil? + + OCR::OCR.new(ocr_prediction) + end + + # Loads extras into the document prediction. + # @param http_response [Hash] Full HTTP contents of the response. + # @return [Mindee::V1::Parsing::Common::OCR::OCR] + def self.extract_extras(http_response) + extras_prediction = http_response['inference'].fetch('extras', nil) + return nil if extras_prediction.nil? || extras_prediction.fetch('mvision-v1', nil).nil? + + Mindee::V1::Parsing::Common::Extras::Extras.new(extras_prediction) + end + + # @param product_class [Mindee::Inference] + # @param http_response [Hash] + def initialize(product_class, http_response) + @id = http_response['id'] + @name = http_response['name'] + @inference = product_class.new(http_response['inference']) + @ocr = self.class.load_ocr(http_response) + @extras = self.class.extract_extras(http_response) + inject_full_text_ocr(http_response) + @n_pages = http_response['n_pages'] + end + + # @return [String] + def to_s + out_str = String.new + out_str << "########\nDocument\n########" + out_str << "\n:Mindee ID: #{@id}" + out_str << "\n:Filename: #{@name}" + out_str << "\n\n#{@inference}" + end + + private + + def inject_full_text_ocr(raw_prediction) + return unless raw_prediction.dig('inference', 'pages', 0, 'extras', 'full_text_ocr') + + full_text_ocr = String.new + raw_prediction.dig('inference', 'pages').each do |page| + full_text_ocr << page['extras']['full_text_ocr']['content'] + end + artificial_text_obj = { 'content' => full_text_ocr } + if @extras.nil? || @extras.empty? + @extras = Mindee::V1::Parsing::Common::Extras::Extras.new({ 'full_text_ocr' => artificial_text_obj }) + else + @extras.add_artificial_extra({ 'full_text_ocr' => artificial_text_obj }) + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/execution.rb b/lib/mindee/v1/parsing/common/execution.rb new file mode 100644 index 000000000..bfb9f1a24 --- /dev/null +++ b/lib/mindee/v1/parsing/common/execution.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Common + # Identifier for the batch to which the execution belongs. + class Execution + # Identifier for the batch to which the execution belongs. + # @return [String] + attr_reader :batch_name + # The time at which the execution started. + # @return [Time, nil] + attr_reader :created_at + # File representation within a workflow execution. + # @return [ExecutionFile] + attr_reader :file + # Identifier for the execution. + # @return [String] + attr_reader :id + # Deserialized inference object. + # @return [Mindee::Inference] + attr_reader :inference + # Priority of the execution. + # @return [ExecutionPriority, Symbol, nil] + attr_reader :priority + # The time at which the file was tagged as reviewed. + # @return [Time, nil] + attr_reader :reviewed_at + # The time at which the file was uploaded to a workflow. + # @return [Time, nil] + attr_reader :available_at + # Reviewed fields and values. + # @return [Mindee::V1::Product::Universal::UniversalDocument] + attr_reader :reviewed_prediction + # Execution Status. + # @return [String] + attr_reader :status + # Execution type. + # @return [String] + attr_reader :type + # The time at which the file was uploaded to a workflow. + # @return [Time, nil] + attr_reader :uploaded_at + # Identifier for the workflow. + # @return [String] + attr_reader :workflow_id + + # rubocop:disable Metrics/CyclomaticComplexity + + # @param product_class [Mindee::Inference] + # @param http_response [Hash] + def initialize(product_class, http_response) + @batch_name = http_response['batch_name'] + @created_at = Time.iso8601(http_response['created_at']) if http_response['created_at'] + @file = ExecutionFile.new(http_response['file']) if http_response['file'] + @id = http_response['id'] + @inference = product_class.new(http_response['inference']) if http_response['inference'] + @priority = Mindee::V1::Parsing::Common::ExecutionPriority.to_priority(http_response['priority']) + @reviewed_at = Time.iso8601(http_response['reviewed_at']) if http_response['reviewed_at'] + @available_at = Time.iso8601(http_response['available_at']) if http_response['available_at'] + if http_response['reviewed_prediction'] + @reviewed_prediction = Mindee::V1::Product::Universal::UniversalDocument.new( + http_response['reviewed_prediction'] + ) + end + @status = http_response['status'] + @type = http_response['type'] + @uploaded_at = Time.iso8601(http_response['uploaded_at']) if http_response['uploaded_at'] + @workflow_id = http_response['workflow_id'] + end + + # rubocop:enable Metrics/CyclomaticComplexity + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/execution_file.rb b/lib/mindee/v1/parsing/common/execution_file.rb new file mode 100644 index 000000000..953509d86 --- /dev/null +++ b/lib/mindee/v1/parsing/common/execution_file.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Common + # Representation of a workflow execution's file data. + class ExecutionFile + # File name. + # @return [String] + attr_reader :name + + # Optional alias for the file. + # @return [String] + attr_reader :alias + + # @param http_response [Hash] + def initialize(http_response) + @name = http_response['name'] + @alias = http_response['alias'] + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/execution_priority.rb b/lib/mindee/v1/parsing/common/execution_priority.rb new file mode 100644 index 000000000..764012a85 --- /dev/null +++ b/lib/mindee/v1/parsing/common/execution_priority.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Common + # Execution policy priority values. + module ExecutionPriority + # Low priority execution. + # @return [Symbol] :low + LOW = :low + # Medium priority execution. + # @return [Symbol] :low + MEDIUM = :medium + # High priority execution. + # @return [Symbol] :low + HIGH = :high + + # Sets the priority to one of its possibly values, defaults to nil otherwise. + # @param [String, nil] priority_str + # @return [Symbol, nil] + def self.to_priority(priority_str) + return nil if priority_str.nil? + + case priority_str.downcase + when 'low' + :low + when 'high' + :high + else + :medium + end + end + end + end + end + end +end diff --git a/lib/mindee/parsing/common/extras.rb b/lib/mindee/v1/parsing/common/extras.rb similarity index 100% rename from lib/mindee/parsing/common/extras.rb rename to lib/mindee/v1/parsing/common/extras.rb diff --git a/lib/mindee/v1/parsing/common/extras/cropper_extra.rb b/lib/mindee/v1/parsing/common/extras/cropper_extra.rb new file mode 100644 index 000000000..a1290dfb2 --- /dev/null +++ b/lib/mindee/v1/parsing/common/extras/cropper_extra.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require_relative '../../standard/position_field' + +module Mindee + module V1 + module Parsing + module Common + module Extras + # Contains information on the cropping of a prediction. + class CropperExtra + # Cropper extra initialization. + # @return [Array] + attr_reader :croppings + + def initialize(raw_prediction, page_id = nil) + @croppings = [] # : Array[Mindee::V1::Parsing::Standard::PositionField] + raw_prediction['cropping']&.each do |crop| + @croppings.push(Mindee::V1::Parsing::Standard::PositionField.new(crop, page_id)) + end + end + + # @return [String] + def to_s + @croppings.join("\n ") + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/extras/extras.rb b/lib/mindee/v1/parsing/common/extras/extras.rb new file mode 100644 index 000000000..a7f32533c --- /dev/null +++ b/lib/mindee/v1/parsing/common/extras/extras.rb @@ -0,0 +1,62 @@ +# frozen_string_literal: true + +require_relative '../../standard/position_field' + +module Mindee + module V1 + module Parsing + module Common + # Extras namespace. + module Extras + # Extra information added to the prediction. + class Extras + # @return [CropperExtra, nil] + attr_reader :cropper + # @return [Mindee::V1::Parsing::Common::Extras::FullTextOCRExtra] + attr_reader :full_text_ocr + # @return [RAGExtra, nil] + attr_reader :rag + + def initialize(raw_prediction) + if raw_prediction['cropper'] + @cropper = Mindee::V1::Parsing::Common::Extras::CropperExtra.new(raw_prediction['cropper']) + end + if raw_prediction['full_text_ocr'] + @full_text_ocr = Mindee::V1::Parsing::Common::Extras::FullTextOCRExtra.new( + raw_prediction['full_text_ocr'] + ) + end + @rag = Mindee::V1::Parsing::Common::Extras::RAGExtra.new(raw_prediction['rag']) if raw_prediction['rag'] + + raw_prediction.each do |key, value| + instance_variable_set("@#{key}", value) unless ['cropper', 'full_text_ocr', 'rag'].include?(key.to_s) + end + end + + # @return [String] + def to_s + out_str = String.new + instance_variables.each do |var| + out_str << "#{var}: #{instance_variable_get(var)}" + end + out_str + end + + # Adds artificial extra data for reconstructed extras. Currently only used for full_text_ocr. + # + # @param [Hash] raw_prediction Raw prediction used by the document. + def add_artificial_extra(raw_prediction) + return unless raw_prediction['full_text_ocr'] + + @full_text_ocr << Mindee::V1::Parsing::Common::Extras::FullTextOCRExtra.new(raw_prediction) + end + end + + def empty? + instance_variables.all? { |var| instance_variable_get(var).nil? } + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/extras/full_text_ocr_extra.rb b/lib/mindee/v1/parsing/common/extras/full_text_ocr_extra.rb new file mode 100644 index 000000000..8ef69cf90 --- /dev/null +++ b/lib/mindee/v1/parsing/common/extras/full_text_ocr_extra.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require_relative '../../standard/position_field' + +module Mindee + module V1 + module Parsing + module Common + module Extras + # Full Text OCR result. + class FullTextOCRExtra + # Contents of the full text OCR result. + # @return [String, nil] + attr_reader :contents + # Language used on the page. + # @return [String, nil] + attr_reader :language + + def initialize(raw_prediction) + @contents = raw_prediction['content'] if raw_prediction['content'] + return unless raw_prediction['language'] + + @language = raw_prediction['language'] + end + + # @return [String] + def to_s + @contents || '' + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/extras/rag_extra.rb b/lib/mindee/v1/parsing/common/extras/rag_extra.rb new file mode 100644 index 000000000..7dc530e78 --- /dev/null +++ b/lib/mindee/v1/parsing/common/extras/rag_extra.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Common + module Extras + # Retrieval-Augmented Generation extra. + class RAGExtra + # ID of the matching document + # @return [String, nil] + attr_reader :matching_document_id + + def initialize(raw_prediction) + @matching_document_id = raw_prediction['matching_document_id'] if raw_prediction['matching_document_id'] + end + + # String representation. + # @return [String] + def to_s + @matching_document_id || '' + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/inference.rb b/lib/mindee/v1/parsing/common/inference.rb new file mode 100644 index 000000000..53dfcf77e --- /dev/null +++ b/lib/mindee/v1/parsing/common/inference.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +require_relative 'product' + +module Mindee + module V1 + module Parsing + # Common fields used for most documents. + module Common + # Abstract class for prediction Inferences + # Holds prediction for a page or entire document. + class Inference + # @return [bool] + attr_reader :is_rotation_applied + # @return [Array] + attr_reader :pages + # @return [Mindee::V1::Parsing::Common::Prediction] + attr_reader :prediction + # @return [Mindee::V1::Parsing::Common::Product] + attr_reader :product + # Name of the endpoint for this product. + # @return [String] + attr_reader :endpoint_name + # Version for this product. + # @return [String] + attr_reader :endpoint_version + # Whether this product has access to an asynchronous endpoint. + # @return [bool] + attr_reader :has_async + # Whether this product has access to synchronous endpoint. + # @return [bool] + attr_reader :has_sync + # @return [Mindee::V1::Parsing::Common::Extras::Extras] Potential Extras fields sent back along the prediction + attr_reader :extras + + @endpoint_name = nil + @endpoint_version = nil + @has_async = false + @has_sync = false + + # @param raw_prediction [Hash] + def initialize(raw_prediction) + @is_rotation_applied = raw_prediction['is_rotation_applied'] + @product = Product.new(raw_prediction['product']) + @pages = [] # : Array[Page] + @extras = Extras::Extras.new(raw_prediction['extras']) if raw_prediction.include?('extras') + end + + # @return [String] + def to_s + is_rotation_applied = @is_rotation_applied ? 'Yes' : 'No' + out_str = String.new + out_str << "Inference\n#########" + out_str << "\n:Product: #{@product.name} v#{@product.version}" + out_str << "\n:Rotation applied: #{is_rotation_applied}" + out_str << "\n\nPrediction\n==========" + out_str << "\n#{"#{@prediction}\n" if @prediction.to_s.size.positive?}" + if @pages.any? { |page| !page.prediction.nil? } + out_str << "\nPage Predictions\n================\n\n" + out_str << @pages.join("\n\n") + end + out_str.rstrip! + out_str + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/job.rb b/lib/mindee/v1/parsing/common/job.rb new file mode 100644 index 000000000..de99c6a1c --- /dev/null +++ b/lib/mindee/v1/parsing/common/job.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +require 'time' + +module Mindee + module V1 + module Parsing + module Common + # Job (queue) information on async parsing. + class Job + # @return [String] Mindee ID of the document + attr_reader :id + # @return [Time] + attr_reader :issued_at + # @return [Time, nil] + attr_reader :available_at + # @return [JobStatus, Symbol] + attr_reader :status + # @return [Integer, nil] + attr_reader :millisecs_taken + # @return [Hash, nil] + attr_reader :error + + # @param http_response [Hash] + def initialize(http_response) + @id = http_response['id'] + @error = http_response['error'] + @issued_at = Time.iso8601(http_response['issued_at']) + if http_response.key?('available_at') && !http_response['available_at'].nil? + @available_at = Time.iso8601(http_response['available_at']) + @millisecs_taken = (1000 * (@available_at.to_time - @issued_at.to_time).to_f).to_i + end + @status = case http_response['status'] + when 'waiting' + JobStatus::WAITING + when 'processing' + JobStatus::PROCESSING + when 'completed' + JobStatus::COMPLETED + else + http_response['status']&.to_sym + end + end + end + end + end + end +end diff --git a/lib/mindee/parsing/common/ocr.rb b/lib/mindee/v1/parsing/common/ocr.rb similarity index 100% rename from lib/mindee/parsing/common/ocr.rb rename to lib/mindee/v1/parsing/common/ocr.rb diff --git a/lib/mindee/v1/parsing/common/ocr/mvision_v1.rb b/lib/mindee/v1/parsing/common/ocr/mvision_v1.rb new file mode 100644 index 000000000..fdc0dd31f --- /dev/null +++ b/lib/mindee/v1/parsing/common/ocr/mvision_v1.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Common + module OCR + # Mindee Vision V1. + class MVisionV1 + # List of pages. + # @return [Array] + attr_reader :pages + + # @param prediction [Hash] + def initialize(prediction) + @pages = [] # : Array[Mindee::V1::Parsing::Common::OCR::OCRPage] + prediction['pages'].each do |page_prediction| + @pages.push(OCRPage.new(page_prediction)) + end + end + + # @return [String] + def to_s + out_str = String.new + @pages.map do |page| + out_str << "\n" + out_str << page.to_s + end + out_str.strip + end + + # Constructs a line from a column, located underneath given coordinates + # @param coordinates [Array] Polygon or bounding box where the reconstruction + # should start. + # @param page_id [Integer] ID of the page to start at + # @param x_margin [Float] Margin of misalignment for the x coordinate. + # @return [Mindee::V1::Parsing::Common::OCR::OCRLine] + def reconstruct_vertically(coordinates, page_id, x_margin) + line_arr = OCRLine.new([]) + @pages[page_id].all_lines.each do |line| + line.each do |word| + line_arr.push(word) if Geometry.below?(word.polygon, coordinates, x_margin / 2, x_margin * 2) + end + end + line_arr + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/ocr/ocr.rb b/lib/mindee/v1/parsing/common/ocr/ocr.rb new file mode 100644 index 000000000..794136674 --- /dev/null +++ b/lib/mindee/v1/parsing/common/ocr/ocr.rb @@ -0,0 +1,180 @@ +# frozen_string_literal: true + +require_relative 'mvision_v1' + +module Mindee + module V1 + module Parsing + module Common + # OCR-specific parsing fields and options + module OCR + # A single word. + class OCRWord + # The confidence score, value will be between 0.0 and 1.0 + # @return [Float] + attr_reader :confidence + # @return [String] + attr_reader :text + # @return [Mindee::Geometry::Quadrilateral] + attr_reader :bounding_box + # @return [Mindee::Geometry::Polygon] + attr_reader :polygon + + # @param prediction [Hash] + def initialize(prediction) + @text = prediction['text'] + @confidence = prediction['confidence'] + @polygon = Mindee::Geometry::Polygon.new(prediction['polygon']) + @bounding_box = Geometry.get_bounding_box(@polygon) unless @polygon.nil? || @polygon.empty? + end + + # @return [String] + def to_s + @text.to_s + end + end + + # A list of words which are on the same line. + class OCRLine < Array + # @param prediction [Hash, nil] + # @param from_array [Array, nil] + def initialize(prediction = nil, from_array = nil) + if !prediction.nil? + super(prediction.map { |word_prediction| OCRWord.new(word_prediction) }) + elsif !from_array.nil? + super(from_array) + end + end + + # Sort the words on the line from left to right. + # @return [OCRLine] + def sort_on_x + from_array = sort_by { |word| Geometry.get_min_max_x(word.polygon).min } + OCRLine.new(nil, from_array) + end + + # @return [String] + def to_s + each(&:to_s).join(' ') + end + end + + # OCR extraction for a single page. + class OCRPage + # All the words on the page, in semi-random order. + # @return [Array] + attr_reader :all_words + # @return [Array] + attr_reader :lines + + # @param prediction [Hash] + def initialize(prediction) + @lines = [] # : Array[Mindee::V1::Parsing::Common::OCR::OCRLine] + @all_words = [] # : Array[Mindee::V1::Parsing::Common::OCR::OCRWord] + prediction['all_words'].each do |word_prediction| + @all_words.push(OCRWord.new(word_prediction)) + end + end + + # All the words on the page, ordered in lines. + # @return [Array] + def all_lines + @lines = to_lines if @lines.empty? + @lines + end + + # @return [String] + def to_s + lines = all_lines + return '' if lines.empty? + + out_str = String.new + lines.map do |line| + out_str << "#{line}\n" unless line.to_s.strip.empty? + end + out_str.strip + end + + private + + # Helper function that iterates through all the words and compares them to a candidate + # @param sorted_words [Array] + # @param current [OCRWord] + # @param indexes [Array] + # @param lines [Array] + def parse_one(sorted_words, current, indexes, lines) + line = OCRLine.new(nil, []) + sorted_words.each_with_index do |word, idx| + next if indexes.include?(idx) + + if current.nil? + current = word + indexes.push(idx) + line = OCRLine.new([]) + line.push(word) + elsif words_on_same_line?(current, word) + line.push(word) + indexes.push(idx) + end + end + lines.push(line.sort_on_x) if line.any? + end + + # Order all the words on the page into lines. + # @return [Array] + def to_lines + current = nil + indexes = [] # : Array[Integer] + lines = [] # : Array[Mindee::V1::Parsing::Common::OCR::OCRLine] + + # make sure words are sorted from top to bottom + all_words = @all_words.sort_by { |word| Geometry.get_min_max_y(word.polygon).min } + all_words.each do + parse_one(all_words, current, indexes, lines) + current = nil + end + lines + end + + # Determine if two words are on the same line. + # @param current_word [Mindee::V1::Parsing::Common::OCR::OCRWord] + # @param next_word [Mindee::V1::Parsing::Common::OCR::OCRWord] + # @return [bool] + def words_on_same_line?(current_word, next_word) + current_in_next = current_word.polygon.point_in_y?(next_word.polygon.centroid) + next_in_current = next_word.polygon.point_in_y?(current_word.polygon.centroid) unless current_word.nil? + current_in_next || next_in_current + end + end + + # OCR extraction from the entire document. + class OCR + # Mindee Vision v1 results. + # @return [Mindee::V1::Parsing::Common::OCR::MVisionV1] + attr_reader :mvision_v1 + + # @param prediction [Hash] + def initialize(prediction) + @mvision_v1 = Mindee::V1::Parsing::Common::OCR::MVisionV1.new(prediction['mvision-v1']) + end + + # @return [String] + def to_s + @mvision_v1.to_s + end + + # Constructs a line from a column, located underneath given coordinates + # @param coordinates [Array] Polygon or bounding box where the reconstruction + # should start + # @param page_id [Integer] ID of the page to start at + # @param x_margin [Float] Margin of misalignment for the x coordinate (default 10%) + # @return [Mindee::V1::Parsing::Common::OCR::OCRLine] + def reconstruct_vertically(coordinates, page_id, x_margin = 0.05) + @mvision_v1.reconstruct_vertically(coordinates, page_id, x_margin) + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/orientation.rb b/lib/mindee/v1/parsing/common/orientation.rb new file mode 100644 index 000000000..52d23e696 --- /dev/null +++ b/lib/mindee/v1/parsing/common/orientation.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Common + # Page orientation + class Orientation + # @return [Integer, nil] + attr_reader :page_id + # A prediction among these 3 possible outputs: + # * 0 degrees: the page is already upright + # * 90 degrees: the page must be rotated clockwise to be upright + # * 270 degrees: the page must be rotated counterclockwise to be upright + # @return [Integer, nil] + attr_reader :value + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + @value = prediction['value'] + @page_id = page_id + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/page.rb b/lib/mindee/v1/parsing/common/page.rb new file mode 100644 index 000000000..009641bb8 --- /dev/null +++ b/lib/mindee/v1/parsing/common/page.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require_relative 'product' +require_relative 'extras' + +module Mindee + module V1 + module Parsing + # Common fields used for most documents. + module Common + # Abstract wrapper class for prediction Pages + # Holds prediction for a page as well as it's orientation and id. + class Page + # ID of the page (as given by the API). + # @return [Integer] + attr_reader :page_id + # Orientation of the page. + # @return [Mindee::V1::Parsing::Common::Orientation] + attr_reader :orientation + # Page prediction + # @return [Mindee::V1::Parsing::Common::Prediction] + attr_reader :prediction + # Additional page-level information. + # @return [Mindee::V1::Parsing::Common::Extras::Extras] + attr_reader :extras + + # @param raw_prediction [Hash] + def initialize(raw_prediction) + @page_id = raw_prediction['id'] + @orientation = Mindee::V1::Parsing::Common::Orientation.new(raw_prediction['orientation'], @page_id) + return if raw_prediction['extras'].nil? + + @extras = Mindee::V1::Parsing::Common::Extras::Extras.new(raw_prediction['extras']) + end + + # @return [String] + def to_s + out_str = String.new + title = "Page #{@page_id}" + out_str << "#{title}\n" + out_str << ('-' * title.size) + out_str << @prediction.to_s + out_str + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/prediction.rb b/lib/mindee/v1/parsing/common/prediction.rb new file mode 100644 index 000000000..b4da8232c --- /dev/null +++ b/lib/mindee/v1/parsing/common/prediction.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Common + # Abstract class for all predictions + class Prediction + # @return [String] + def to_s + '' + end + + def initialize(_ = nil, _ = nil); end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/product.rb b/lib/mindee/v1/parsing/common/product.rb new file mode 100644 index 000000000..cb33c6ef8 --- /dev/null +++ b/lib/mindee/v1/parsing/common/product.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Common + # Product information + class Product + # @return [String] Name of the product. + attr_reader :name + # @return [String?] Type of product. + attr_reader :type + # @return [String] Product version. + attr_reader :version + + # @param prediction [Hash] + def initialize(prediction) + @name = prediction['name'] + @type = prediction['type'] + @version = prediction['version'] + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/common/workflow_response.rb b/lib/mindee/v1/parsing/common/workflow_response.rb new file mode 100644 index 000000000..1fa2b4117 --- /dev/null +++ b/lib/mindee/v1/parsing/common/workflow_response.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Common + # Represents the server response after a document is sent to a workflow. + class WorkflowResponse + # Set the prediction model used to parse the document. + # The response object will be instantiated based on this parameter. + # @return [Mindee::V1::Parsing::Common::Execution] + attr_reader :execution + # @return [Mindee::V1::Parsing::Common::ApiRequest] + attr_reader :api_request + # @return [String] + attr_reader :raw_http + + # @param http_response [Hash] + # @param product_class [Mindee::Inference] + def initialize(product_class, http_response, raw_http) + @raw_http = raw_http.to_s + @api_request = Mindee::V1::Parsing::Common::ApiRequest.new(http_response['api_request']) + product_class ||= Mindee::V1::Product::Universal::Universal + @execution = Mindee::V1::Parsing::Common::Execution.new(product_class, http_response['execution']) + end + end + end + end + end +end diff --git a/lib/mindee/parsing/standard.rb b/lib/mindee/v1/parsing/standard.rb similarity index 100% rename from lib/mindee/parsing/standard.rb rename to lib/mindee/v1/parsing/standard.rb diff --git a/lib/mindee/v1/parsing/standard/abstract_field.rb b/lib/mindee/v1/parsing/standard/abstract_field.rb new file mode 100644 index 000000000..93fe01abb --- /dev/null +++ b/lib/mindee/v1/parsing/standard/abstract_field.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +require_relative '../../../geometry' + +module Mindee + module V1 + module Parsing + module Standard + # Base BaseField object, upon which fields and feature fields are built + class AbstractField + # @return [Mindee::Geometry::Quadrilateral, nil] + attr_reader :bounding_box + # @return [Mindee::Geometry::Polygon, nil] + attr_reader :polygon + # @return [Integer, nil] + attr_reader :page_id + # The confidence score, value will be between 0.0 and 1.0 + # @return [Float, nil] + attr_accessor :confidence + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + @confidence = prediction['confidence'] if prediction.key?('confidence') + @polygon = Mindee::Geometry::Polygon.new(prediction['polygon']) if prediction.key?('polygon') + @bounding_box = Geometry.get_bounding_box(@polygon) unless @polygon.nil? || @polygon.empty? + @page_id = page_id || prediction['page_id'] + end + + # @return [String] + def to_s + @value ? @value.to_s : '' + end + + # Multiply all the Mindee::V1::Parsing::Standard::BaseField confidences in the array. + # @return [Float] + def self.array_confidence(field_array) + product = 1 + field_array.each do |field| + return 0.0 if field.confidence.nil? + + product *= field.confidence + end + product.to_f + end + + # Add all the Mindee::V1::Parsing::Standard::BaseField values in the array. + # @return [Float] + def self.array_sum(field_array) + arr_sum = 0 + field_array.each do |field| + return 0.0 if field.value.nil? + + arr_sum += field.value + end + arr_sum.to_f + end + + # @param value [Float] + # @param min_precision [Integer] + # @return [String] + def self.float_to_string(value, min_precision = 2) + return String.new if value.nil? + + precision = value.to_f.to_s.split('.')[1].size + precision = [precision, min_precision].max + format_string = "%.#{precision}f" + format(format_string, value) + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/address_field.rb b/lib/mindee/v1/parsing/standard/address_field.rb new file mode 100644 index 000000000..05805266c --- /dev/null +++ b/lib/mindee/v1/parsing/standard/address_field.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require_relative 'string_field' + +module Mindee + module V1 + module Parsing + module Standard + # Represents physical-address information. + class AddressField < Mindee::V1::Parsing::Standard::StringField + # Street number + # @return [String, nil] + attr_reader :street_number + # Street name + # @return [String, nil] + attr_reader :street_name + # PO Box number + # @return [String, nil] + attr_reader :po_box + # Address complement + # @return [String, nil] + attr_reader :address_complement + # City name. + # @return [String, nil] + attr_reader :city + # Postal or ZIP code. + # @return [String, nil] + attr_reader :postal_code + # State, province or region. + # @return [String, nil] + attr_reader :state + # Country. + # @return [String, nil] + attr_reader :country + + def initialize(prediction, page_id = nil, reconstructed: false) + super + @street_number = prediction['street_number'] + @street_name = prediction['street_name'] + @po_box = prediction['po_box'] + @address_complement = prediction['address_complement'] + @city = prediction['city'] + @postal_code = prediction['postal_code'] + @state = prediction['state'] + @country = prediction['country'] + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/amount_field.rb b/lib/mindee/v1/parsing/standard/amount_field.rb new file mode 100644 index 000000000..5468d66c8 --- /dev/null +++ b/lib/mindee/v1/parsing/standard/amount_field.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +require_relative 'base_field' + +module Mindee + module V1 + module Parsing + module Standard + # Represents tax information. + class AmountField < BaseField + # Amount value as 3 decimal float + # @return [Float, nil] + attr_reader :value + + def initialize(prediction, page_id, reconstructed: false) + super + @value = @value.to_f.round(3).to_f unless @value.to_s.empty? + end + + # @return [String] + def to_s + @value.nil? ? '' : BaseField.float_to_string(@value.to_f) + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/base_field.rb b/lib/mindee/v1/parsing/standard/base_field.rb new file mode 100644 index 000000000..6bd0c229c --- /dev/null +++ b/lib/mindee/v1/parsing/standard/base_field.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +require_relative '../../../geometry' +require_relative 'abstract_field' + +module Mindee + module V1 + module Parsing + module Standard + # Base field object. + class BaseField < Mindee::V1::Parsing::Standard::AbstractField + # @return [String, Float, Integer, bool] + attr_reader :value + # true if the field was reconstructed or computed using other fields. + # @return [bool] + attr_reader :reconstructed + + # @param prediction [Hash] + # @param page_id [Integer, nil] + # @param reconstructed [bool] + def initialize(prediction, page_id, reconstructed: false) + super(prediction, page_id) + @value = prediction['value'] + @reconstructed = reconstructed + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/boolean_field.rb b/lib/mindee/v1/parsing/standard/boolean_field.rb new file mode 100644 index 000000000..e2bfbcaa5 --- /dev/null +++ b/lib/mindee/v1/parsing/standard/boolean_field.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +require_relative 'base_field' + +module Mindee + module V1 + module Parsing + module Standard + # Represents basic text information. + class BooleanField < BaseField + # Value as bool + # @return [bool, nil] + attr_reader :value + + def initialize(prediction, page_id = nil, reconstructed: false) + super + end + + # @return [String] + def to_s + return '' if value.nil? + + value ? 'True' : 'False' + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/classification_field.rb b/lib/mindee/v1/parsing/standard/classification_field.rb new file mode 100644 index 000000000..539554dc3 --- /dev/null +++ b/lib/mindee/v1/parsing/standard/classification_field.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +require_relative 'base_field' + +module Mindee + module V1 + module Parsing + module Standard + # Represents a classifier value. + class ClassificationField < BaseField + # Value as String + # @return [String] + attr_reader :value + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/company_registration_field.rb b/lib/mindee/v1/parsing/standard/company_registration_field.rb new file mode 100644 index 000000000..c8841683a --- /dev/null +++ b/lib/mindee/v1/parsing/standard/company_registration_field.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Standard + # Company registration number or code, and its type. + class CompanyRegistrationField < BaseField + # @return [String] + attr_reader :type + + # @param prediction [Hash] + # @param page_id [Integer, nil] + # @param reconstructed [bool] + def initialize(prediction, page_id, reconstructed: false) + super + @type = prediction['type'] + end + + # Table line representation of the values. + # @return [String] The formatted table line, as a string. + def to_table_line + printable = printable_values + format('| %-15s | %-20s ', type: printable[:type], value: printable[:value]) + end + + # @return [String] + def to_s + printable = printable_values + format('Type: %s, Value: %s', type: printable[:type], value: printable[:value]) + end + + # Hashed representation of the values. + # @return [Hash] Hash of the values. + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:type] = type + printable[:value] = value.to_s + printable + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/date_field.rb b/lib/mindee/v1/parsing/standard/date_field.rb new file mode 100644 index 000000000..ccd5b3912 --- /dev/null +++ b/lib/mindee/v1/parsing/standard/date_field.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +require 'date' + +require_relative 'base_field' + +module Mindee + module V1 + module Parsing + module Standard + # Represents a date. + class DateField < BaseField + # The date as a standard Ruby `Date` object. + # @return [Date, nil] + attr_reader :date_object + # The ISO 8601 representation of the date, regardless of the `raw` contents. + # @return [String, nil] + attr_reader :value + # The textual representation of the date as found on the document. + # @return [String, nil] + attr_reader :raw + # Whether the field was computed or retrieved directly from the document. + # @return [bool, nil] + attr_reader :is_computed + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @is_computed = prediction['is_computed'] + return unless @value + + @date_object = Date.parse(@value) + @raw = prediction['raw'] + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/feature_field.rb b/lib/mindee/v1/parsing/standard/feature_field.rb new file mode 100644 index 000000000..059f7c4cb --- /dev/null +++ b/lib/mindee/v1/parsing/standard/feature_field.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Standard + # Feature field object wrapper for specialized methods. + class FeatureField < AbstractField + # Format strings for display by shortening long strings and assigning empty ones. + # @param in_str [String, bool, nil] + # @param max_col_size [int, nil] + # @return [String] + def format_for_display(in_str, max_col_size = nil) + return 'True' if in_str == true + return 'False' if in_str == false + return '' if in_str.nil? + return in_str.to_s if max_col_size.nil? + + in_str = in_str.to_s.gsub(%r{[\n\r\t]}, "\n" => '\\n', "\r" => '\\r', "\t" => '\\t') + in_str.to_s.length <= max_col_size.to_i ? in_str.to_s : "#{in_str[0..(max_col_size.to_i - 4)]}..." + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/locale_field.rb b/lib/mindee/v1/parsing/standard/locale_field.rb new file mode 100644 index 000000000..660c1f925 --- /dev/null +++ b/lib/mindee/v1/parsing/standard/locale_field.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Standard + # Represents locale information + class LocaleField + # The confidence score, value will be between 0.0 and 1.0 + # @return [Float] + attr_reader :confidence + # Language code in ISO 639-1 format. + # @return [String] + attr_reader :language + # Country code in ISO 3166-1 alpha-2 format. + # @return [String, nil] + attr_reader :country + # Currency code in ISO 4217 format. + # @return [String] + attr_reader :currency + # Language code, with country code when available. + # @return [String] + attr_reader :value + + # @param prediction [Hash] + def initialize(prediction, _page_id = nil) + value_key = if !prediction.include?('value') || prediction['value'].nil? + 'language' + else + 'value' + end + @confidence = prediction['confidence'] + @value = prediction[value_key] + @language = prediction['language'] + @country = prediction['country'] + @currency = prediction['currency'] + end + + # @return [String] + def to_s + out_str = String.new + out_str << "#{@value}; " unless @value.nil? + out_str << "#{@language}; " if @language + out_str << "#{@country}; " if @country + out_str << "#{@currency}; " if @currency + out_str.strip + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/payment_details_field.rb b/lib/mindee/v1/parsing/standard/payment_details_field.rb new file mode 100644 index 000000000..04ac74d2a --- /dev/null +++ b/lib/mindee/v1/parsing/standard/payment_details_field.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +require_relative 'base_field' + +module Mindee + module V1 + module Parsing + module Standard + # Represents payment details for invoices and receipts + class PaymentDetailsField < BaseField + # @return [String, nil] + attr_reader :account_number + # @return [String, nil] + attr_reader :iban + # @return [String, nil] + attr_reader :routing_number + # @return [String, nil] + attr_reader :swift + + # @param prediction [Hash] + # @param page_id [Integer, nil] + # @param reconstructed [bool] + def initialize(prediction, page_id, reconstructed: false) + super + @account_number = prediction['account_number'] + @iban = prediction['iban'] + @routing_number = prediction['routing_number'] + @swift = prediction['swift'] + end + + # @return [String] + def to_s + out_str = String.new + out_str << "#{@account_number}; " if @account_number + out_str << "#{@iban}; " if @iban + out_str << "#{@routing_number}; " if @routing_number + out_str << "#{@swift}; " if @swift + out_str.strip + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/position_field.rb b/lib/mindee/v1/parsing/standard/position_field.rb new file mode 100644 index 000000000..7f408782f --- /dev/null +++ b/lib/mindee/v1/parsing/standard/position_field.rb @@ -0,0 +1,61 @@ +# frozen_string_literal: true + +module Mindee + module V1 + module Parsing + module Standard + # An element's position on the image + class PositionField + # @return [Mindee::Geometry::Polygon] + attr_reader :polygon + # @return [Mindee::Geometry::Polygon] + attr_reader :value + # @return [Mindee::Geometry::Quadrilateral] + attr_reader :quadrangle + # @return [Mindee::Geometry::Quadrilateral] + attr_reader :rectangle + # @return [Mindee::Geometry::Quadrilateral] + attr_reader :bounding_box + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + unless prediction['polygon'].nil? || prediction['polygon'].empty? + @polygon = Mindee::Geometry::Polygon.new(prediction['polygon']) + end + @quadrangle = to_quadrilateral(prediction, 'quadrangle') + @rectangle = to_quadrilateral(prediction, 'rectangle') + @bounding_box = to_quadrilateral(prediction, 'bounding_box') + @page_id = page_id || prediction['page_id'] + @value = @polygon + end + + # rubocop:disable Metrics/CyclomaticComplexity + # rubocop:disable Metrics/PerceivedComplexity + + # String representation. + # @return [String] + def to_s + return "Polygon with #{@polygon.size} points." if @polygon&.size&.positive? + return "Polygon with #{@bounding_box.size} points." if @bounding_box&.size&.positive? + return "Polygon with #{@rectangle.size} points." if @rectangle&.size&.positive? + return "Polygon with #{@quadrangle.size} points." if @quadrangle&.size&.positive? + + '' + end + + # rubocop:enable Metrics/CyclomaticComplexity + # rubocop:enable Metrics/PerceivedComplexity + + private + + def to_quadrilateral(prediction, key) + return if prediction[key].nil? || prediction[key].empty? + + Mindee::Geometry.quadrilateral_from_prediction(prediction[key]) + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/string_field.rb b/lib/mindee/v1/parsing/standard/string_field.rb new file mode 100644 index 000000000..2b6feca22 --- /dev/null +++ b/lib/mindee/v1/parsing/standard/string_field.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +require_relative 'base_field' + +module Mindee + module V1 + module Parsing + module Standard + # Represents basic text information. + class StringField < Mindee::V1::Parsing::Standard::BaseField + # Value as String + # @return [String, nil] + attr_reader :value + # Value as String + # @return [String, nil] + attr_reader :raw_value + + def initialize(prediction, page_id = nil, reconstructed: false) + super + @raw_value = prediction['raw_value'] + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/standard/tax_field.rb b/lib/mindee/v1/parsing/standard/tax_field.rb new file mode 100644 index 000000000..657e0a007 --- /dev/null +++ b/lib/mindee/v1/parsing/standard/tax_field.rb @@ -0,0 +1,110 @@ +# frozen_string_literal: true + +require_relative 'base_field' + +module Mindee + module V1 + module Parsing + module Standard + # Represents tax information. + class TaxField < BaseField + # Tax value as 3 decimal float + # @return [Float, nil] + attr_reader :value + # Tax rate percentage + # @return [Float] + attr_reader :rate + # Tax code + # @return [String] + attr_reader :code + # Tax base + # @return [Float] + attr_reader :base + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @value = prediction['value']&.round(3) + @rate = prediction['rate'].to_f unless prediction['rate'].nil? + @base = prediction['base'].to_f unless prediction['base'].nil? + @code = prediction['code'] unless prediction['code'] == 'None' + end + + # @param value [Float] + def print_float(value) + format('%.2f', value) + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "Base: #{printable[:base]}" + out_str << ", Code: #{printable[:code]}" + out_str << ", Rate (%): #{printable[:rate]}" + out_str << ", Amount: #{printable[:value]}" + out_str.strip + end + + # @return [Hash] + def printable_values + out_h = {} # @type var out_h: Hash[Symbol, String] + out_h[:code] = @code.nil? ? '' : @code + out_h[:base] = @base.nil? ? '' : print_float(@base) + out_h[:rate] = @rate.nil? ? '' : print_float(@rate).to_s + out_h[:value] = @value.to_s.empty? ? '' : print_float(@value.to_f).to_s + out_h + end + + # @return [String] + def to_table_line + printable = printable_values + out_str = String.new + out_str << "| #{printable[:base].ljust(13, ' ')}" + out_str << " | #{printable[:code].ljust(6, ' ')}" + out_str << " | #{printable[:rate].ljust(8, ' ')}" + out_str << " | #{printable[:value].ljust(13, ' ')} |" + out_str.strip + end + end + + # Represents tax information, grouped as an array. + class Taxes < Array + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super(prediction.map { |entry| TaxField.new(entry, page_id) }) + end + + # @param char [String] + # @return [String] + def line_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 15}" + out_str << "+#{char * 8}" + out_str << "+#{char * 10}" + out_str << "+#{char * 15}" + out_str << '+' + out_str + end + + # @return [String] + def to_s + return '' if nil? || empty? + + out_str = String.new + out_str << "\n#{line_separator('-')}" + out_str << "\n | Base | Code | Rate (%) | Amount |" + out_str << "\n#{line_separator('=')}" + each do |entry| + out_str << "\n #{entry.to_table_line}\n#{line_separator('-')}" + end + out_str + end + end + end + end + end +end diff --git a/lib/mindee/parsing/universal.rb b/lib/mindee/v1/parsing/universal.rb similarity index 100% rename from lib/mindee/parsing/universal.rb rename to lib/mindee/v1/parsing/universal.rb diff --git a/lib/mindee/v1/parsing/universal/universal_list_field.rb b/lib/mindee/v1/parsing/universal/universal_list_field.rb new file mode 100644 index 000000000..da735839f --- /dev/null +++ b/lib/mindee/v1/parsing/universal/universal_list_field.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +require_relative 'universal_object_field' + +module Mindee + module V1 + module Parsing + module Universal + # A list of values or objects, used in universal APIs. + class UniversalListField + include Mindee::V1::Parsing::Standard + include Mindee::V1::Parsing::Universal + + # ID of the page (as given by the API). + # @return [Integer] + attr_reader :page_id + + # List of word values + # @return [Array] + attr_reader :values + + # ID of the page the object was found on. + # List of word values. + + def initialize(raw_prediction, page_id = nil) + @values = [] # : Array[UniversalObjectField | Parsing::Standard::StringField] + + raw_prediction.each do |value| + page_id = value['page_id'] if value.key?('page_id') && !value['page_id'].nil? + + if Universal.universal_object?(value) + @values.push(Mindee::V1::Parsing::Universal::UniversalObjectField.new(value, page_id)) + else + value_str = value.dup + value_str['value'] = value_str['value'].to_s if value_str.key?('value') && !value_str['value'].nil? + @values.push(Mindee::V1::Parsing::Standard::StringField.new(value_str, page_id)) + end + end + end + + # Return an Array of the contents of all values. + # @return [Array] + def contents_list + @values.map(&:to_s) + end + + # Return a string representation of all values. + def contents_string(separator = ' ') + @values.join(separator) + end + + # String representation + def to_s + contents_string + end + end + end + end + end +end diff --git a/lib/mindee/v1/parsing/universal/universal_object_field.rb b/lib/mindee/v1/parsing/universal/universal_object_field.rb new file mode 100644 index 000000000..4cc419600 --- /dev/null +++ b/lib/mindee/v1/parsing/universal/universal_object_field.rb @@ -0,0 +1,123 @@ +# frozen_string_literal: true + +require_relative '../common' + +module Mindee + module V1 + module Parsing + # Universal fields and functions. + module Universal + # A JSON-like object, with miscellaneous values. + class UniversalObjectField + # ID of the page (as given by the API). + # @return [Integer] + attr_reader :page_id + # The confidence score, value will be between 0.0 and 1.0 + # @return [Float] + attr_reader :confidence + # Value as String + # @return [String] + attr_reader :raw_value + # All values + # @return [Hash] + attr_reader :all_values + + # ID of the page the object was found on. + # Confidence with which the value was assessed. + # Raw unprocessed value, as it was sent by the server. + + def initialize(raw_prediction, page_id = nil) + @all_values = {} # : Hash[String | Symbol, untyped] + item_page_id = nil + raw_prediction.each do |name, value| + case name + when 'page_id' + item_page_id = value + when 'polygon', 'rectangle', 'quadrangle', 'bounding_box' + handle_position_field(name, value, item_page_id) + when 'confidence' + @confidence = value + when 'raw_value' + @raw_value = value + else + handle_default_field(name, value) + end + @page_id = page_id || item_page_id + end + end + + # String representation that takes into account the level of indentation. + def str_level(level = 0) + indent = " #{' ' * level}" + out_str = '' + @all_values.each do |attr, value| + str_value = value.nil? ? '' : value.to_s + out_str += "\n#{indent}:#{attr}: #{str_value}".rstrip + end + "\n#{indent}#{out_str.strip}" + end + + # Necessary overload of the method_missing method to allow for direct access to dynamic attributes without + # changing the user usage too much. + # Returns the corresponding attribute when asked. + # + # Otherwise, raises a NoMethodError. + # + # @param method_name [Symbol] The name of the method being called. + # @param _args [Array] Arguments passed to the method. + # @return [Object] The value associated with the method name in @all_values. + def method_missing(method_name, *_args) + super unless @all_values.key?(method_name.to_s) + @all_values[method_name.to_s] + end + + # Necessary overload of the respond_to_missing? method to allow for direct access to dynamic attributes + # without changing DX too much. + # Returns true if the method name exists as a key in @all_values, + # indicating that the object can respond to the method. + # Otherwise, calls super to fallback to the default behavior. + # + # @param method_name [Symbol] The name of the method being checked. + # @param include_private [bool] Whether to include private methods in the check. + # @return [bool] `true` if the method can be responded to, false otherwise. + def respond_to_missing?(method_name, include_private = false) + @all_values.key?(method_name.to_s) || super + end + + # String representation + def to_s + str_level + end + + private + + def handle_position_field(name, value, item_page_id) + @all_values[name.to_s] = + Mindee::V1::Parsing::Standard::PositionField.new( + { name.to_s => value }, item_page_id + ) + end + + def handle_default_field(name, value) + @all_values[name] = value&.to_s + end + end + + def self.universal_object?(str_dict) + common_keys = [ + 'value', + 'polygon', + 'rectangle', + 'page_id', + 'confidence', + 'quadrangle', + 'values', + 'raw_value', + ] + str_dict.each_key { |key| return true unless common_keys.include?(key.to_s) } + false + end + end + end + end +end diff --git a/lib/mindee/product.rb b/lib/mindee/v1/product.rb similarity index 55% rename from lib/mindee/product.rb rename to lib/mindee/v1/product.rb index 61cce8af2..1758b29cd 100644 --- a/lib/mindee/product.rb +++ b/lib/mindee/v1/product.rb @@ -1,31 +1,18 @@ # frozen_string_literal: true require_relative 'product/barcode_reader/barcode_reader_v1' -require_relative 'product/bill_of_lading/bill_of_lading_v1' -require_relative 'product/business_card/business_card_v1' require_relative 'product/cropper/cropper_v1' -require_relative 'product/delivery_note/delivery_note_v1' -require_relative 'product/driver_license/driver_license_v1' require_relative 'product/financial_document/financial_document_v1' require_relative 'product/fr/bank_account_details/bank_account_details_v1' require_relative 'product/fr/bank_account_details/bank_account_details_v2' require_relative 'product/fr/bank_statement/bank_statement_v2' -require_relative 'product/fr/carte_grise/carte_grise_v1' -require_relative 'product/fr/energy_bill/energy_bill_v1' -require_relative 'product/fr/health_card/health_card_v1' require_relative 'product/fr/id_card/id_card_v1' require_relative 'product/fr/id_card/id_card_v2' -require_relative 'product/fr/payslip/payslip_v3' -require_relative 'product/ind/indian_passport/indian_passport_v1' require_relative 'product/international_id/international_id_v2' require_relative 'product/invoice/invoice_v4' require_relative 'product/invoice_splitter/invoice_splitter_v1' require_relative 'product/multi_receipts_detector/multi_receipts_detector_v1' -require_relative 'product/nutrition_facts_label/nutrition_facts_label_v1' require_relative 'product/passport/passport_v1' require_relative 'product/receipt/receipt_v5' require_relative 'product/resume/resume_v1' require_relative 'product/universal/universal' -require_relative 'product/us/bank_check/bank_check_v1' -require_relative 'product/us/healthcare_card/healthcare_card_v1' -require_relative 'product/us/us_mail/us_mail_v3' diff --git a/lib/mindee/product/.rubocop.yml b/lib/mindee/v1/product/.rubocop.yml similarity index 84% rename from lib/mindee/product/.rubocop.yml rename to lib/mindee/v1/product/.rubocop.yml index 8b0217de0..8aefc2116 100644 --- a/lib/mindee/product/.rubocop.yml +++ b/lib/mindee/v1/product/.rubocop.yml @@ -1,4 +1,4 @@ -inherit_from: ../../../.rubocop.yml +inherit_from: ../../../../.rubocop.yml Metrics/AbcSize: Enabled: false @@ -10,4 +10,3 @@ Metrics/PerceivedComplexity: Enabled: false Metrics/MethodLength: Enabled: false - diff --git a/lib/mindee/product/fr/id_card/id_card_v1.rb b/lib/mindee/v1/product/barcode_reader/barcode_reader_v1.rb similarity index 63% rename from lib/mindee/product/fr/id_card/id_card_v1.rb rename to lib/mindee/v1/product/barcode_reader/barcode_reader_v1.rb index 63cb3bdc0..b4ee0580d 100644 --- a/lib/mindee/product/fr/id_card/id_card_v1.rb +++ b/lib/mindee/v1/product/barcode_reader/barcode_reader_v1.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'id_card_v1_document' -require_relative 'id_card_v1_page' +require_relative '../../parsing' +require_relative 'barcode_reader_v1_document' +require_relative 'barcode_reader_v1_page' module Mindee - module Product - module FR - # Carte Nationale d'Identité module. - module IdCard - # Carte Nationale d'Identité API version 1 inference prediction. - class IdCardV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'idcard_fr' + module V1 + module Product + # Barcode Reader module. + module BarcodeReader + # Barcode Reader API version 1 inference prediction. + class BarcodeReaderV1 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'barcode_reader' @endpoint_version = '1' @has_async = false @has_sync = true @@ -19,10 +19,10 @@ class IdCardV1 < Mindee::Parsing::Common::Inference # @param prediction [Hash] def initialize(prediction) super - @prediction = IdCardV1Document.new(prediction['prediction'], nil) + @prediction = BarcodeReaderV1Document.new(prediction['prediction'], nil) @pages = [] prediction['pages'].each do |page| - @pages.push(IdCardV1Page.new(page)) + @pages.push(BarcodeReaderV1Page.new(page)) end end diff --git a/lib/mindee/v1/product/barcode_reader/barcode_reader_v1_document.rb b/lib/mindee/v1/product/barcode_reader/barcode_reader_v1_document.rb new file mode 100644 index 000000000..c6a6cffbf --- /dev/null +++ b/lib/mindee/v1/product/barcode_reader/barcode_reader_v1_document.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module BarcodeReader + # Barcode Reader API version 1.0 document data. + class BarcodeReaderV1Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # List of decoded 1D barcodes. + # @return [Array] + attr_reader :codes_1d + # List of decoded 2D barcodes. + # @return [Array] + attr_reader :codes_2d + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @codes_1d = [] # : Array[Parsing::Standard::StringField] + prediction['codes_1d'].each do |item| + @codes_1d.push(Parsing::Standard::StringField.new(item, page_id)) + end + @codes_2d = [] # : Array[Parsing::Standard::StringField] + prediction['codes_2d'].each do |item| + @codes_2d.push(Parsing::Standard::StringField.new(item, page_id)) + end + end + + # @return [String] + def to_s + codes_1d = @codes_1d.join("\n #{' ' * 13}") + codes_2d = @codes_2d.join("\n #{' ' * 13}") + out_str = String.new + out_str << "\n:Barcodes 1D: #{codes_1d}".rstrip + out_str << "\n:Barcodes 2D: #{codes_2d}".rstrip + out_str[1..].to_s + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/bank_statement/bank_statement_v2_page.rb b/lib/mindee/v1/product/barcode_reader/barcode_reader_v1_page.rb similarity index 60% rename from lib/mindee/product/fr/bank_statement/bank_statement_v2_page.rb rename to lib/mindee/v1/product/barcode_reader/barcode_reader_v1_page.rb index d0e3976c7..05e003b4e 100644 --- a/lib/mindee/product/fr/bank_statement/bank_statement_v2_page.rb +++ b/lib/mindee/v1/product/barcode_reader/barcode_reader_v1_page.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'bank_statement_v2_document' +require_relative '../../parsing' +require_relative 'barcode_reader_v1_document' module Mindee - module Product - module FR - module BankStatement - # Bank Statement API version 2.0 page data. - class BankStatementV2Page < Mindee::Parsing::Common::Page + module V1 + module Product + module BarcodeReader + # Barcode Reader API version 1.0 page data. + class BarcodeReaderV1Page < Mindee::V1::Parsing::Common::Page # @param prediction [Hash] def initialize(prediction) super @prediction = if prediction['prediction'].empty? nil else - BankStatementV2PagePrediction.new( + BarcodeReaderV1PagePrediction.new( prediction['prediction'], prediction['id'] ) @@ -23,8 +23,8 @@ def initialize(prediction) end end - # Bank Statement V2 page prediction. - class BankStatementV2PagePrediction < BankStatementV2Document + # Barcode Reader V1 page prediction. + class BarcodeReaderV1PagePrediction < BarcodeReaderV1Document # @return [String] def to_s out_str = String.new diff --git a/lib/mindee/product/us/bank_check/bank_check_v1.rb b/lib/mindee/v1/product/cropper/cropper_v1.rb similarity index 65% rename from lib/mindee/product/us/bank_check/bank_check_v1.rb rename to lib/mindee/v1/product/cropper/cropper_v1.rb index 8dd0008f0..50a48dd5a 100644 --- a/lib/mindee/product/us/bank_check/bank_check_v1.rb +++ b/lib/mindee/v1/product/cropper/cropper_v1.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'bank_check_v1_document' -require_relative 'bank_check_v1_page' +require_relative '../../parsing' +require_relative 'cropper_v1_document' +require_relative 'cropper_v1_page' module Mindee - module Product - module US - # Bank Check module. - module BankCheck - # Bank Check API version 1 inference prediction. - class BankCheckV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'bank_check' + module V1 + module Product + # Cropper module. + module Cropper + # Cropper API version 1 inference prediction. + class CropperV1 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'cropper' @endpoint_version = '1' @has_async = false @has_sync = true @@ -19,10 +19,10 @@ class BankCheckV1 < Mindee::Parsing::Common::Inference # @param prediction [Hash] def initialize(prediction) super - @prediction = BankCheckV1Document.new(prediction['prediction'], nil) + @prediction = CropperV1Document.new(prediction['prediction'], nil) @pages = [] prediction['pages'].each do |page| - @pages.push(BankCheckV1Page.new(page)) + @pages.push(CropperV1Page.new(page)) end end diff --git a/lib/mindee/v1/product/cropper/cropper_v1_document.rb b/lib/mindee/v1/product/cropper/cropper_v1_document.rb new file mode 100644 index 000000000..aad2900db --- /dev/null +++ b/lib/mindee/v1/product/cropper/cropper_v1_document.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module Cropper + # Cropper API version 1.1 document data. + class CropperV1Document < Mindee::V1::Parsing::Common::Prediction + end + end + end + end +end diff --git a/lib/mindee/v1/product/cropper/cropper_v1_page.rb b/lib/mindee/v1/product/cropper/cropper_v1_page.rb new file mode 100644 index 000000000..841e90c7b --- /dev/null +++ b/lib/mindee/v1/product/cropper/cropper_v1_page.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'cropper_v1_document' + +module Mindee + module V1 + module Product + module Cropper + # Cropper API version 1.1 page data. + class CropperV1Page < Mindee::V1::Parsing::Common::Page + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = if prediction['prediction'].empty? + nil + else + CropperV1PagePrediction.new( + prediction['prediction'], + prediction['id'] + ) + end + end + end + + # Cropper V1 page prediction. + class CropperV1PagePrediction < CropperV1Document + include Mindee::V1::Parsing::Standard + + # List of documents found in the image. + # @return [Array] + attr_reader :cropping + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + @cropping = [] + prediction['cropping'].each do |item| + @cropping.push(Parsing::Standard::PositionField.new(item, page_id)) + end + super + end + + # @return [String] + def to_s + cropping = @cropping.join("\n #{' ' * 18}") + out_str = String.new + out_str << "\n:Document Cropper: #{cropping}".rstrip + out_str + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1.rb b/lib/mindee/v1/product/financial_document/financial_document_v1.rb similarity index 60% rename from lib/mindee/product/fr/energy_bill/energy_bill_v1.rb rename to lib/mindee/v1/product/financial_document/financial_document_v1.rb index 6f7ec95fb..29e765c79 100644 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1.rb +++ b/lib/mindee/v1/product/financial_document/financial_document_v1.rb @@ -1,28 +1,28 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'energy_bill_v1_document' -require_relative 'energy_bill_v1_page' +require_relative '../../parsing' +require_relative 'financial_document_v1_document' +require_relative 'financial_document_v1_page' module Mindee - module Product - module FR - # Energy Bill module. - module EnergyBill - # Energy Bill API version 1 inference prediction. - class EnergyBillV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'energy_bill_fra' + module V1 + module Product + # Financial Document module. + module FinancialDocument + # Financial Document API version 1 inference prediction. + class FinancialDocumentV1 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'financial_document' @endpoint_version = '1' @has_async = true - @has_sync = false + @has_sync = true # @param prediction [Hash] def initialize(prediction) super - @prediction = EnergyBillV1Document.new(prediction['prediction'], nil) + @prediction = FinancialDocumentV1Document.new(prediction['prediction'], nil) @pages = [] prediction['pages'].each do |page| - @pages.push(EnergyBillV1Page.new(page)) + @pages.push(FinancialDocumentV1Page.new(page)) end end diff --git a/lib/mindee/v1/product/financial_document/financial_document_v1_document.rb b/lib/mindee/v1/product/financial_document/financial_document_v1_document.rb new file mode 100644 index 000000000..2a879f465 --- /dev/null +++ b/lib/mindee/v1/product/financial_document/financial_document_v1_document.rb @@ -0,0 +1,329 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'financial_document_v1_line_items' + +module Mindee + module V1 + module Product + module FinancialDocument + # Financial Document API version 1.14 document data. + class FinancialDocumentV1Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # The customer's address used for billing. + # @return [Mindee::V1::Parsing::Standard::AddressField] + attr_reader :billing_address + # The purchase category. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :category + # The address of the customer. + # @return [Mindee::V1::Parsing::Standard::AddressField] + attr_reader :customer_address + # List of company registration numbers associated to the customer. + # @return [Array] + attr_reader :customer_company_registrations + # The customer account number or identifier from the supplier. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :customer_id + # The name of the customer. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :customer_name + # The date the purchase was made. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :date + # The document number or identifier (invoice number or receipt number). + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :document_number + # The type of the document: INVOICE or CREDIT NOTE if it is an invoice, CREDIT CARD RECEIPT or EXPENSE + # RECEIPT if it is a receipt. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :document_type + # Document type extended. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :document_type_extended + # The date on which the payment is due. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :due_date + # The invoice number or identifier only if document is an invoice. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :invoice_number + # List of line item present on the document. + # @return [Mindee::V1::Product::FinancialDocument::FinancialDocumentV1LineItems] + attr_reader :line_items + # The locale of the document. + # @return [Mindee::V1::Parsing::Standard::LocaleField] + attr_reader :locale + # The date on which the payment is due / fullfilled. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :payment_date + # The purchase order number, only if the document is an invoice. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :po_number + # The receipt number or identifier only if document is a receipt. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :receipt_number + # List of Reference numbers, including PO number, only if the document is an invoice. + # @return [Array] + attr_reader :reference_numbers + # The customer's address used for shipping. + # @return [Mindee::V1::Parsing::Standard::AddressField] + attr_reader :shipping_address + # The purchase subcategory for transport, food and shooping. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :subcategory + # The address of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::AddressField] + attr_reader :supplier_address + # List of company registration numbers associated to the supplier. + # @return [Array] + attr_reader :supplier_company_registrations + # The email of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_email + # The name of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_name + # List of payment details associated to the supplier (only for invoices). + # @return [Array] + attr_reader :supplier_payment_details + # The phone number of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_phone_number + # The website URL of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_website + # List of all taxes on the document. + # @return [Mindee::V1::Parsing::Standard::Taxes] + attr_reader :taxes + # The time the purchase was made (only for receipts). + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :time + # The total amount of tip and gratuity + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :tip + # The total amount paid: includes taxes, tips, fees, and other charges. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_amount + # The net amount paid: does not include taxes, fees, and discounts. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_net + # The sum of all taxes present on the document. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_tax + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @billing_address = Parsing::Standard::AddressField.new( + prediction['billing_address'], + page_id + ) + @category = Parsing::Standard::ClassificationField.new( + prediction['category'], + page_id + ) + @customer_address = Parsing::Standard::AddressField.new( + prediction['customer_address'], + page_id + ) + @customer_company_registrations = [] # : Array[Parsing::Standard::CompanyRegistrationField] + prediction['customer_company_registrations'].each do |item| + @customer_company_registrations.push(Parsing::Standard::CompanyRegistrationField.new(item, page_id)) + end + @customer_id = Parsing::Standard::StringField.new( + prediction['customer_id'], + page_id + ) + @customer_name = Parsing::Standard::StringField.new( + prediction['customer_name'], + page_id + ) + @date = Parsing::Standard::DateField.new(prediction['date'], page_id) + @document_number = Parsing::Standard::StringField.new( + prediction['document_number'], + page_id + ) + @document_type = Parsing::Standard::ClassificationField.new( + prediction['document_type'], + page_id + ) + @document_type_extended = Parsing::Standard::ClassificationField.new( + prediction['document_type_extended'], + page_id + ) + @due_date = Parsing::Standard::DateField.new( + prediction['due_date'], + page_id + ) + @invoice_number = Parsing::Standard::StringField.new( + prediction['invoice_number'], + page_id + ) + @line_items = Product::FinancialDocument::FinancialDocumentV1LineItems.new( + prediction['line_items'], page_id + ) + @locale = Parsing::Standard::LocaleField.new( + prediction['locale'], + page_id + ) + @payment_date = Parsing::Standard::DateField.new( + prediction['payment_date'], + page_id + ) + @po_number = Parsing::Standard::StringField.new( + prediction['po_number'], + page_id + ) + @receipt_number = Parsing::Standard::StringField.new( + prediction['receipt_number'], + page_id + ) + @reference_numbers = [] # : Array[Parsing::Standard::StringField] + prediction['reference_numbers'].each do |item| + @reference_numbers.push(Parsing::Standard::StringField.new(item, page_id)) + end + @shipping_address = Parsing::Standard::AddressField.new( + prediction['shipping_address'], + page_id + ) + @subcategory = Parsing::Standard::ClassificationField.new( + prediction['subcategory'], + page_id + ) + @supplier_address = Parsing::Standard::AddressField.new( + prediction['supplier_address'], + page_id + ) + @supplier_company_registrations = [] # : Array[Parsing::Standard::CompanyRegistrationField] + prediction['supplier_company_registrations'].each do |item| + @supplier_company_registrations.push(Parsing::Standard::CompanyRegistrationField.new(item, page_id)) + end + @supplier_email = Parsing::Standard::StringField.new( + prediction['supplier_email'], + page_id + ) + @supplier_name = Parsing::Standard::StringField.new( + prediction['supplier_name'], + page_id + ) + @supplier_payment_details = [] # : Array[Parsing::Standard::PaymentDetailsField] + prediction['supplier_payment_details'].each do |item| + @supplier_payment_details.push(Parsing::Standard::PaymentDetailsField.new(item, page_id)) + end + @supplier_phone_number = Parsing::Standard::StringField.new( + prediction['supplier_phone_number'], + page_id + ) + @supplier_website = Parsing::Standard::StringField.new( + prediction['supplier_website'], + page_id + ) + @taxes = Parsing::Standard::Taxes.new(prediction['taxes'], page_id) + @time = Parsing::Standard::StringField.new(prediction['time'], page_id) + @tip = Parsing::Standard::AmountField.new(prediction['tip'], page_id) + @total_amount = Parsing::Standard::AmountField.new( + prediction['total_amount'], + page_id + ) + @total_net = Parsing::Standard::AmountField.new( + prediction['total_net'], + page_id + ) + @total_tax = Parsing::Standard::AmountField.new( + prediction['total_tax'], + page_id + ) + end + + # @return [String] + def to_s + reference_numbers = @reference_numbers.join("\n #{' ' * 19}") + supplier_payment_details = @supplier_payment_details.join("\n #{' ' * 26}") + supplier_company_registrations = @supplier_company_registrations.join("\n #{' ' * 32}") + customer_company_registrations = @customer_company_registrations.join("\n #{' ' * 32}") + line_items = line_items_to_s + out_str = String.new + out_str << "\n:Locale: #{@locale}".rstrip + out_str << "\n:Invoice Number: #{@invoice_number}".rstrip + out_str << "\n:Purchase Order Number: #{@po_number}".rstrip + out_str << "\n:Receipt Number: #{@receipt_number}".rstrip + out_str << "\n:Document Number: #{@document_number}".rstrip + out_str << "\n:Reference Numbers: #{reference_numbers}".rstrip + out_str << "\n:Purchase Date: #{@date}".rstrip + out_str << "\n:Due Date: #{@due_date}".rstrip + out_str << "\n:Payment Date: #{@payment_date}".rstrip + out_str << "\n:Total Net: #{@total_net}".rstrip + out_str << "\n:Total Amount: #{@total_amount}".rstrip + out_str << "\n:Taxes:#{@taxes}".rstrip + out_str << "\n:Supplier Payment Details: #{supplier_payment_details}".rstrip + out_str << "\n:Supplier Name: #{@supplier_name}".rstrip + out_str << "\n:Supplier Company Registrations: #{supplier_company_registrations}".rstrip + out_str << "\n:Supplier Address: #{@supplier_address}".rstrip + out_str << "\n:Supplier Phone Number: #{@supplier_phone_number}".rstrip + out_str << "\n:Customer Name: #{@customer_name}".rstrip + out_str << "\n:Supplier Website: #{@supplier_website}".rstrip + out_str << "\n:Supplier Email: #{@supplier_email}".rstrip + out_str << "\n:Customer Company Registrations: #{customer_company_registrations}".rstrip + out_str << "\n:Customer Address: #{@customer_address}".rstrip + out_str << "\n:Customer ID: #{@customer_id}".rstrip + out_str << "\n:Shipping Address: #{@shipping_address}".rstrip + out_str << "\n:Billing Address: #{@billing_address}".rstrip + out_str << "\n:Document Type: #{@document_type}".rstrip + out_str << "\n:Document Type Extended: #{@document_type_extended}".rstrip + out_str << "\n:Purchase Subcategory: #{@subcategory}".rstrip + out_str << "\n:Purchase Category: #{@category}".rstrip + out_str << "\n:Total Tax: #{@total_tax}".rstrip + out_str << "\n:Tip and Gratuity: #{@tip}".rstrip + out_str << "\n:Purchase Time: #{@time}".rstrip + out_str << "\n:Line Items:" + out_str << line_items + out_str[1..].to_s + end + + private + + # @param char [String] + # @return [String] + def line_items_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 38}" + out_str << "+#{char * 14}" + out_str << "+#{char * 10}" + out_str << "+#{char * 12}" + out_str << "+#{char * 14}" + out_str << "+#{char * 14}" + out_str << "+#{char * 17}" + out_str << "+#{char * 12}" + out_str << '+' + out_str + end + + # @return [String] + def line_items_to_s + return '' if @line_items.empty? + + line_items = @line_items.map(&:to_table_line).join("\n#{line_items_separator('-')}\n ") + out_str = String.new + out_str << "\n#{line_items_separator('-')}" + out_str << "\n |" + out_str << ' Description |' + out_str << ' Product code |' + out_str << ' Quantity |' + out_str << ' Tax Amount |' + out_str << ' Tax Rate (%) |' + out_str << ' Total Amount |' + out_str << ' Unit of measure |' + out_str << ' Unit Price |' + out_str << "\n#{line_items_separator('=')}" + out_str << "\n #{line_items}" + out_str << "\n#{line_items_separator('-')}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/financial_document/financial_document_v1_line_item.rb b/lib/mindee/v1/product/financial_document/financial_document_v1_line_item.rb new file mode 100644 index 000000000..d9989b4e7 --- /dev/null +++ b/lib/mindee/v1/product/financial_document/financial_document_v1_line_item.rb @@ -0,0 +1,124 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module FinancialDocument + # List of line item present on the document. + class FinancialDocumentV1LineItem < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # The item description. + # @return [String] + attr_reader :description + # The product code referring to the item. + # @return [String] + attr_reader :product_code + # The item quantity + # @return [Float] + attr_reader :quantity + # The item tax amount. + # @return [Float] + attr_reader :tax_amount + # The item tax rate in percentage. + # @return [Float] + attr_reader :tax_rate + # The item total amount. + # @return [Float] + attr_reader :total_amount + # The item unit of measure. + # @return [String] + attr_reader :unit_measure + # The item unit price. + # @return [Float] + attr_reader :unit_price + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @description = prediction['description'] + @product_code = prediction['product_code'] + @quantity = prediction['quantity'] + @tax_amount = prediction['tax_amount'] + @tax_rate = prediction['tax_rate'] + @total_amount = prediction['total_amount'] + @unit_measure = prediction['unit_measure'] + @unit_price = prediction['unit_price'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:description] = format_for_display(@description) + printable[:product_code] = format_for_display(@product_code) + printable[:quantity] = + @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) + printable[:tax_amount] = + @tax_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_amount) + printable[:tax_rate] = + @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) + printable[:total_amount] = + @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) + printable[:unit_measure] = format_for_display(@unit_measure) + printable[:unit_price] = + @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) + printable + end + + # @return [Hash] + def table_printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:description] = format_for_display(@description, 36) + printable[:product_code] = format_for_display(@product_code, nil) + printable[:quantity] = + @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) + printable[:tax_amount] = + @tax_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_amount) + printable[:tax_rate] = + @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) + printable[:total_amount] = + @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) + printable[:unit_measure] = format_for_display(@unit_measure, nil) + printable[:unit_price] = + @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) + printable + end + + # @return [String] + def to_table_line + printable = table_printable_values + out_str = String.new + out_str << format('| %- 37s', printable[:description]) + out_str << format('| %- 13s', printable[:product_code]) + out_str << format('| %- 9s', printable[:quantity]) + out_str << format('| %- 11s', printable[:tax_amount]) + out_str << format('| %- 13s', printable[:tax_rate]) + out_str << format('| %- 13s', printable[:total_amount]) + out_str << format('| %- 16s', printable[:unit_measure]) + out_str << format('| %- 11s', printable[:unit_price]) + out_str << '|' + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Description: #{printable[:description]}" + out_str << "\n :Product code: #{printable[:product_code]}" + out_str << "\n :Quantity: #{printable[:quantity]}" + out_str << "\n :Tax Amount: #{printable[:tax_amount]}" + out_str << "\n :Tax Rate (%): #{printable[:tax_rate]}" + out_str << "\n :Total Amount: #{printable[:total_amount]}" + out_str << "\n :Unit of measure: #{printable[:unit_measure]}" + out_str << "\n :Unit Price: #{printable[:unit_price]}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_subscriptions.rb b/lib/mindee/v1/product/financial_document/financial_document_v1_line_items.rb similarity index 62% rename from lib/mindee/product/fr/energy_bill/energy_bill_v1_subscriptions.rb rename to lib/mindee/v1/product/financial_document/financial_document_v1_line_items.rb index 0de21ea63..3f2ce8f84 100644 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_subscriptions.rb +++ b/lib/mindee/v1/product/financial_document/financial_document_v1_line_items.rb @@ -1,27 +1,22 @@ # frozen_string_literal: true -require_relative 'energy_bill_v1_energy_supplier' -require_relative 'energy_bill_v1_energy_consumer' -require_relative 'energy_bill_v1_subscription' -require_relative 'energy_bill_v1_energy_usage' -require_relative 'energy_bill_v1_taxes_and_contribution' -require_relative 'energy_bill_v1_meter_detail' +require_relative 'financial_document_v1_line_item' module Mindee - module Product - module FR - module EnergyBill - # The subscription details fee for the energy service. - class EnergyBillV1Subscriptions < Array + module V1 + module Product + module FinancialDocument + # List of line item present on the document. + class FinancialDocumentV1LineItems < Array # Entries. - # @return [Array] + # @return [Array] attr_reader :entries # @param prediction [Array] # @param page_id [Integer, nil] def initialize(prediction, page_id) entries = prediction.map do |entry| - EnergyBill::EnergyBillV1Subscription.new(entry, page_id) + FinancialDocument::FinancialDocumentV1LineItem.new(entry, page_id) end super(entries) end @@ -32,10 +27,12 @@ def initialize(prediction, page_id) def self.line_items_separator(char) out_str = String.new out_str << "+#{char * 38}" - out_str << "+#{char * 12}" - out_str << "+#{char * 12}" + out_str << "+#{char * 14}" out_str << "+#{char * 10}" - out_str << "+#{char * 11}" + out_str << "+#{char * 12}" + out_str << "+#{char * 14}" + out_str << "+#{char * 14}" + out_str << "+#{char * 17}" out_str << "+#{char * 12}" out_str end @@ -50,10 +47,12 @@ def to_s out_str = String.new out_str << "\n#{self.class.line_items_separator('-')}\n " out_str << ' | Description ' - out_str << ' | End Date ' - out_str << ' | Start Date' - out_str << ' | Tax Rate' - out_str << ' | Total ' + out_str << ' | Product code' + out_str << ' | Quantity' + out_str << ' | Tax Amount' + out_str << ' | Tax Rate (%)' + out_str << ' | Total Amount' + out_str << ' | Unit of measure' out_str << ' | Unit Price' out_str << " |\n#{self.class.line_items_separator('=')}" out_str + lines diff --git a/lib/mindee/v1/product/financial_document/financial_document_v1_page.rb b/lib/mindee/v1/product/financial_document/financial_document_v1_page.rb new file mode 100644 index 000000000..d34c7d87c --- /dev/null +++ b/lib/mindee/v1/product/financial_document/financial_document_v1_page.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'financial_document_v1_document' + +module Mindee + module V1 + module Product + module FinancialDocument + # Financial Document API version 1.14 page data. + class FinancialDocumentV1Page < Mindee::V1::Parsing::Common::Page + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = if prediction['prediction'].empty? + nil + else + FinancialDocumentV1PagePrediction.new( + prediction['prediction'], + prediction['id'] + ) + end + end + end + + # Financial Document V1 page prediction. + class FinancialDocumentV1PagePrediction < FinancialDocumentV1Document + # @return [String] + def to_s + out_str = String.new + out_str << "\n#{super}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v1.rb b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v1.rb new file mode 100644 index 000000000..0f05a1372 --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v1.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'bank_account_details_v1_document' +require_relative 'bank_account_details_v1_page' + +module Mindee + module V1 + module Product + module FR + # Bank Account Details module. + module BankAccountDetails + # Bank Account Details API version 1 inference prediction. + class BankAccountDetailsV1 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'bank_account_details' + @endpoint_version = '1' + @has_async = false + @has_sync = true + + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = BankAccountDetailsV1Document.new(prediction['prediction'], nil) + @pages = [] + prediction['pages'].each do |page| + @pages.push(BankAccountDetailsV1Page.new(page)) + end + end + + class << self + # Name of the endpoint for this product. + # @return [String] + attr_reader :endpoint_name + # Version for this product. + # @return [String] + attr_reader :endpoint_version + # Whether this product has access to an asynchronous endpoint. + # @return [bool] + attr_reader :has_async + # Whether this product has access to synchronous endpoint. + # @return [bool] + attr_reader :has_sync + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_document.rb b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_document.rb new file mode 100644 index 000000000..b58fa1780 --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_document.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' + +module Mindee + module V1 + module Product + module FR + module BankAccountDetails + # Bank Account Details API version 1.0 document data. + class BankAccountDetailsV1Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # The name of the account holder as seen on the document. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :account_holder_name + # The International Bank Account Number (IBAN). + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :iban + # The bank's SWIFT Business Identifier Code (BIC). + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :swift + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @account_holder_name = Parsing::Standard::StringField.new( + prediction['account_holder_name'], + page_id + ) + @iban = Parsing::Standard::StringField.new(prediction['iban'], page_id) + @swift = Parsing::Standard::StringField.new(prediction['swift'], page_id) + end + + # @return [String] + def to_s + out_str = String.new + out_str << "\n:IBAN: #{@iban}".rstrip + out_str << "\n:Account Holder's Name: #{@account_holder_name}".rstrip + out_str << "\n:SWIFT Code: #{@swift}".rstrip + out_str[1..].to_s + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_page.rb b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_page.rb new file mode 100644 index 000000000..6dfd7ca0d --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_page.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'bank_account_details_v1_document' + +module Mindee + module V1 + module Product + module FR + module BankAccountDetails + # Bank Account Details API version 1.0 page data. + class BankAccountDetailsV1Page < Mindee::V1::Parsing::Common::Page + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = if prediction['prediction'].empty? + nil + else + BankAccountDetailsV1PagePrediction.new( + prediction['prediction'], + prediction['id'] + ) + end + end + end + + # Bank Account Details V1 page prediction. + class BankAccountDetailsV1PagePrediction < BankAccountDetailsV1Document + # @return [String] + def to_s + out_str = String.new + out_str << "\n#{super}" + out_str + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2.rb b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2.rb new file mode 100644 index 000000000..0411f9b0b --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'bank_account_details_v2_document' +require_relative 'bank_account_details_v2_page' + +module Mindee + module V1 + module Product + module FR + # Bank Account Details module. + module BankAccountDetails + # Bank Account Details API version 2 inference prediction. + class BankAccountDetailsV2 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'bank_account_details' + @endpoint_version = '2' + @has_async = false + @has_sync = true + + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = BankAccountDetailsV2Document.new(prediction['prediction'], nil) + @pages = [] + prediction['pages'].each do |page| + @pages.push(BankAccountDetailsV2Page.new(page)) + end + end + + class << self + # Name of the endpoint for this product. + # @return [String] + attr_reader :endpoint_name + # Version for this product. + # @return [String] + attr_reader :endpoint_version + # Whether this product has access to an asynchronous endpoint. + # @return [bool] + attr_reader :has_async + # Whether this product has access to synchronous endpoint. + # @return [bool] + attr_reader :has_sync + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_bban.rb b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_bban.rb new file mode 100644 index 000000000..2c1a2dcaf --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_bban.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' + +module Mindee + module V1 + module Product + module FR + module BankAccountDetails + # Full extraction of BBAN, including: branch code, bank code, account and key. + class BankAccountDetailsV2Bban < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # The BBAN bank code outputted as a string. + # @return [String] + attr_reader :bban_bank_code + # The BBAN branch code outputted as a string. + # @return [String] + attr_reader :bban_branch_code + # The BBAN key outputted as a string. + # @return [String] + attr_reader :bban_key + # The BBAN Account number outputted as a string. + # @return [String] + attr_reader :bban_number + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @bban_bank_code = prediction['bban_bank_code'] + @bban_branch_code = prediction['bban_branch_code'] + @bban_key = prediction['bban_key'] + @bban_number = prediction['bban_number'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:bban_bank_code] = format_for_display(@bban_bank_code) + printable[:bban_branch_code] = format_for_display(@bban_branch_code) + printable[:bban_key] = format_for_display(@bban_key) + printable[:bban_number] = format_for_display(@bban_number) + printable + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Bank Code: #{printable[:bban_bank_code]}" + out_str << "\n :Branch Code: #{printable[:bban_branch_code]}" + out_str << "\n :Key: #{printable[:bban_key]}" + out_str << "\n :Account Number: #{printable[:bban_number]}" + out_str + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_document.rb b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_document.rb new file mode 100644 index 000000000..0861defd4 --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_document.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'bank_account_details_v2_bban' + +module Mindee + module V1 + module Product + module FR + module BankAccountDetails + # Bank Account Details API version 2.0 document data. + class BankAccountDetailsV2Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # Full extraction of the account holders names. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :account_holders_names + # Full extraction of BBAN, including: branch code, bank code, account and key. + # @return [Mindee::V1::Product::FR::BankAccountDetails::BankAccountDetailsV2Bban] + attr_reader :bban + # Full extraction of the IBAN number. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :iban + # Full extraction of the SWIFT code. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :swift_code + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @account_holders_names = Parsing::Standard::StringField.new( + prediction['account_holders_names'], + page_id + ) + @bban = Product::FR::BankAccountDetails::BankAccountDetailsV2Bban.new(prediction['bban'], page_id) + @iban = Parsing::Standard::StringField.new(prediction['iban'], page_id) + @swift_code = Parsing::Standard::StringField.new( + prediction['swift_code'], + page_id + ) + end + + # @return [String] + def to_s + bban = @bban.to_s + out_str = String.new + out_str << "\n:Account Holder's Names: #{@account_holders_names}".rstrip + out_str << "\n:Basic Bank Account Number:" + out_str << bban + out_str << "\n:IBAN: #{@iban}".rstrip + out_str << "\n:SWIFT Code: #{@swift_code}".rstrip + out_str[1..].to_s + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_page.rb b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_page.rb new file mode 100644 index 000000000..ab096cc36 --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_page.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'bank_account_details_v2_document' + +module Mindee + module V1 + module Product + module FR + module BankAccountDetails + # Bank Account Details API version 2.0 page data. + class BankAccountDetailsV2Page < Mindee::V1::Parsing::Common::Page + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = if prediction['prediction'].empty? + nil + else + BankAccountDetailsV2PagePrediction.new( + prediction['prediction'], + prediction['id'] + ) + end + end + end + + # Bank Account Details V2 page prediction. + class BankAccountDetailsV2PagePrediction < BankAccountDetailsV2Document + # @return [String] + def to_s + out_str = String.new + out_str << "\n#{super}" + out_str + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2.rb b/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2.rb new file mode 100644 index 000000000..8448457fc --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'bank_statement_v2_document' +require_relative 'bank_statement_v2_page' + +module Mindee + module V1 + module Product + module FR + # Bank Statement module. + module BankStatement + # Bank Statement API version 2 inference prediction. + class BankStatementV2 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'bank_statement_fr' + @endpoint_version = '2' + @has_async = true + @has_sync = false + + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = BankStatementV2Document.new(prediction['prediction'], nil) + @pages = [] + prediction['pages'].each do |page| + @pages.push(BankStatementV2Page.new(page)) + end + end + + class << self + # Name of the endpoint for this product. + # @return [String] + attr_reader :endpoint_name + # Version for this product. + # @return [String] + attr_reader :endpoint_version + # Whether this product has access to an asynchronous endpoint. + # @return [bool] + attr_reader :has_async + # Whether this product has access to synchronous endpoint. + # @return [bool] + attr_reader :has_sync + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_document.rb b/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_document.rb new file mode 100644 index 000000000..fe27d7162 --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_document.rb @@ -0,0 +1,169 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'bank_statement_v2_transactions' + +module Mindee + module V1 + module Product + module FR + module BankStatement + # Bank Statement API version 2.0 document data. + class BankStatementV2Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # The unique identifier for a customer's account in the bank's system. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :account_number + # The physical location of the bank where the statement was issued. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :bank_address + # The name of the bank that issued the statement. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :bank_name + # The address of the client associated with the bank statement. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :client_address + # The name of the clients who own the bank statement. + # @return [Array] + attr_reader :client_names + # The final amount of money in the account at the end of the statement period. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :closing_balance + # The initial amount of money in an account at the start of the period. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :opening_balance + # The date on which the bank statement was generated. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :statement_date + # The date when the statement period ends. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :statement_end_date + # The date when the bank statement period begins. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :statement_start_date + # The total amount of money deposited into the account. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_credits + # The total amount of money debited from the account. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_debits + # The list of values that represent the financial transactions recorded in a bank statement. + # @return [Mindee::V1::Product::FR::BankStatement::BankStatementV2Transactions] + attr_reader :transactions + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @account_number = Parsing::Standard::StringField.new( + prediction['account_number'], + page_id + ) + @bank_address = Parsing::Standard::StringField.new( + prediction['bank_address'], + page_id + ) + @bank_name = Parsing::Standard::StringField.new( + prediction['bank_name'], + page_id + ) + @client_address = Parsing::Standard::StringField.new( + prediction['client_address'], + page_id + ) + @client_names = [] # : Array[Parsing::Standard::StringField] + prediction['client_names'].each do |item| + @client_names.push(Parsing::Standard::StringField.new(item, page_id)) + end + @closing_balance = Parsing::Standard::AmountField.new( + prediction['closing_balance'], + page_id + ) + @opening_balance = Parsing::Standard::AmountField.new( + prediction['opening_balance'], + page_id + ) + @statement_date = Parsing::Standard::DateField.new( + prediction['statement_date'], + page_id + ) + @statement_end_date = Parsing::Standard::DateField.new( + prediction['statement_end_date'], + page_id + ) + @statement_start_date = Parsing::Standard::DateField.new( + prediction['statement_start_date'], + page_id + ) + @total_credits = Parsing::Standard::AmountField.new( + prediction['total_credits'], + page_id + ) + @total_debits = Parsing::Standard::AmountField.new( + prediction['total_debits'], + page_id + ) + @transactions = Product::FR::BankStatement::BankStatementV2Transactions.new( + prediction['transactions'], page_id + ) + end + + # @return [String] + def to_s + client_names = @client_names.join("\n #{' ' * 14}") + transactions = transactions_to_s + out_str = String.new + out_str << "\n:Account Number: #{@account_number}".rstrip + out_str << "\n:Bank Name: #{@bank_name}".rstrip + out_str << "\n:Bank Address: #{@bank_address}".rstrip + out_str << "\n:Client Names: #{client_names}".rstrip + out_str << "\n:Client Address: #{@client_address}".rstrip + out_str << "\n:Statement Date: #{@statement_date}".rstrip + out_str << "\n:Statement Start Date: #{@statement_start_date}".rstrip + out_str << "\n:Statement End Date: #{@statement_end_date}".rstrip + out_str << "\n:Opening Balance: #{@opening_balance}".rstrip + out_str << "\n:Closing Balance: #{@closing_balance}".rstrip + out_str << "\n:Transactions:" + out_str << transactions + out_str << "\n:Total Debits: #{@total_debits}".rstrip + out_str << "\n:Total Credits: #{@total_credits}".rstrip + out_str[1..].to_s + end + + private + + # @param char [String] + # @return [String] + def transactions_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 12}" + out_str << "+#{char * 12}" + out_str << "+#{char * 38}" + out_str << '+' + out_str + end + + # @return [String] + def transactions_to_s + return '' if @transactions.empty? + + line_items = @transactions.map(&:to_table_line).join("\n#{transactions_separator('-')}\n ") + out_str = String.new + out_str << "\n#{transactions_separator('-')}" + out_str << "\n |" + out_str << ' Amount |' + out_str << ' Date |' + out_str << ' Description |' + out_str << "\n#{transactions_separator('=')}" + out_str << "\n #{line_items}" + out_str << "\n#{transactions_separator('-')}" + out_str + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_page.rb b/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_page.rb new file mode 100644 index 000000000..4e8ccb9cd --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_page.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'bank_statement_v2_document' + +module Mindee + module V1 + module Product + module FR + module BankStatement + # Bank Statement API version 2.0 page data. + class BankStatementV2Page < Mindee::V1::Parsing::Common::Page + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = if prediction['prediction'].empty? + nil + else + BankStatementV2PagePrediction.new( + prediction['prediction'], + prediction['id'] + ) + end + end + end + + # Bank Statement V2 page prediction. + class BankStatementV2PagePrediction < BankStatementV2Document + # @return [String] + def to_s + out_str = String.new + out_str << "\n#{super}" + out_str + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_transaction.rb b/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_transaction.rb new file mode 100644 index 000000000..b131b888b --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_transaction.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' + +module Mindee + module V1 + module Product + module FR + module BankStatement + # The list of values that represent the financial transactions recorded in a bank statement. + class BankStatementV2Transaction < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # The monetary amount of the transaction. + # @return [Float] + attr_reader :amount + # The date on which the transaction occurred. + # @return [String] + attr_reader :date + # The additional information about the transaction. + # @return [String] + attr_reader :description + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @amount = prediction['amount'] + @date = prediction['date'] + @description = prediction['description'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:amount] = + @amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@amount) + printable[:date] = format_for_display(@date) + printable[:description] = format_for_display(@description) + printable + end + + # @return [Hash] + def table_printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:amount] = + @amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@amount) + printable[:date] = format_for_display(@date, 10) + printable[:description] = format_for_display(@description, 36) + printable + end + + # @return [String] + def to_table_line + printable = table_printable_values + out_str = String.new + out_str << format('| %- 11s', printable[:amount]) + out_str << format('| %- 11s', printable[:date]) + out_str << format('| %- 37s', printable[:description]) + out_str << '|' + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Amount: #{printable[:amount]}" + out_str << "\n :Date: #{printable[:date]}" + out_str << "\n :Description: #{printable[:description]}" + out_str + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_transactions.rb b/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_transactions.rb new file mode 100644 index 000000000..a4a99df4b --- /dev/null +++ b/lib/mindee/v1/product/fr/bank_statement/bank_statement_v2_transactions.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require_relative 'bank_statement_v2_transaction' + +module Mindee + module V1 + module Product + module FR + module BankStatement + # The list of values that represent the financial transactions recorded in a bank statement. + class BankStatementV2Transactions < Array + # Entries. + # @return [Array] + attr_reader :entries + + # @param prediction [Array] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + entries = prediction.map do |entry| + BankStatement::BankStatementV2Transaction.new(entry, page_id) + end + super(entries) + end + + # Creates a line of rST table-compliant string separators. + # @param char [String] Character to use as a separator. + # @return [String] + def self.line_items_separator(char) + out_str = String.new + out_str << "+#{char * 12}" + out_str << "+#{char * 12}" + out_str << "+#{char * 38}" + out_str + end + + # @return [String] + def to_s + return '' if empty? + + lines = map do |entry| + "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" + end.join + out_str = String.new + out_str << "\n#{self.class.line_items_separator('-')}\n " + out_str << ' | Amount ' + out_str << ' | Date ' + out_str << ' | Description ' + out_str << " |\n#{self.class.line_items_separator('=')}" + out_str + lines + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/id_card/id_card_v1.rb b/lib/mindee/v1/product/fr/id_card/id_card_v1.rb new file mode 100644 index 000000000..40819ebf9 --- /dev/null +++ b/lib/mindee/v1/product/fr/id_card/id_card_v1.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'id_card_v1_document' +require_relative 'id_card_v1_page' + +module Mindee + module V1 + module Product + module FR + # Carte Nationale d'Identité module. + module IdCard + # Carte Nationale d'Identité API version 1 inference prediction. + class IdCardV1 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'idcard_fr' + @endpoint_version = '1' + @has_async = false + @has_sync = true + + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = IdCardV1Document.new(prediction['prediction'], nil) + @pages = [] + prediction['pages'].each do |page| + @pages.push(IdCardV1Page.new(page)) + end + end + + class << self + # Name of the endpoint for this product. + # @return [String] + attr_reader :endpoint_name + # Version for this product. + # @return [String] + attr_reader :endpoint_version + # Whether this product has access to an asynchronous endpoint. + # @return [bool] + attr_reader :has_async + # Whether this product has access to synchronous endpoint. + # @return [bool] + attr_reader :has_sync + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/id_card/id_card_v1_document.rb b/lib/mindee/v1/product/fr/id_card/id_card_v1_document.rb new file mode 100644 index 000000000..b151903d7 --- /dev/null +++ b/lib/mindee/v1/product/fr/id_card/id_card_v1_document.rb @@ -0,0 +1,106 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' + +module Mindee + module V1 + module Product + module FR + module IdCard + # Carte Nationale d'Identité API version 1.1 document data. + class IdCardV1Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # The name of the issuing authority. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :authority + # The date of birth of the card holder. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :birth_date + # The place of birth of the card holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :birth_place + # The expiry date of the identification card. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :expiry_date + # The gender of the card holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :gender + # The given name(s) of the card holder. + # @return [Array] + attr_reader :given_names + # The identification card number. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :id_number + # Machine Readable Zone, first line + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :mrz1 + # Machine Readable Zone, second line + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :mrz2 + # The surname of the card holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :surname + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @authority = Parsing::Standard::StringField.new( + prediction['authority'], + page_id + ) + @birth_date = Parsing::Standard::DateField.new( + prediction['birth_date'], + page_id + ) + @birth_place = Parsing::Standard::StringField.new( + prediction['birth_place'], + page_id + ) + @expiry_date = Parsing::Standard::DateField.new( + prediction['expiry_date'], + page_id + ) + @gender = Parsing::Standard::StringField.new( + prediction['gender'], + page_id + ) + @given_names = [] # : Array[Parsing::Standard::StringField] + prediction['given_names'].each do |item| + @given_names.push(Parsing::Standard::StringField.new(item, page_id)) + end + @id_number = Parsing::Standard::StringField.new( + prediction['id_number'], + page_id + ) + @mrz1 = Parsing::Standard::StringField.new(prediction['mrz1'], page_id) + @mrz2 = Parsing::Standard::StringField.new(prediction['mrz2'], page_id) + @surname = Parsing::Standard::StringField.new( + prediction['surname'], + page_id + ) + end + + # @return [String] + def to_s + given_names = @given_names.join("\n #{' ' * 15}") + out_str = String.new + out_str << "\n:Identity Number: #{@id_number}".rstrip + out_str << "\n:Given Name(s): #{given_names}".rstrip + out_str << "\n:Surname: #{@surname}".rstrip + out_str << "\n:Date of Birth: #{@birth_date}".rstrip + out_str << "\n:Place of Birth: #{@birth_place}".rstrip + out_str << "\n:Expiry Date: #{@expiry_date}".rstrip + out_str << "\n:Issuing Authority: #{@authority}".rstrip + out_str << "\n:Gender: #{@gender}".rstrip + out_str << "\n:MRZ Line 1: #{@mrz1}".rstrip + out_str << "\n:MRZ Line 2: #{@mrz2}".rstrip + out_str[1..].to_s + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/id_card/id_card_v1_page.rb b/lib/mindee/v1/product/fr/id_card/id_card_v1_page.rb new file mode 100644 index 000000000..d81bdf893 --- /dev/null +++ b/lib/mindee/v1/product/fr/id_card/id_card_v1_page.rb @@ -0,0 +1,57 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'id_card_v1_document' + +module Mindee + module V1 + module Product + module FR + module IdCard + # Carte Nationale d'Identité API version 1.1 page data. + class IdCardV1Page < Mindee::V1::Parsing::Common::Page + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = if prediction['prediction'].empty? + nil + else + IdCardV1PagePrediction.new( + prediction['prediction'], + prediction['id'] + ) + end + end + end + + # Carte Nationale d'Identité V1 page prediction. + class IdCardV1PagePrediction < IdCardV1Document + include Mindee::V1::Parsing::Standard + + # The side of the document which is visible. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :document_side + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + @document_side = Parsing::Standard::ClassificationField.new( + prediction['document_side'], + page_id + ) + super + end + + # @return [String] + def to_s + out_str = String.new + out_str << "\n:Document Side: #{@document_side}".rstrip + out_str << "\n#{super}" + out_str + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/id_card/id_card_v2.rb b/lib/mindee/v1/product/fr/id_card/id_card_v2.rb new file mode 100644 index 000000000..b628ae3d6 --- /dev/null +++ b/lib/mindee/v1/product/fr/id_card/id_card_v2.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'id_card_v2_document' +require_relative 'id_card_v2_page' + +module Mindee + module V1 + module Product + module FR + # Carte Nationale d'Identité module. + module IdCard + # Carte Nationale d'Identité API version 2 inference prediction. + class IdCardV2 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'idcard_fr' + @endpoint_version = '2' + @has_async = false + @has_sync = true + + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = IdCardV2Document.new(prediction['prediction'], nil) + @pages = [] + prediction['pages'].each do |page| + @pages.push(IdCardV2Page.new(page)) + end + end + + class << self + # Name of the endpoint for this product. + # @return [String] + attr_reader :endpoint_name + # Version for this product. + # @return [String] + attr_reader :endpoint_version + # Whether this product has access to an asynchronous endpoint. + # @return [bool] + attr_reader :has_async + # Whether this product has access to synchronous endpoint. + # @return [bool] + attr_reader :has_sync + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/id_card/id_card_v2_document.rb b/lib/mindee/v1/product/fr/id_card/id_card_v2_document.rb new file mode 100644 index 000000000..0d622e2b2 --- /dev/null +++ b/lib/mindee/v1/product/fr/id_card/id_card_v2_document.rb @@ -0,0 +1,143 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' + +module Mindee + module V1 + module Product + module FR + module IdCard + # Carte Nationale d'Identité API version 2.0 document data. + class IdCardV2Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # The alternate name of the card holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :alternate_name + # The name of the issuing authority. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :authority + # The date of birth of the card holder. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :birth_date + # The place of birth of the card holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :birth_place + # The card access number (CAN). + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :card_access_number + # The document number. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :document_number + # The expiry date of the identification card. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :expiry_date + # The gender of the card holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :gender + # The given name(s) of the card holder. + # @return [Array] + attr_reader :given_names + # The date of issue of the identification card. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :issue_date + # The Machine Readable Zone, first line. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :mrz1 + # The Machine Readable Zone, second line. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :mrz2 + # The Machine Readable Zone, third line. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :mrz3 + # The nationality of the card holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :nationality + # The surname of the card holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :surname + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @alternate_name = Parsing::Standard::StringField.new( + prediction['alternate_name'], + page_id + ) + @authority = Parsing::Standard::StringField.new( + prediction['authority'], + page_id + ) + @birth_date = Parsing::Standard::DateField.new( + prediction['birth_date'], + page_id + ) + @birth_place = Parsing::Standard::StringField.new( + prediction['birth_place'], + page_id + ) + @card_access_number = Parsing::Standard::StringField.new( + prediction['card_access_number'], + page_id + ) + @document_number = Parsing::Standard::StringField.new( + prediction['document_number'], + page_id + ) + @expiry_date = Parsing::Standard::DateField.new( + prediction['expiry_date'], + page_id + ) + @gender = Parsing::Standard::StringField.new( + prediction['gender'], + page_id + ) + @given_names = [] # : Array[Parsing::Standard::StringField] + prediction['given_names'].each do |item| + @given_names.push(Parsing::Standard::StringField.new(item, page_id)) + end + @issue_date = Parsing::Standard::DateField.new( + prediction['issue_date'], + page_id + ) + @mrz1 = Parsing::Standard::StringField.new(prediction['mrz1'], page_id) + @mrz2 = Parsing::Standard::StringField.new(prediction['mrz2'], page_id) + @mrz3 = Parsing::Standard::StringField.new(prediction['mrz3'], page_id) + @nationality = Parsing::Standard::StringField.new( + prediction['nationality'], + page_id + ) + @surname = Parsing::Standard::StringField.new( + prediction['surname'], + page_id + ) + end + + # @return [String] + def to_s + given_names = @given_names.join("\n #{' ' * 15}") + out_str = String.new + out_str << "\n:Nationality: #{@nationality}".rstrip + out_str << "\n:Card Access Number: #{@card_access_number}".rstrip + out_str << "\n:Document Number: #{@document_number}".rstrip + out_str << "\n:Given Name(s): #{given_names}".rstrip + out_str << "\n:Surname: #{@surname}".rstrip + out_str << "\n:Alternate Name: #{@alternate_name}".rstrip + out_str << "\n:Date of Birth: #{@birth_date}".rstrip + out_str << "\n:Place of Birth: #{@birth_place}".rstrip + out_str << "\n:Gender: #{@gender}".rstrip + out_str << "\n:Expiry Date: #{@expiry_date}".rstrip + out_str << "\n:Mrz Line 1: #{@mrz1}".rstrip + out_str << "\n:Mrz Line 2: #{@mrz2}".rstrip + out_str << "\n:Mrz Line 3: #{@mrz3}".rstrip + out_str << "\n:Date of Issue: #{@issue_date}".rstrip + out_str << "\n:Issuing Authority: #{@authority}".rstrip + out_str[1..].to_s + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/fr/id_card/id_card_v2_page.rb b/lib/mindee/v1/product/fr/id_card/id_card_v2_page.rb new file mode 100644 index 000000000..d3f1eaf72 --- /dev/null +++ b/lib/mindee/v1/product/fr/id_card/id_card_v2_page.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +require_relative '../../../parsing' +require_relative 'id_card_v2_document' + +module Mindee + module V1 + module Product + module FR + module IdCard + # Carte Nationale d'Identité API version 2.0 page data. + class IdCardV2Page < Mindee::V1::Parsing::Common::Page + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = if prediction['prediction'].empty? + nil + else + IdCardV2PagePrediction.new( + prediction['prediction'], + prediction['id'] + ) + end + end + end + + # Carte Nationale d'Identité V2 page prediction. + class IdCardV2PagePrediction < IdCardV2Document + include Mindee::V1::Parsing::Standard + + # The sides of the document which are visible. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :document_side + # The document type or format. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :document_type + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + @document_side = Parsing::Standard::ClassificationField.new( + prediction['document_side'], + page_id + ) + @document_type = Parsing::Standard::ClassificationField.new( + prediction['document_type'], + page_id + ) + super + end + + # @return [String] + def to_s + out_str = String.new + out_str << "\n:Document Type: #{@document_type}".rstrip + out_str << "\n:Document Sides: #{@document_side}".rstrip + out_str << "\n#{super}" + out_str + end + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/bank_statement/bank_statement_v2.rb b/lib/mindee/v1/product/international_id/international_id_v2.rb similarity index 62% rename from lib/mindee/product/fr/bank_statement/bank_statement_v2.rb rename to lib/mindee/v1/product/international_id/international_id_v2.rb index c119d46f5..0305ac8c5 100644 --- a/lib/mindee/product/fr/bank_statement/bank_statement_v2.rb +++ b/lib/mindee/v1/product/international_id/international_id_v2.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'bank_statement_v2_document' -require_relative 'bank_statement_v2_page' +require_relative '../../parsing' +require_relative 'international_id_v2_document' +require_relative 'international_id_v2_page' module Mindee - module Product - module FR - # Bank Statement module. - module BankStatement - # Bank Statement API version 2 inference prediction. - class BankStatementV2 < Mindee::Parsing::Common::Inference - @endpoint_name = 'bank_statement_fr' + module V1 + module Product + # International ID module. + module InternationalId + # International ID API version 2 inference prediction. + class InternationalIdV2 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'international_id' @endpoint_version = '2' @has_async = true @has_sync = false @@ -19,10 +19,10 @@ class BankStatementV2 < Mindee::Parsing::Common::Inference # @param prediction [Hash] def initialize(prediction) super - @prediction = BankStatementV2Document.new(prediction['prediction'], nil) + @prediction = InternationalIdV2Document.new(prediction['prediction'], nil) @pages = [] prediction['pages'].each do |page| - @pages.push(BankStatementV2Page.new(page)) + @pages.push(InternationalIdV2Page.new(page)) end end diff --git a/lib/mindee/v1/product/international_id/international_id_v2_document.rb b/lib/mindee/v1/product/international_id/international_id_v2_document.rb new file mode 100644 index 000000000..16c664c06 --- /dev/null +++ b/lib/mindee/v1/product/international_id/international_id_v2_document.rb @@ -0,0 +1,164 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module InternationalId + # International ID API version 2.2 document data. + class InternationalIdV2Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # The physical address of the document holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :address + # The date of birth of the document holder. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :birth_date + # The place of birth of the document holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :birth_place + # The country where the document was issued. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :country_of_issue + # The unique identifier assigned to the document. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :document_number + # The type of personal identification document. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :document_type + # The date when the document becomes invalid. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :expiry_date + # The list of the document holder's given names. + # @return [Array] + attr_reader :given_names + # The date when the document was issued. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :issue_date + # The Machine Readable Zone, first line. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :mrz_line1 + # The Machine Readable Zone, second line. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :mrz_line2 + # The Machine Readable Zone, third line. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :mrz_line3 + # The country of citizenship of the document holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :nationality + # The unique identifier assigned to the document holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :personal_number + # The biological sex of the document holder. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :sex + # The state or territory where the document was issued. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :state_of_issue + # The list of the document holder's family names. + # @return [Array] + attr_reader :surnames + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @address = Parsing::Standard::StringField.new( + prediction['address'], + page_id + ) + @birth_date = Parsing::Standard::DateField.new( + prediction['birth_date'], + page_id + ) + @birth_place = Parsing::Standard::StringField.new( + prediction['birth_place'], + page_id + ) + @country_of_issue = Parsing::Standard::StringField.new( + prediction['country_of_issue'], + page_id + ) + @document_number = Parsing::Standard::StringField.new( + prediction['document_number'], + page_id + ) + @document_type = Parsing::Standard::ClassificationField.new( + prediction['document_type'], + page_id + ) + @expiry_date = Parsing::Standard::DateField.new( + prediction['expiry_date'], + page_id + ) + @given_names = [] # : Array[Parsing::Standard::StringField] + prediction['given_names'].each do |item| + @given_names.push(Parsing::Standard::StringField.new(item, page_id)) + end + @issue_date = Parsing::Standard::DateField.new( + prediction['issue_date'], + page_id + ) + @mrz_line1 = Parsing::Standard::StringField.new( + prediction['mrz_line1'], + page_id + ) + @mrz_line2 = Parsing::Standard::StringField.new( + prediction['mrz_line2'], + page_id + ) + @mrz_line3 = Parsing::Standard::StringField.new( + prediction['mrz_line3'], + page_id + ) + @nationality = Parsing::Standard::StringField.new( + prediction['nationality'], + page_id + ) + @personal_number = Parsing::Standard::StringField.new( + prediction['personal_number'], + page_id + ) + @sex = Parsing::Standard::StringField.new(prediction['sex'], page_id) + @state_of_issue = Parsing::Standard::StringField.new( + prediction['state_of_issue'], + page_id + ) + @surnames = [] # : Array[Parsing::Standard::StringField] + prediction['surnames'].each do |item| + @surnames.push(Parsing::Standard::StringField.new(item, page_id)) + end + end + + # @return [String] + def to_s + surnames = @surnames.join("\n #{' ' * 10}") + given_names = @given_names.join("\n #{' ' * 13}") + out_str = String.new + out_str << "\n:Document Type: #{@document_type}".rstrip + out_str << "\n:Document Number: #{@document_number}".rstrip + out_str << "\n:Surnames: #{surnames}".rstrip + out_str << "\n:Given Names: #{given_names}".rstrip + out_str << "\n:Sex: #{@sex}".rstrip + out_str << "\n:Birth Date: #{@birth_date}".rstrip + out_str << "\n:Birth Place: #{@birth_place}".rstrip + out_str << "\n:Nationality: #{@nationality}".rstrip + out_str << "\n:Personal Number: #{@personal_number}".rstrip + out_str << "\n:Country of Issue: #{@country_of_issue}".rstrip + out_str << "\n:State of Issue: #{@state_of_issue}".rstrip + out_str << "\n:Issue Date: #{@issue_date}".rstrip + out_str << "\n:Expiration Date: #{@expiry_date}".rstrip + out_str << "\n:Address: #{@address}".rstrip + out_str << "\n:MRZ Line 1: #{@mrz_line1}".rstrip + out_str << "\n:MRZ Line 2: #{@mrz_line2}".rstrip + out_str << "\n:MRZ Line 3: #{@mrz_line3}".rstrip + out_str[1..].to_s + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_page.rb b/lib/mindee/v1/product/international_id/international_id_v2_page.rb similarity index 58% rename from lib/mindee/product/fr/energy_bill/energy_bill_v1_page.rb rename to lib/mindee/v1/product/international_id/international_id_v2_page.rb index ebc00d056..9044ecce8 100644 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_page.rb +++ b/lib/mindee/v1/product/international_id/international_id_v2_page.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'energy_bill_v1_document' +require_relative '../../parsing' +require_relative 'international_id_v2_document' module Mindee - module Product - module FR - module EnergyBill - # Energy Bill API version 1.2 page data. - class EnergyBillV1Page < Mindee::Parsing::Common::Page + module V1 + module Product + module InternationalId + # International ID API version 2.2 page data. + class InternationalIdV2Page < Mindee::V1::Parsing::Common::Page # @param prediction [Hash] def initialize(prediction) super @prediction = if prediction['prediction'].empty? nil else - EnergyBillV1PagePrediction.new( + InternationalIdV2PagePrediction.new( prediction['prediction'], prediction['id'] ) @@ -23,8 +23,8 @@ def initialize(prediction) end end - # Energy Bill V1 page prediction. - class EnergyBillV1PagePrediction < EnergyBillV1Document + # International ID V2 page prediction. + class InternationalIdV2PagePrediction < InternationalIdV2Document # @return [String] def to_s out_str = String.new diff --git a/lib/mindee/product/fr/payslip/payslip_v3.rb b/lib/mindee/v1/product/invoice/invoice_v4.rb similarity index 62% rename from lib/mindee/product/fr/payslip/payslip_v3.rb rename to lib/mindee/v1/product/invoice/invoice_v4.rb index 6eeabe658..139bfa1b5 100644 --- a/lib/mindee/product/fr/payslip/payslip_v3.rb +++ b/lib/mindee/v1/product/invoice/invoice_v4.rb @@ -1,28 +1,28 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'payslip_v3_document' -require_relative 'payslip_v3_page' +require_relative '../../parsing' +require_relative 'invoice_v4_document' +require_relative 'invoice_v4_page' module Mindee - module Product - module FR - # Payslip module. - module Payslip - # Payslip API version 3 inference prediction. - class PayslipV3 < Mindee::Parsing::Common::Inference - @endpoint_name = 'payslip_fra' - @endpoint_version = '3' + module V1 + module Product + # Invoice module. + module Invoice + # Invoice API version 4 inference prediction. + class InvoiceV4 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'invoices' + @endpoint_version = '4' @has_async = true - @has_sync = false + @has_sync = true # @param prediction [Hash] def initialize(prediction) super - @prediction = PayslipV3Document.new(prediction['prediction'], nil) + @prediction = InvoiceV4Document.new(prediction['prediction'], nil) @pages = [] prediction['pages'].each do |page| - @pages.push(PayslipV3Page.new(page)) + @pages.push(InvoiceV4Page.new(page)) end end diff --git a/lib/mindee/v1/product/invoice/invoice_v4_document.rb b/lib/mindee/v1/product/invoice/invoice_v4_document.rb new file mode 100644 index 000000000..cfd06c148 --- /dev/null +++ b/lib/mindee/v1/product/invoice/invoice_v4_document.rb @@ -0,0 +1,300 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'invoice_v4_line_items' + +module Mindee + module V1 + module Product + module Invoice + # Invoice API version 4.11 document data. + class InvoiceV4Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # The customer billing address. + # @return [Mindee::V1::Parsing::Standard::AddressField] + attr_reader :billing_address + # The purchase category. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :category + # The address of the customer. + # @return [Mindee::V1::Parsing::Standard::AddressField] + attr_reader :customer_address + # List of company registration numbers associated to the customer. + # @return [Array] + attr_reader :customer_company_registrations + # The customer account number or identifier from the supplier. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :customer_id + # The name of the customer or client. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :customer_name + # The date the purchase was made. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :date + # Document type: INVOICE or CREDIT NOTE. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :document_type + # Document type extended. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :document_type_extended + # The date on which the payment is due. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :due_date + # The invoice number or identifier. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :invoice_number + # List of all the line items present on the invoice. + # @return [Mindee::V1::Product::Invoice::InvoiceV4LineItems] + attr_reader :line_items + # The locale of the document. + # @return [Mindee::V1::Parsing::Standard::LocaleField] + attr_reader :locale + # The date on which the payment is due / was full-filled. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :payment_date + # The purchase order number. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :po_number + # List of all reference numbers on the invoice, including the purchase order number. + # @return [Array] + attr_reader :reference_numbers + # Customer's delivery address. + # @return [Mindee::V1::Parsing::Standard::AddressField] + attr_reader :shipping_address + # The purchase subcategory for transport, food and shopping. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :subcategory + # The address of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::AddressField] + attr_reader :supplier_address + # List of company registration numbers associated to the supplier. + # @return [Array] + attr_reader :supplier_company_registrations + # The email address of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_email + # The name of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_name + # List of payment details associated to the supplier of the invoice. + # @return [Array] + attr_reader :supplier_payment_details + # The phone number of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_phone_number + # The website URL of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_website + # List of taxes. Each item contains the detail of the tax. + # @return [Mindee::V1::Parsing::Standard::Taxes] + attr_reader :taxes + # The total amount of the invoice: includes taxes, tips, fees, and other charges. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_amount + # The net amount of the invoice: does not include taxes, fees, and discounts. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_net + # The total tax: the sum of all the taxes for this invoice. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_tax + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @billing_address = Parsing::Standard::AddressField.new( + prediction['billing_address'], + page_id + ) + @category = Parsing::Standard::ClassificationField.new( + prediction['category'], + page_id + ) + @customer_address = Parsing::Standard::AddressField.new( + prediction['customer_address'], + page_id + ) + @customer_company_registrations = [] # : Array[Parsing::Standard::CompanyRegistrationField] + prediction['customer_company_registrations'].each do |item| + @customer_company_registrations.push(Parsing::Standard::CompanyRegistrationField.new(item, page_id)) + end + @customer_id = Parsing::Standard::StringField.new( + prediction['customer_id'], + page_id + ) + @customer_name = Parsing::Standard::StringField.new( + prediction['customer_name'], + page_id + ) + @date = Parsing::Standard::DateField.new(prediction['date'], page_id) + @document_type = Parsing::Standard::ClassificationField.new( + prediction['document_type'], + page_id + ) + @document_type_extended = Parsing::Standard::ClassificationField.new( + prediction['document_type_extended'], + page_id + ) + @due_date = Parsing::Standard::DateField.new( + prediction['due_date'], + page_id + ) + @invoice_number = Parsing::Standard::StringField.new( + prediction['invoice_number'], + page_id + ) + @line_items = Product::Invoice::InvoiceV4LineItems.new(prediction['line_items'], page_id) + @locale = Parsing::Standard::LocaleField.new( + prediction['locale'], + page_id + ) + @payment_date = Parsing::Standard::DateField.new( + prediction['payment_date'], + page_id + ) + @po_number = Parsing::Standard::StringField.new( + prediction['po_number'], + page_id + ) + @reference_numbers = [] # : Array[Parsing::Standard::StringField] + prediction['reference_numbers'].each do |item| + @reference_numbers.push(Parsing::Standard::StringField.new(item, page_id)) + end + @shipping_address = Parsing::Standard::AddressField.new( + prediction['shipping_address'], + page_id + ) + @subcategory = Parsing::Standard::ClassificationField.new( + prediction['subcategory'], + page_id + ) + @supplier_address = Parsing::Standard::AddressField.new( + prediction['supplier_address'], + page_id + ) + @supplier_company_registrations = [] # : Array[Parsing::Standard::CompanyRegistrationField] + prediction['supplier_company_registrations'].each do |item| + @supplier_company_registrations.push(Parsing::Standard::CompanyRegistrationField.new(item, page_id)) + end + @supplier_email = Parsing::Standard::StringField.new( + prediction['supplier_email'], + page_id + ) + @supplier_name = Parsing::Standard::StringField.new( + prediction['supplier_name'], + page_id + ) + @supplier_payment_details = [] # : Array[Parsing::Standard::PaymentDetailsField] + prediction['supplier_payment_details'].each do |item| + @supplier_payment_details.push(Parsing::Standard::PaymentDetailsField.new(item, page_id)) + end + @supplier_phone_number = Parsing::Standard::StringField.new( + prediction['supplier_phone_number'], + page_id + ) + @supplier_website = Parsing::Standard::StringField.new( + prediction['supplier_website'], + page_id + ) + @taxes = Parsing::Standard::Taxes.new(prediction['taxes'], page_id) + @total_amount = Parsing::Standard::AmountField.new( + prediction['total_amount'], + page_id + ) + @total_net = Parsing::Standard::AmountField.new( + prediction['total_net'], + page_id + ) + @total_tax = Parsing::Standard::AmountField.new( + prediction['total_tax'], + page_id + ) + end + + # @return [String] + def to_s + reference_numbers = @reference_numbers.join("\n #{' ' * 19}") + supplier_payment_details = @supplier_payment_details.join("\n #{' ' * 26}") + supplier_company_registrations = @supplier_company_registrations.join("\n #{' ' * 32}") + customer_company_registrations = @customer_company_registrations.join("\n #{' ' * 32}") + line_items = line_items_to_s + out_str = String.new + out_str << "\n:Locale: #{@locale}".rstrip + out_str << "\n:Invoice Number: #{@invoice_number}".rstrip + out_str << "\n:Purchase Order Number: #{@po_number}".rstrip + out_str << "\n:Reference Numbers: #{reference_numbers}".rstrip + out_str << "\n:Purchase Date: #{@date}".rstrip + out_str << "\n:Due Date: #{@due_date}".rstrip + out_str << "\n:Payment Date: #{@payment_date}".rstrip + out_str << "\n:Total Net: #{@total_net}".rstrip + out_str << "\n:Total Amount: #{@total_amount}".rstrip + out_str << "\n:Total Tax: #{@total_tax}".rstrip + out_str << "\n:Taxes:#{@taxes}".rstrip + out_str << "\n:Supplier Payment Details: #{supplier_payment_details}".rstrip + out_str << "\n:Supplier Name: #{@supplier_name}".rstrip + out_str << "\n:Supplier Company Registrations: #{supplier_company_registrations}".rstrip + out_str << "\n:Supplier Address: #{@supplier_address}".rstrip + out_str << "\n:Supplier Phone Number: #{@supplier_phone_number}".rstrip + out_str << "\n:Supplier Website: #{@supplier_website}".rstrip + out_str << "\n:Supplier Email: #{@supplier_email}".rstrip + out_str << "\n:Customer Name: #{@customer_name}".rstrip + out_str << "\n:Customer Company Registrations: #{customer_company_registrations}".rstrip + out_str << "\n:Customer Address: #{@customer_address}".rstrip + out_str << "\n:Customer ID: #{@customer_id}".rstrip + out_str << "\n:Shipping Address: #{@shipping_address}".rstrip + out_str << "\n:Billing Address: #{@billing_address}".rstrip + out_str << "\n:Document Type: #{@document_type}".rstrip + out_str << "\n:Document Type Extended: #{@document_type_extended}".rstrip + out_str << "\n:Purchase Subcategory: #{@subcategory}".rstrip + out_str << "\n:Purchase Category: #{@category}".rstrip + out_str << "\n:Line Items:" + out_str << line_items + out_str[1..].to_s + end + + private + + # @param char [String] + # @return [String] + def line_items_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 38}" + out_str << "+#{char * 14}" + out_str << "+#{char * 10}" + out_str << "+#{char * 12}" + out_str << "+#{char * 14}" + out_str << "+#{char * 14}" + out_str << "+#{char * 17}" + out_str << "+#{char * 12}" + out_str << '+' + out_str + end + + # @return [String] + def line_items_to_s + return '' if @line_items.empty? + + line_items = @line_items.map(&:to_table_line).join("\n#{line_items_separator('-')}\n ") + out_str = String.new + out_str << "\n#{line_items_separator('-')}" + out_str << "\n |" + out_str << ' Description |' + out_str << ' Product code |' + out_str << ' Quantity |' + out_str << ' Tax Amount |' + out_str << ' Tax Rate (%) |' + out_str << ' Total Amount |' + out_str << ' Unit of measure |' + out_str << ' Unit Price |' + out_str << "\n#{line_items_separator('=')}" + out_str << "\n #{line_items}" + out_str << "\n#{line_items_separator('-')}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/invoice/invoice_v4_line_item.rb b/lib/mindee/v1/product/invoice/invoice_v4_line_item.rb new file mode 100644 index 000000000..2e5b83574 --- /dev/null +++ b/lib/mindee/v1/product/invoice/invoice_v4_line_item.rb @@ -0,0 +1,124 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module Invoice + # List of all the line items present on the invoice. + class InvoiceV4LineItem < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # The item description. + # @return [String] + attr_reader :description + # The product code of the item. + # @return [String] + attr_reader :product_code + # The item quantity + # @return [Float] + attr_reader :quantity + # The item tax amount. + # @return [Float] + attr_reader :tax_amount + # The item tax rate in percentage. + # @return [Float] + attr_reader :tax_rate + # The item total amount. + # @return [Float] + attr_reader :total_amount + # The item unit of measure. + # @return [String] + attr_reader :unit_measure + # The item unit price. + # @return [Float] + attr_reader :unit_price + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @description = prediction['description'] + @product_code = prediction['product_code'] + @quantity = prediction['quantity'] + @tax_amount = prediction['tax_amount'] + @tax_rate = prediction['tax_rate'] + @total_amount = prediction['total_amount'] + @unit_measure = prediction['unit_measure'] + @unit_price = prediction['unit_price'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:description] = format_for_display(@description) + printable[:product_code] = format_for_display(@product_code) + printable[:quantity] = + @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) + printable[:tax_amount] = + @tax_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_amount) + printable[:tax_rate] = + @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) + printable[:total_amount] = + @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) + printable[:unit_measure] = format_for_display(@unit_measure) + printable[:unit_price] = + @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) + printable + end + + # @return [Hash] + def table_printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:description] = format_for_display(@description, 36) + printable[:product_code] = format_for_display(@product_code, nil) + printable[:quantity] = + @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) + printable[:tax_amount] = + @tax_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_amount) + printable[:tax_rate] = + @tax_rate.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@tax_rate) + printable[:total_amount] = + @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) + printable[:unit_measure] = format_for_display(@unit_measure, nil) + printable[:unit_price] = + @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) + printable + end + + # @return [String] + def to_table_line + printable = table_printable_values + out_str = String.new + out_str << format('| %- 37s', printable[:description]) + out_str << format('| %- 13s', printable[:product_code]) + out_str << format('| %- 9s', printable[:quantity]) + out_str << format('| %- 11s', printable[:tax_amount]) + out_str << format('| %- 13s', printable[:tax_rate]) + out_str << format('| %- 13s', printable[:total_amount]) + out_str << format('| %- 16s', printable[:unit_measure]) + out_str << format('| %- 11s', printable[:unit_price]) + out_str << '|' + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Description: #{printable[:description]}" + out_str << "\n :Product code: #{printable[:product_code]}" + out_str << "\n :Quantity: #{printable[:quantity]}" + out_str << "\n :Tax Amount: #{printable[:tax_amount]}" + out_str << "\n :Tax Rate (%): #{printable[:tax_rate]}" + out_str << "\n :Total Amount: #{printable[:total_amount]}" + out_str << "\n :Unit of measure: #{printable[:unit_measure]}" + out_str << "\n :Unit Price: #{printable[:unit_price]}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contributions.rb b/lib/mindee/v1/product/invoice/invoice_v4_line_items.rb similarity index 61% rename from lib/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contributions.rb rename to lib/mindee/v1/product/invoice/invoice_v4_line_items.rb index f0202a696..3d2da3072 100644 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contributions.rb +++ b/lib/mindee/v1/product/invoice/invoice_v4_line_items.rb @@ -1,27 +1,22 @@ # frozen_string_literal: true -require_relative 'energy_bill_v1_energy_supplier' -require_relative 'energy_bill_v1_energy_consumer' -require_relative 'energy_bill_v1_subscription' -require_relative 'energy_bill_v1_energy_usage' -require_relative 'energy_bill_v1_taxes_and_contribution' -require_relative 'energy_bill_v1_meter_detail' +require_relative 'invoice_v4_line_item' module Mindee - module Product - module FR - module EnergyBill - # Details of Taxes and Contributions. - class EnergyBillV1TaxesAndContributions < Array + module V1 + module Product + module Invoice + # List of all the line items present on the invoice. + class InvoiceV4LineItems < Array # Entries. - # @return [Array] + # @return [Array] attr_reader :entries # @param prediction [Array] # @param page_id [Integer, nil] def initialize(prediction, page_id) entries = prediction.map do |entry| - EnergyBill::EnergyBillV1TaxesAndContribution.new(entry, page_id) + Invoice::InvoiceV4LineItem.new(entry, page_id) end super(entries) end @@ -32,10 +27,12 @@ def initialize(prediction, page_id) def self.line_items_separator(char) out_str = String.new out_str << "+#{char * 38}" - out_str << "+#{char * 12}" - out_str << "+#{char * 12}" + out_str << "+#{char * 14}" out_str << "+#{char * 10}" - out_str << "+#{char * 11}" + out_str << "+#{char * 12}" + out_str << "+#{char * 14}" + out_str << "+#{char * 14}" + out_str << "+#{char * 17}" out_str << "+#{char * 12}" out_str end @@ -50,10 +47,12 @@ def to_s out_str = String.new out_str << "\n#{self.class.line_items_separator('-')}\n " out_str << ' | Description ' - out_str << ' | End Date ' - out_str << ' | Start Date' - out_str << ' | Tax Rate' - out_str << ' | Total ' + out_str << ' | Product code' + out_str << ' | Quantity' + out_str << ' | Tax Amount' + out_str << ' | Tax Rate (%)' + out_str << ' | Total Amount' + out_str << ' | Unit of measure' out_str << ' | Unit Price' out_str << " |\n#{self.class.line_items_separator('=')}" out_str + lines diff --git a/lib/mindee/product/fr/carte_grise/carte_grise_v1_page.rb b/lib/mindee/v1/product/invoice/invoice_v4_page.rb similarity index 60% rename from lib/mindee/product/fr/carte_grise/carte_grise_v1_page.rb rename to lib/mindee/v1/product/invoice/invoice_v4_page.rb index 492e459c1..19c064720 100644 --- a/lib/mindee/product/fr/carte_grise/carte_grise_v1_page.rb +++ b/lib/mindee/v1/product/invoice/invoice_v4_page.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'carte_grise_v1_document' +require_relative '../../parsing' +require_relative 'invoice_v4_document' module Mindee - module Product - module FR - module CarteGrise - # Carte Grise API version 1.1 page data. - class CarteGriseV1Page < Mindee::Parsing::Common::Page + module V1 + module Product + module Invoice + # Invoice API version 4.11 page data. + class InvoiceV4Page < Mindee::V1::Parsing::Common::Page # @param prediction [Hash] def initialize(prediction) super @prediction = if prediction['prediction'].empty? nil else - CarteGriseV1PagePrediction.new( + InvoiceV4PagePrediction.new( prediction['prediction'], prediction['id'] ) @@ -23,8 +23,8 @@ def initialize(prediction) end end - # Carte Grise V1 page prediction. - class CarteGriseV1PagePrediction < CarteGriseV1Document + # Invoice V4 page prediction. + class InvoiceV4PagePrediction < InvoiceV4Document # @return [String] def to_s out_str = String.new diff --git a/lib/mindee/product/ind/indian_passport/indian_passport_v1.rb b/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1.rb similarity index 62% rename from lib/mindee/product/ind/indian_passport/indian_passport_v1.rb rename to lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1.rb index 48689564f..8df5a0b0f 100644 --- a/lib/mindee/product/ind/indian_passport/indian_passport_v1.rb +++ b/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'indian_passport_v1_document' -require_relative 'indian_passport_v1_page' +require_relative '../../parsing' +require_relative 'invoice_splitter_v1_document' +require_relative 'invoice_splitter_v1_page' module Mindee - module Product - module IND - # Passport - India module. - module IndianPassport - # Passport - India API version 1 inference prediction. - class IndianPassportV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'ind_passport' + module V1 + module Product + # Invoice Splitter module. + module InvoiceSplitter + # Invoice Splitter API version 1 inference prediction. + class InvoiceSplitterV1 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'invoice_splitter' @endpoint_version = '1' @has_async = true @has_sync = false @@ -19,10 +19,10 @@ class IndianPassportV1 < Mindee::Parsing::Common::Inference # @param prediction [Hash] def initialize(prediction) super - @prediction = IndianPassportV1Document.new(prediction['prediction'], nil) + @prediction = InvoiceSplitterV1Document.new(prediction['prediction'], nil) @pages = [] prediction['pages'].each do |page| - @pages.push(IndianPassportV1Page.new(page)) + @pages.push(InvoiceSplitterV1Page.new(page)) end end diff --git a/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_document.rb b/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_document.rb new file mode 100644 index 000000000..7619c0a5b --- /dev/null +++ b/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_document.rb @@ -0,0 +1,66 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'invoice_splitter_v1_invoice_page_groups' + +module Mindee + module V1 + module Product + module InvoiceSplitter + # Invoice Splitter API version 1.4 document data. + class InvoiceSplitterV1Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # List of page groups. Each group represents a single invoice within a multi-invoice document. + # @return [Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1InvoicePageGroups] + attr_reader :invoice_page_groups + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @invoice_page_groups = Product::InvoiceSplitter::InvoiceSplitterV1InvoicePageGroups.new( + prediction['invoice_page_groups'], page_id + ) + end + + # @return [String] + def to_s + invoice_page_groups = invoice_page_groups_to_s + out_str = String.new + out_str << "\n:Invoice Page Groups:" + out_str << invoice_page_groups + out_str[1..].to_s + end + + private + + # @param char [String] + # @return [String] + def invoice_page_groups_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 74}" + out_str << '+' + out_str + end + + # @return [String] + def invoice_page_groups_to_s + return '' if @invoice_page_groups.empty? + + line_items = @invoice_page_groups.map(&:to_table_line).join("\n#{invoice_page_groups_separator('-')}\n ") + out_str = String.new + out_str << "\n#{invoice_page_groups_separator('-')}" + out_str << "\n |" + out_str << ' Page Indexes |' + out_str << "\n#{invoice_page_groups_separator('=')}" + out_str << "\n #{line_items}" + out_str << "\n#{invoice_page_groups_separator('-')}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rb b/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rb new file mode 100644 index 000000000..8c72438d7 --- /dev/null +++ b/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module InvoiceSplitter + # List of page groups. Each group represents a single invoice within a multi-invoice document. + class InvoiceSplitterV1InvoicePageGroup < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # List of page indexes that belong to the same invoice (group). + # @return [Array] + attr_reader :page_indexes + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @page_indexes = prediction['page_indexes'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:page_indexes] = format_for_display(@page_indexes) + printable + end + + # @return [Hash] + def table_printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:page_indexes] = @page_indexes.join(', ') + printable + end + + # @return [String] + def to_table_line + printable = table_printable_values + out_str = String.new + out_str << format('| %- 73s', printable[:page_indexes]) + out_str << '|' + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Page Indexes: #{printable[:page_indexes]}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/product/us/healthcare_card/healthcare_card_v1_copays.rb b/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rb similarity index 65% rename from lib/mindee/product/us/healthcare_card/healthcare_card_v1_copays.rb rename to lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rb index d65799f6a..5919fe689 100644 --- a/lib/mindee/product/us/healthcare_card/healthcare_card_v1_copays.rb +++ b/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rb @@ -1,22 +1,22 @@ # frozen_string_literal: true -require_relative 'healthcare_card_v1_copay' +require_relative 'invoice_splitter_v1_invoice_page_group' module Mindee - module Product - module US - module HealthcareCard - # Copayments for covered services. - class HealthcareCardV1Copays < Array + module V1 + module Product + module InvoiceSplitter + # List of page groups. Each group represents a single invoice within a multi-invoice document. + class InvoiceSplitterV1InvoicePageGroups < Array # Entries. - # @return [Array] + # @return [Array] attr_reader :entries # @param prediction [Array] # @param page_id [Integer, nil] def initialize(prediction, page_id) entries = prediction.map do |entry| - HealthcareCard::HealthcareCardV1Copay.new(entry, page_id) + InvoiceSplitter::InvoiceSplitterV1InvoicePageGroup.new(entry, page_id) end super(entries) end @@ -26,8 +26,7 @@ def initialize(prediction, page_id) # @return [String] def self.line_items_separator(char) out_str = String.new - out_str << "+#{char * 14}" - out_str << "+#{char * 22}" + out_str << "+#{char * 74}" out_str end @@ -40,8 +39,7 @@ def to_s end.join out_str = String.new out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Service Fees' - out_str << ' | Service Name ' + out_str << ' | Page Indexes ' out_str << " |\n#{self.class.line_items_separator('=')}" out_str + lines end diff --git a/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_page.rb b/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_page.rb new file mode 100644 index 000000000..5f654f760 --- /dev/null +++ b/lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_page.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'invoice_splitter_v1_document' + +module Mindee + module V1 + module Product + module InvoiceSplitter + # Invoice Splitter API version 1.4 page data. + class InvoiceSplitterV1Page < Mindee::V1::Parsing::Common::Page + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = if prediction['prediction'].empty? + nil + else + InvoiceSplitterV1PagePrediction.new( + prediction['prediction'], + prediction['id'] + ) + end + end + end + + # Invoice Splitter V1 page prediction. + class InvoiceSplitterV1PagePrediction < InvoiceSplitterV1Document + # @return [String] + def to_s + out_str = String.new + out_str << "\n#{super}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/bank_account_details/bank_account_details_v1.rb b/lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1.rb similarity index 60% rename from lib/mindee/product/fr/bank_account_details/bank_account_details_v1.rb rename to lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1.rb index edb3ada1f..3cca13f43 100644 --- a/lib/mindee/product/fr/bank_account_details/bank_account_details_v1.rb +++ b/lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'bank_account_details_v1_document' -require_relative 'bank_account_details_v1_page' +require_relative '../../parsing' +require_relative 'multi_receipts_detector_v1_document' +require_relative 'multi_receipts_detector_v1_page' module Mindee - module Product - module FR - # Bank Account Details module. - module BankAccountDetails - # Bank Account Details API version 1 inference prediction. - class BankAccountDetailsV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'bank_account_details' + module V1 + module Product + # Multi Receipts Detector module. + module MultiReceiptsDetector + # Multi Receipts Detector API version 1 inference prediction. + class MultiReceiptsDetectorV1 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'multi_receipts_detector' @endpoint_version = '1' @has_async = false @has_sync = true @@ -19,10 +19,10 @@ class BankAccountDetailsV1 < Mindee::Parsing::Common::Inference # @param prediction [Hash] def initialize(prediction) super - @prediction = BankAccountDetailsV1Document.new(prediction['prediction'], nil) + @prediction = MultiReceiptsDetectorV1Document.new(prediction['prediction'], nil) @pages = [] prediction['pages'].each do |page| - @pages.push(BankAccountDetailsV1Page.new(page)) + @pages.push(MultiReceiptsDetectorV1Page.new(page)) end end diff --git a/lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_document.rb b/lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_document.rb new file mode 100644 index 000000000..a5c23ea7f --- /dev/null +++ b/lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_document.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module MultiReceiptsDetector + # Multi Receipts Detector API version 1.1 document data. + class MultiReceiptsDetectorV1Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # Positions of the receipts on the document. + # @return [Array] + attr_reader :receipts + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @receipts = [] # : Array[Parsing::Standard::PositionField] + prediction['receipts'].each do |item| + @receipts.push(Parsing::Standard::PositionField.new(item, page_id)) + end + end + + # @return [String] + def to_s + receipts = @receipts.join("\n #{' ' * 18}") + out_str = String.new + out_str << "\n:List of Receipts: #{receipts}".rstrip + out_str[1..].to_s + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/bank_account_details/bank_account_details_v1_page.rb b/lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_page.rb similarity index 56% rename from lib/mindee/product/fr/bank_account_details/bank_account_details_v1_page.rb rename to lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_page.rb index 93c5571e3..14e05304f 100644 --- a/lib/mindee/product/fr/bank_account_details/bank_account_details_v1_page.rb +++ b/lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_page.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'bank_account_details_v1_document' +require_relative '../../parsing' +require_relative 'multi_receipts_detector_v1_document' module Mindee - module Product - module FR - module BankAccountDetails - # Bank Account Details API version 1.0 page data. - class BankAccountDetailsV1Page < Mindee::Parsing::Common::Page + module V1 + module Product + module MultiReceiptsDetector + # Multi Receipts Detector API version 1.1 page data. + class MultiReceiptsDetectorV1Page < Mindee::V1::Parsing::Common::Page # @param prediction [Hash] def initialize(prediction) super @prediction = if prediction['prediction'].empty? nil else - BankAccountDetailsV1PagePrediction.new( + MultiReceiptsDetectorV1PagePrediction.new( prediction['prediction'], prediction['id'] ) @@ -23,8 +23,8 @@ def initialize(prediction) end end - # Bank Account Details V1 page prediction. - class BankAccountDetailsV1PagePrediction < BankAccountDetailsV1Document + # Multi Receipts Detector V1 page prediction. + class MultiReceiptsDetectorV1PagePrediction < MultiReceiptsDetectorV1Document # @return [String] def to_s out_str = String.new diff --git a/lib/mindee/product/fr/carte_grise/carte_grise_v1.rb b/lib/mindee/v1/product/passport/passport_v1.rb similarity index 64% rename from lib/mindee/product/fr/carte_grise/carte_grise_v1.rb rename to lib/mindee/v1/product/passport/passport_v1.rb index 72f9f9717..b2c7dd34c 100644 --- a/lib/mindee/product/fr/carte_grise/carte_grise_v1.rb +++ b/lib/mindee/v1/product/passport/passport_v1.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'carte_grise_v1_document' -require_relative 'carte_grise_v1_page' +require_relative '../../parsing' +require_relative 'passport_v1_document' +require_relative 'passport_v1_page' module Mindee - module Product - module FR - # Carte Grise module. - module CarteGrise - # Carte Grise API version 1 inference prediction. - class CarteGriseV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'carte_grise' + module V1 + module Product + # Passport module. + module Passport + # Passport API version 1 inference prediction. + class PassportV1 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'passport' @endpoint_version = '1' @has_async = false @has_sync = true @@ -19,10 +19,10 @@ class CarteGriseV1 < Mindee::Parsing::Common::Inference # @param prediction [Hash] def initialize(prediction) super - @prediction = CarteGriseV1Document.new(prediction['prediction'], nil) + @prediction = PassportV1Document.new(prediction['prediction'], nil) @pages = [] prediction['pages'].each do |page| - @pages.push(CarteGriseV1Page.new(page)) + @pages.push(PassportV1Page.new(page)) end end diff --git a/lib/mindee/product/fr/id_card/id_card_v1_document.rb b/lib/mindee/v1/product/passport/passport_v1_document.rb similarity index 56% rename from lib/mindee/product/fr/id_card/id_card_v1_document.rb rename to lib/mindee/v1/product/passport/passport_v1_document.rb index c893d907a..513a51900 100644 --- a/lib/mindee/product/fr/id_card/id_card_v1_document.rb +++ b/lib/mindee/v1/product/passport/passport_v1_document.rb @@ -1,53 +1,53 @@ # frozen_string_literal: true -require_relative '../../../parsing' +require_relative '../../parsing' module Mindee - module Product - module FR - module IdCard - # Carte Nationale d'Identité API version 1.1 document data. - class IdCardV1Document < Mindee::Parsing::Common::Prediction - include Mindee::Parsing::Standard - # The name of the issuing authority. - # @return [Mindee::Parsing::Standard::StringField] - attr_reader :authority - # The date of birth of the card holder. - # @return [Mindee::Parsing::Standard::DateField] + module V1 + module Product + module Passport + # Passport API version 1.1 document data. + class PassportV1Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # The date of birth of the passport holder. + # @return [Mindee::V1::Parsing::Standard::DateField] attr_reader :birth_date - # The place of birth of the card holder. - # @return [Mindee::Parsing::Standard::StringField] + # The place of birth of the passport holder. + # @return [Mindee::V1::Parsing::Standard::StringField] attr_reader :birth_place - # The expiry date of the identification card. - # @return [Mindee::Parsing::Standard::DateField] + # The country's 3 letter code (ISO 3166-1 alpha-3). + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :country + # The expiry date of the passport. + # @return [Mindee::V1::Parsing::Standard::DateField] attr_reader :expiry_date - # The gender of the card holder. - # @return [Mindee::Parsing::Standard::StringField] + # The gender of the passport holder. + # @return [Mindee::V1::Parsing::Standard::StringField] attr_reader :gender - # The given name(s) of the card holder. - # @return [Array] + # The given name(s) of the passport holder. + # @return [Array] attr_reader :given_names - # The identification card number. - # @return [Mindee::Parsing::Standard::StringField] + # The passport's identification number. + # @return [Mindee::V1::Parsing::Standard::StringField] attr_reader :id_number + # The date the passport was issued. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :issuance_date # Machine Readable Zone, first line - # @return [Mindee::Parsing::Standard::StringField] + # @return [Mindee::V1::Parsing::Standard::StringField] attr_reader :mrz1 # Machine Readable Zone, second line - # @return [Mindee::Parsing::Standard::StringField] + # @return [Mindee::V1::Parsing::Standard::StringField] attr_reader :mrz2 - # The surname of the card holder. - # @return [Mindee::Parsing::Standard::StringField] + # The surname of the passport holder. + # @return [Mindee::V1::Parsing::Standard::StringField] attr_reader :surname # @param prediction [Hash] # @param page_id [Integer, nil] def initialize(prediction, page_id) super - @authority = Parsing::Standard::StringField.new( - prediction['authority'], - page_id - ) @birth_date = Parsing::Standard::DateField.new( prediction['birth_date'], page_id @@ -56,6 +56,10 @@ def initialize(prediction, page_id) prediction['birth_place'], page_id ) + @country = Parsing::Standard::StringField.new( + prediction['country'], + page_id + ) @expiry_date = Parsing::Standard::DateField.new( prediction['expiry_date'], page_id @@ -72,6 +76,10 @@ def initialize(prediction, page_id) prediction['id_number'], page_id ) + @issuance_date = Parsing::Standard::DateField.new( + prediction['issuance_date'], + page_id + ) @mrz1 = Parsing::Standard::StringField.new(prediction['mrz1'], page_id) @mrz2 = Parsing::Standard::StringField.new(prediction['mrz2'], page_id) @surname = Parsing::Standard::StringField.new( @@ -84,14 +92,15 @@ def initialize(prediction, page_id) def to_s given_names = @given_names.join("\n #{' ' * 15}") out_str = String.new - out_str << "\n:Identity Number: #{@id_number}".rstrip + out_str << "\n:Country Code: #{@country}".rstrip + out_str << "\n:ID Number: #{@id_number}".rstrip out_str << "\n:Given Name(s): #{given_names}".rstrip out_str << "\n:Surname: #{@surname}".rstrip out_str << "\n:Date of Birth: #{@birth_date}".rstrip out_str << "\n:Place of Birth: #{@birth_place}".rstrip - out_str << "\n:Expiry Date: #{@expiry_date}".rstrip - out_str << "\n:Issuing Authority: #{@authority}".rstrip out_str << "\n:Gender: #{@gender}".rstrip + out_str << "\n:Date of Issue: #{@issuance_date}".rstrip + out_str << "\n:Expiry Date: #{@expiry_date}".rstrip out_str << "\n:MRZ Line 1: #{@mrz1}".rstrip out_str << "\n:MRZ Line 2: #{@mrz2}".rstrip out_str[1..].to_s diff --git a/lib/mindee/product/fr/health_card/health_card_v1_page.rb b/lib/mindee/v1/product/passport/passport_v1_page.rb similarity index 60% rename from lib/mindee/product/fr/health_card/health_card_v1_page.rb rename to lib/mindee/v1/product/passport/passport_v1_page.rb index c92dac688..0767cd015 100644 --- a/lib/mindee/product/fr/health_card/health_card_v1_page.rb +++ b/lib/mindee/v1/product/passport/passport_v1_page.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'health_card_v1_document' +require_relative '../../parsing' +require_relative 'passport_v1_document' module Mindee - module Product - module FR - module HealthCard - # Health Card API version 1.0 page data. - class HealthCardV1Page < Mindee::Parsing::Common::Page + module V1 + module Product + module Passport + # Passport API version 1.1 page data. + class PassportV1Page < Mindee::V1::Parsing::Common::Page # @param prediction [Hash] def initialize(prediction) super @prediction = if prediction['prediction'].empty? nil else - HealthCardV1PagePrediction.new( + PassportV1PagePrediction.new( prediction['prediction'], prediction['id'] ) @@ -23,8 +23,8 @@ def initialize(prediction) end end - # Health Card V1 page prediction. - class HealthCardV1PagePrediction < HealthCardV1Document + # Passport V1 page prediction. + class PassportV1PagePrediction < PassportV1Document # @return [String] def to_s out_str = String.new diff --git a/lib/mindee/v1/product/receipt/receipt_v5.rb b/lib/mindee/v1/product/receipt/receipt_v5.rb new file mode 100644 index 000000000..6fd1214e2 --- /dev/null +++ b/lib/mindee/v1/product/receipt/receipt_v5.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'receipt_v5_document' +require_relative 'receipt_v5_page' + +module Mindee + module V1 + module Product + # Receipt module. + module Receipt + # Receipt API version 5 inference prediction. + class ReceiptV5 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'expense_receipts' + @endpoint_version = '5' + @has_async = true + @has_sync = true + + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = ReceiptV5Document.new(prediction['prediction'], nil) + @pages = [] + prediction['pages'].each do |page| + @pages.push(ReceiptV5Page.new(page)) + end + end + + class << self + # Name of the endpoint for this product. + # @return [String] + attr_reader :endpoint_name + # Version for this product. + # @return [String] + attr_reader :endpoint_version + # Whether this product has access to an asynchronous endpoint. + # @return [bool] + attr_reader :has_async + # Whether this product has access to synchronous endpoint. + # @return [bool] + attr_reader :has_sync + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/receipt/receipt_v5_document.rb b/lib/mindee/v1/product/receipt/receipt_v5_document.rb new file mode 100644 index 000000000..fff10708b --- /dev/null +++ b/lib/mindee/v1/product/receipt/receipt_v5_document.rb @@ -0,0 +1,187 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'receipt_v5_line_items' + +module Mindee + module V1 + module Product + module Receipt + # Receipt API version 5.4 document data. + class ReceiptV5Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # The purchase category of the receipt. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :category + # The date the purchase was made. + # @return [Mindee::V1::Parsing::Standard::DateField] + attr_reader :date + # The type of receipt: EXPENSE RECEIPT or CREDIT CARD RECEIPT. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :document_type + # List of all line items on the receipt. + # @return [Mindee::V1::Product::Receipt::ReceiptV5LineItems] + attr_reader :line_items + # The locale of the document. + # @return [Mindee::V1::Parsing::Standard::LocaleField] + attr_reader :locale + # The receipt number or identifier. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :receipt_number + # The purchase subcategory of the receipt for transport and food. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :subcategory + # The address of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_address + # List of company registration numbers associated to the supplier. + # @return [Array] + attr_reader :supplier_company_registrations + # The name of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_name + # The phone number of the supplier or merchant. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :supplier_phone_number + # The list of taxes present on the receipt. + # @return [Mindee::V1::Parsing::Standard::Taxes] + attr_reader :taxes + # The time the purchase was made. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :time + # The total amount of tip and gratuity. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :tip + # The total amount paid: includes taxes, discounts, fees, tips, and gratuity. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_amount + # The net amount paid: does not include taxes, fees, and discounts. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_net + # The sum of all taxes. + # @return [Mindee::V1::Parsing::Standard::AmountField] + attr_reader :total_tax + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @category = Parsing::Standard::ClassificationField.new( + prediction['category'], + page_id + ) + @date = Parsing::Standard::DateField.new(prediction['date'], page_id) + @document_type = Parsing::Standard::ClassificationField.new( + prediction['document_type'], + page_id + ) + @line_items = Product::Receipt::ReceiptV5LineItems.new(prediction['line_items'], page_id) + @locale = Parsing::Standard::LocaleField.new( + prediction['locale'], + page_id + ) + @receipt_number = Parsing::Standard::StringField.new( + prediction['receipt_number'], + page_id + ) + @subcategory = Parsing::Standard::ClassificationField.new( + prediction['subcategory'], + page_id + ) + @supplier_address = Parsing::Standard::StringField.new( + prediction['supplier_address'], + page_id + ) + @supplier_company_registrations = [] # : Array[Parsing::Standard::CompanyRegistrationField] + prediction['supplier_company_registrations'].each do |item| + @supplier_company_registrations.push(Parsing::Standard::CompanyRegistrationField.new(item, page_id)) + end + @supplier_name = Parsing::Standard::StringField.new( + prediction['supplier_name'], + page_id + ) + @supplier_phone_number = Parsing::Standard::StringField.new( + prediction['supplier_phone_number'], + page_id + ) + @taxes = Parsing::Standard::Taxes.new(prediction['taxes'], page_id) + @time = Parsing::Standard::StringField.new(prediction['time'], page_id) + @tip = Parsing::Standard::AmountField.new(prediction['tip'], page_id) + @total_amount = Parsing::Standard::AmountField.new( + prediction['total_amount'], + page_id + ) + @total_net = Parsing::Standard::AmountField.new( + prediction['total_net'], + page_id + ) + @total_tax = Parsing::Standard::AmountField.new( + prediction['total_tax'], + page_id + ) + end + + # @return [String] + def to_s + supplier_company_registrations = @supplier_company_registrations.join("\n #{' ' * 32}") + line_items = line_items_to_s + out_str = String.new + out_str << "\n:Expense Locale: #{@locale}".rstrip + out_str << "\n:Purchase Category: #{@category}".rstrip + out_str << "\n:Purchase Subcategory: #{@subcategory}".rstrip + out_str << "\n:Document Type: #{@document_type}".rstrip + out_str << "\n:Purchase Date: #{@date}".rstrip + out_str << "\n:Purchase Time: #{@time}".rstrip + out_str << "\n:Total Amount: #{@total_amount}".rstrip + out_str << "\n:Total Net: #{@total_net}".rstrip + out_str << "\n:Total Tax: #{@total_tax}".rstrip + out_str << "\n:Tip and Gratuity: #{@tip}".rstrip + out_str << "\n:Taxes:#{@taxes}".rstrip + out_str << "\n:Supplier Name: #{@supplier_name}".rstrip + out_str << "\n:Supplier Company Registrations: #{supplier_company_registrations}".rstrip + out_str << "\n:Supplier Address: #{@supplier_address}".rstrip + out_str << "\n:Supplier Phone Number: #{@supplier_phone_number}".rstrip + out_str << "\n:Receipt Number: #{@receipt_number}".rstrip + out_str << "\n:Line Items:" + out_str << line_items + out_str[1..].to_s + end + + private + + # @param char [String] + # @return [String] + def line_items_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 38}" + out_str << "+#{char * 10}" + out_str << "+#{char * 14}" + out_str << "+#{char * 12}" + out_str << '+' + out_str + end + + # @return [String] + def line_items_to_s + return '' if @line_items.empty? + + line_items = @line_items.map(&:to_table_line).join("\n#{line_items_separator('-')}\n ") + out_str = String.new + out_str << "\n#{line_items_separator('-')}" + out_str << "\n |" + out_str << ' Description |' + out_str << ' Quantity |' + out_str << ' Total Amount |' + out_str << ' Unit Price |' + out_str << "\n#{line_items_separator('=')}" + out_str << "\n #{line_items}" + out_str << "\n#{line_items_separator('-')}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/receipt/receipt_v5_line_item.rb b/lib/mindee/v1/product/receipt/receipt_v5_line_item.rb new file mode 100644 index 000000000..dd7964af7 --- /dev/null +++ b/lib/mindee/v1/product/receipt/receipt_v5_line_item.rb @@ -0,0 +1,88 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module Receipt + # List of all line items on the receipt. + class ReceiptV5LineItem < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # The item description. + # @return [String] + attr_reader :description + # The item quantity. + # @return [Float] + attr_reader :quantity + # The item total amount. + # @return [Float] + attr_reader :total_amount + # The item unit price. + # @return [Float] + attr_reader :unit_price + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @description = prediction['description'] + @quantity = prediction['quantity'] + @total_amount = prediction['total_amount'] + @unit_price = prediction['unit_price'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:description] = format_for_display(@description) + printable[:quantity] = + @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) + printable[:total_amount] = + @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) + printable[:unit_price] = + @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) + printable + end + + # @return [Hash] + def table_printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:description] = format_for_display(@description, 36) + printable[:quantity] = + @quantity.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@quantity) + printable[:total_amount] = + @total_amount.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@total_amount) + printable[:unit_price] = + @unit_price.nil? ? '' : Parsing::Standard::BaseField.float_to_string(@unit_price) + printable + end + + # @return [String] + def to_table_line + printable = table_printable_values + out_str = String.new + out_str << format('| %- 37s', printable[:description]) + out_str << format('| %- 9s', printable[:quantity]) + out_str << format('| %- 13s', printable[:total_amount]) + out_str << format('| %- 11s', printable[:unit_price]) + out_str << '|' + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Description: #{printable[:description]}" + out_str << "\n :Quantity: #{printable[:quantity]}" + out_str << "\n :Total Amount: #{printable[:total_amount]}" + out_str << "\n :Unit Price: #{printable[:unit_price]}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/bank_statement/bank_statement_v2_transactions.rb b/lib/mindee/v1/product/receipt/receipt_v5_line_items.rb similarity index 70% rename from lib/mindee/product/fr/bank_statement/bank_statement_v2_transactions.rb rename to lib/mindee/v1/product/receipt/receipt_v5_line_items.rb index b45980d8c..c46de5ba1 100644 --- a/lib/mindee/product/fr/bank_statement/bank_statement_v2_transactions.rb +++ b/lib/mindee/v1/product/receipt/receipt_v5_line_items.rb @@ -1,22 +1,22 @@ # frozen_string_literal: true -require_relative 'bank_statement_v2_transaction' +require_relative 'receipt_v5_line_item' module Mindee - module Product - module FR - module BankStatement - # The list of values that represent the financial transactions recorded in a bank statement. - class BankStatementV2Transactions < Array + module V1 + module Product + module Receipt + # List of all line items on the receipt. + class ReceiptV5LineItems < Array # Entries. - # @return [Array] + # @return [Array] attr_reader :entries # @param prediction [Array] # @param page_id [Integer, nil] def initialize(prediction, page_id) entries = prediction.map do |entry| - BankStatement::BankStatementV2Transaction.new(entry, page_id) + Receipt::ReceiptV5LineItem.new(entry, page_id) end super(entries) end @@ -26,9 +26,10 @@ def initialize(prediction, page_id) # @return [String] def self.line_items_separator(char) out_str = String.new - out_str << "+#{char * 12}" - out_str << "+#{char * 12}" out_str << "+#{char * 38}" + out_str << "+#{char * 10}" + out_str << "+#{char * 14}" + out_str << "+#{char * 12}" out_str end @@ -41,9 +42,10 @@ def to_s end.join out_str = String.new out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Amount ' - out_str << ' | Date ' out_str << ' | Description ' + out_str << ' | Quantity' + out_str << ' | Total Amount' + out_str << ' | Unit Price' out_str << " |\n#{self.class.line_items_separator('=')}" out_str + lines end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_page.rb b/lib/mindee/v1/product/receipt/receipt_v5_page.rb similarity index 62% rename from lib/mindee/product/fr/payslip/payslip_v3_page.rb rename to lib/mindee/v1/product/receipt/receipt_v5_page.rb index cac295bf1..ad6fcf12a 100644 --- a/lib/mindee/product/fr/payslip/payslip_v3_page.rb +++ b/lib/mindee/v1/product/receipt/receipt_v5_page.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'payslip_v3_document' +require_relative '../../parsing' +require_relative 'receipt_v5_document' module Mindee - module Product - module FR - module Payslip - # Payslip API version 3.0 page data. - class PayslipV3Page < Mindee::Parsing::Common::Page + module V1 + module Product + module Receipt + # Receipt API version 5.4 page data. + class ReceiptV5Page < Mindee::V1::Parsing::Common::Page # @param prediction [Hash] def initialize(prediction) super @prediction = if prediction['prediction'].empty? nil else - PayslipV3PagePrediction.new( + ReceiptV5PagePrediction.new( prediction['prediction'], prediction['id'] ) @@ -23,8 +23,8 @@ def initialize(prediction) end end - # Payslip V3 page prediction. - class PayslipV3PagePrediction < PayslipV3Document + # Receipt V5 page prediction. + class ReceiptV5PagePrediction < ReceiptV5Document # @return [String] def to_s out_str = String.new diff --git a/lib/mindee/product/us/us_mail/us_mail_v3.rb b/lib/mindee/v1/product/resume/resume_v1.rb similarity index 64% rename from lib/mindee/product/us/us_mail/us_mail_v3.rb rename to lib/mindee/v1/product/resume/resume_v1.rb index 025576973..8bf77da32 100644 --- a/lib/mindee/product/us/us_mail/us_mail_v3.rb +++ b/lib/mindee/v1/product/resume/resume_v1.rb @@ -1,28 +1,28 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'us_mail_v3_document' -require_relative 'us_mail_v3_page' +require_relative '../../parsing' +require_relative 'resume_v1_document' +require_relative 'resume_v1_page' module Mindee - module Product - module US - # US Mail module. - module UsMail - # US Mail API version 3 inference prediction. - class UsMailV3 < Mindee::Parsing::Common::Inference - @endpoint_name = 'us_mail' - @endpoint_version = '3' + module V1 + module Product + # Resume module. + module Resume + # Resume API version 1 inference prediction. + class ResumeV1 < Mindee::V1::Parsing::Common::Inference + @endpoint_name = 'resume' + @endpoint_version = '1' @has_async = true @has_sync = false # @param prediction [Hash] def initialize(prediction) super - @prediction = UsMailV3Document.new(prediction['prediction'], nil) + @prediction = ResumeV1Document.new(prediction['prediction'], nil) @pages = [] prediction['pages'].each do |page| - @pages.push(UsMailV3Page.new(page)) + @pages.push(ResumeV1Page.new(page)) end end diff --git a/lib/mindee/v1/product/resume/resume_v1_certificate.rb b/lib/mindee/v1/product/resume/resume_v1_certificate.rb new file mode 100644 index 000000000..c0af21f6b --- /dev/null +++ b/lib/mindee/v1/product/resume/resume_v1_certificate.rb @@ -0,0 +1,82 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module Resume + # The list of certificates obtained by the candidate. + class ResumeV1Certificate < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # The grade obtained for the certificate. + # @return [String] + attr_reader :grade + # The name of certification. + # @return [String] + attr_reader :name + # The organization or institution that issued the certificate. + # @return [String] + attr_reader :provider + # The year when a certificate was issued or received. + # @return [String] + attr_reader :year + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @grade = prediction['grade'] + @name = prediction['name'] + @provider = prediction['provider'] + @year = prediction['year'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:grade] = format_for_display(@grade) + printable[:name] = format_for_display(@name) + printable[:provider] = format_for_display(@provider) + printable[:year] = format_for_display(@year) + printable + end + + # @return [Hash] + def table_printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:grade] = format_for_display(@grade, 10) + printable[:name] = format_for_display(@name, 30) + printable[:provider] = format_for_display(@provider, 25) + printable[:year] = format_for_display(@year, nil) + printable + end + + # @return [String] + def to_table_line + printable = table_printable_values + out_str = String.new + out_str << format('| %- 11s', printable[:grade]) + out_str << format('| %- 31s', printable[:name]) + out_str << format('| %- 26s', printable[:provider]) + out_str << format('| %- 5s', printable[:year]) + out_str << '|' + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Grade: #{printable[:grade]}" + out_str << "\n :Name: #{printable[:name]}" + out_str << "\n :Provider: #{printable[:provider]}" + out_str << "\n :Year: #{printable[:year]}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_paid_time_offs.rb b/lib/mindee/v1/product/resume/resume_v1_certificates.rb similarity index 52% rename from lib/mindee/product/fr/payslip/payslip_v3_paid_time_offs.rb rename to lib/mindee/v1/product/resume/resume_v1_certificates.rb index b1b280fa7..713856bb2 100644 --- a/lib/mindee/product/fr/payslip/payslip_v3_paid_time_offs.rb +++ b/lib/mindee/v1/product/resume/resume_v1_certificates.rb @@ -1,29 +1,26 @@ # frozen_string_literal: true -require_relative 'payslip_v3_pay_period' -require_relative 'payslip_v3_employee' -require_relative 'payslip_v3_employer' -require_relative 'payslip_v3_bank_account_detail' -require_relative 'payslip_v3_employment' -require_relative 'payslip_v3_salary_detail' -require_relative 'payslip_v3_pay_detail' -require_relative 'payslip_v3_paid_time_off' +require_relative 'resume_v1_social_networks_url' +require_relative 'resume_v1_language' +require_relative 'resume_v1_education' +require_relative 'resume_v1_professional_experience' +require_relative 'resume_v1_certificate' module Mindee - module Product - module FR - module Payslip - # Information about paid time off. - class PayslipV3PaidTimeOffs < Array + module V1 + module Product + module Resume + # The list of certificates obtained by the candidate. + class ResumeV1Certificates < Array # Entries. - # @return [Array] + # @return [Array] attr_reader :entries # @param prediction [Array] # @param page_id [Integer, nil] def initialize(prediction, page_id) entries = prediction.map do |entry| - Payslip::PayslipV3PaidTimeOff.new(entry, page_id) + Resume::ResumeV1Certificate.new(entry, page_id) end super(entries) end @@ -33,11 +30,10 @@ def initialize(prediction, page_id) # @return [String] def self.line_items_separator(char) out_str = String.new - out_str << "+#{char * 11}" - out_str << "+#{char * 8}" - out_str << "+#{char * 13}" - out_str << "+#{char * 11}" - out_str << "+#{char * 11}" + out_str << "+#{char * 12}" + out_str << "+#{char * 32}" + out_str << "+#{char * 27}" + out_str << "+#{char * 6}" out_str end @@ -50,11 +46,10 @@ def to_s end.join out_str = String.new out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Accrued ' - out_str << ' | Period' - out_str << ' | Type ' - out_str << ' | Remaining' - out_str << ' | Used ' + out_str << ' | Grade ' + out_str << ' | Name ' + out_str << ' | Provider ' + out_str << ' | Year' out_str << " |\n#{self.class.line_items_separator('=')}" out_str + lines end diff --git a/lib/mindee/v1/product/resume/resume_v1_document.rb b/lib/mindee/v1/product/resume/resume_v1_document.rb new file mode 100644 index 000000000..33050a9a4 --- /dev/null +++ b/lib/mindee/v1/product/resume/resume_v1_document.rb @@ -0,0 +1,340 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'resume_v1_social_networks_urls' +require_relative 'resume_v1_languages' +require_relative 'resume_v1_educations' +require_relative 'resume_v1_professional_experiences' +require_relative 'resume_v1_certificates' + +module Mindee + module V1 + module Product + module Resume + # Resume API version 1.2 document data. + class ResumeV1Document < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Standard + + # The location information of the candidate, including city, state, and country. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :address + # The list of certificates obtained by the candidate. + # @return [Mindee::V1::Product::Resume::ResumeV1Certificates] + attr_reader :certificates + # The ISO 639 code of the language in which the document is written. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :document_language + # The type of the document sent. + # @return [Mindee::V1::Parsing::Standard::ClassificationField] + attr_reader :document_type + # The list of the candidate's educational background. + # @return [Mindee::V1::Product::Resume::ResumeV1Educations] + attr_reader :education + # The email address of the candidate. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :email_address + # The candidate's first or given names. + # @return [Array] + attr_reader :given_names + # The list of the candidate's technical abilities and knowledge. + # @return [Array] + attr_reader :hard_skills + # The position that the candidate is applying for. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :job_applied + # The list of languages that the candidate is proficient in. + # @return [Mindee::V1::Product::Resume::ResumeV1Languages] + attr_reader :languages + # The ISO 3166 code for the country of citizenship of the candidate. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :nationality + # The phone number of the candidate. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :phone_number + # The candidate's current profession. + # @return [Mindee::V1::Parsing::Standard::StringField] + attr_reader :profession + # The list of the candidate's professional experiences. + # @return [Mindee::V1::Product::Resume::ResumeV1ProfessionalExperiences] + attr_reader :professional_experiences + # The list of social network profiles of the candidate. + # @return [Mindee::V1::Product::Resume::ResumeV1SocialNetworksUrls] + attr_reader :social_networks_urls + # The list of the candidate's interpersonal and communication abilities. + # @return [Array] + attr_reader :soft_skills + # The candidate's last names. + # @return [Array] + attr_reader :surnames + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @address = Parsing::Standard::StringField.new( + prediction['address'], + page_id + ) + @certificates = Product::Resume::ResumeV1Certificates.new(prediction['certificates'], page_id) + @document_language = Parsing::Standard::StringField.new( + prediction['document_language'], + page_id + ) + @document_type = Parsing::Standard::ClassificationField.new( + prediction['document_type'], + page_id + ) + @education = Product::Resume::ResumeV1Educations.new(prediction['education'], page_id) + @email_address = Parsing::Standard::StringField.new( + prediction['email_address'], + page_id + ) + @given_names = [] # : Array[Parsing::Standard::StringField] + prediction['given_names'].each do |item| + @given_names.push(Parsing::Standard::StringField.new(item, page_id)) + end + @hard_skills = [] # : Array[Parsing::Standard::StringField] + prediction['hard_skills'].each do |item| + @hard_skills.push(Parsing::Standard::StringField.new(item, page_id)) + end + @job_applied = Parsing::Standard::StringField.new( + prediction['job_applied'], + page_id + ) + @languages = Product::Resume::ResumeV1Languages.new(prediction['languages'], page_id) + @nationality = Parsing::Standard::StringField.new( + prediction['nationality'], + page_id + ) + @phone_number = Parsing::Standard::StringField.new( + prediction['phone_number'], + page_id + ) + @profession = Parsing::Standard::StringField.new( + prediction['profession'], + page_id + ) + @professional_experiences = Product::Resume::ResumeV1ProfessionalExperiences.new( + prediction['professional_experiences'], page_id + ) + @social_networks_urls = Product::Resume::ResumeV1SocialNetworksUrls.new( + prediction['social_networks_urls'], page_id + ) + @soft_skills = [] # : Array[Parsing::Standard::StringField] + prediction['soft_skills'].each do |item| + @soft_skills.push(Parsing::Standard::StringField.new(item, page_id)) + end + @surnames = [] # : Array[Parsing::Standard::StringField] + prediction['surnames'].each do |item| + @surnames.push(Parsing::Standard::StringField.new(item, page_id)) + end + end + + # @return [String] + def to_s + given_names = @given_names.join("\n #{' ' * 13}") + surnames = @surnames.join("\n #{' ' * 10}") + social_networks_urls = social_networks_urls_to_s + languages = languages_to_s + hard_skills = @hard_skills.join("\n #{' ' * 13}") + soft_skills = @soft_skills.join("\n #{' ' * 13}") + education = education_to_s + professional_experiences = professional_experiences_to_s + certificates = certificates_to_s + out_str = String.new + out_str << "\n:Document Language: #{@document_language}".rstrip + out_str << "\n:Document Type: #{@document_type}".rstrip + out_str << "\n:Given Names: #{given_names}".rstrip + out_str << "\n:Surnames: #{surnames}".rstrip + out_str << "\n:Nationality: #{@nationality}".rstrip + out_str << "\n:Email Address: #{@email_address}".rstrip + out_str << "\n:Phone Number: #{@phone_number}".rstrip + out_str << "\n:Address: #{@address}".rstrip + out_str << "\n:Social Networks:" + out_str << social_networks_urls + out_str << "\n:Profession: #{@profession}".rstrip + out_str << "\n:Job Applied: #{@job_applied}".rstrip + out_str << "\n:Languages:" + out_str << languages + out_str << "\n:Hard Skills: #{hard_skills}".rstrip + out_str << "\n:Soft Skills: #{soft_skills}".rstrip + out_str << "\n:Education:" + out_str << education + out_str << "\n:Professional Experiences:" + out_str << professional_experiences + out_str << "\n:Certificates:" + out_str << certificates + out_str[1..].to_s + end + + private + + # @param char [String] + # @return [String] + def social_networks_urls_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 22}" + out_str << "+#{char * 52}" + out_str << '+' + out_str + end + + # @return [String] + def social_networks_urls_to_s + return '' if @social_networks_urls.empty? + + line_items = @social_networks_urls.map(&:to_table_line).join("\n#{social_networks_urls_separator('-')}\n ") + out_str = String.new + out_str << "\n#{social_networks_urls_separator('-')}" + out_str << "\n |" + out_str << ' Name |' + out_str << ' URL |' + out_str << "\n#{social_networks_urls_separator('=')}" + out_str << "\n #{line_items}" + out_str << "\n#{social_networks_urls_separator('-')}" + out_str + end + + # @param char [String] + # @return [String] + def languages_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 10}" + out_str << "+#{char * 22}" + out_str << '+' + out_str + end + + # @return [String] + def languages_to_s + return '' if @languages.empty? + + line_items = @languages.map(&:to_table_line).join("\n#{languages_separator('-')}\n ") + out_str = String.new + out_str << "\n#{languages_separator('-')}" + out_str << "\n |" + out_str << ' Language |' + out_str << ' Level |' + out_str << "\n#{languages_separator('=')}" + out_str << "\n #{line_items}" + out_str << "\n#{languages_separator('-')}" + out_str + end + + # @param char [String] + # @return [String] + def education_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 17}" + out_str << "+#{char * 27}" + out_str << "+#{char * 11}" + out_str << "+#{char * 10}" + out_str << "+#{char * 27}" + out_str << "+#{char * 13}" + out_str << "+#{char * 12}" + out_str << '+' + out_str + end + + # @return [String] + def education_to_s + return '' if @education.empty? + + line_items = @education.map(&:to_table_line).join("\n#{education_separator('-')}\n ") + out_str = String.new + out_str << "\n#{education_separator('-')}" + out_str << "\n |" + out_str << ' Domain |' + out_str << ' Degree |' + out_str << ' End Month |' + out_str << ' End Year |' + out_str << ' School |' + out_str << ' Start Month |' + out_str << ' Start Year |' + out_str << "\n#{education_separator('=')}" + out_str << "\n #{line_items}" + out_str << "\n#{education_separator('-')}" + out_str + end + + # @param char [String] + # @return [String] + def professional_experiences_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 17}" + out_str << "+#{char * 12}" + out_str << "+#{char * 38}" + out_str << "+#{char * 27}" + out_str << "+#{char * 11}" + out_str << "+#{char * 10}" + out_str << "+#{char * 22}" + out_str << "+#{char * 13}" + out_str << "+#{char * 12}" + out_str << '+' + out_str + end + + # @return [String] + def professional_experiences_to_s + return '' if @professional_experiences.empty? + + line_items = @professional_experiences.map(&:to_table_line).join( + "\n#{professional_experiences_separator('-')}\n " + ) + out_str = String.new + out_str << "\n#{professional_experiences_separator('-')}" + out_str << "\n |" + out_str << ' Contract Type |' + out_str << ' Department |' + out_str << ' Description |' + out_str << ' Employer |' + out_str << ' End Month |' + out_str << ' End Year |' + out_str << ' Role |' + out_str << ' Start Month |' + out_str << ' Start Year |' + out_str << "\n#{professional_experiences_separator('=')}" + out_str << "\n #{line_items}" + out_str << "\n#{professional_experiences_separator('-')}" + out_str + end + + # @param char [String] + # @return [String] + def certificates_separator(char) + out_str = String.new + out_str << ' ' + out_str << "+#{char * 12}" + out_str << "+#{char * 32}" + out_str << "+#{char * 27}" + out_str << "+#{char * 6}" + out_str << '+' + out_str + end + + # @return [String] + def certificates_to_s + return '' if @certificates.empty? + + line_items = @certificates.map(&:to_table_line).join("\n#{certificates_separator('-')}\n ") + out_str = String.new + out_str << "\n#{certificates_separator('-')}" + out_str << "\n |" + out_str << ' Grade |' + out_str << ' Name |' + out_str << ' Provider |' + out_str << ' Year |' + out_str << "\n#{certificates_separator('=')}" + out_str << "\n #{line_items}" + out_str << "\n#{certificates_separator('-')}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/resume/resume_v1_education.rb b/lib/mindee/v1/product/resume/resume_v1_education.rb new file mode 100644 index 000000000..adbd06400 --- /dev/null +++ b/lib/mindee/v1/product/resume/resume_v1_education.rb @@ -0,0 +1,106 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module Resume + # The list of the candidate's educational background. + class ResumeV1Education < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # The area of study or specialization. + # @return [String] + attr_reader :degree_domain + # The type of degree obtained, such as Bachelor's, Master's, or Doctorate. + # @return [String] + attr_reader :degree_type + # The month when the education program or course was completed. + # @return [String] + attr_reader :end_month + # The year when the education program or course was completed. + # @return [String] + attr_reader :end_year + # The name of the school. + # @return [String] + attr_reader :school + # The month when the education program or course began. + # @return [String] + attr_reader :start_month + # The year when the education program or course began. + # @return [String] + attr_reader :start_year + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @degree_domain = prediction['degree_domain'] + @degree_type = prediction['degree_type'] + @end_month = prediction['end_month'] + @end_year = prediction['end_year'] + @school = prediction['school'] + @start_month = prediction['start_month'] + @start_year = prediction['start_year'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:degree_domain] = format_for_display(@degree_domain) + printable[:degree_type] = format_for_display(@degree_type) + printable[:end_month] = format_for_display(@end_month) + printable[:end_year] = format_for_display(@end_year) + printable[:school] = format_for_display(@school) + printable[:start_month] = format_for_display(@start_month) + printable[:start_year] = format_for_display(@start_year) + printable + end + + # @return [Hash] + def table_printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:degree_domain] = format_for_display(@degree_domain, 15) + printable[:degree_type] = format_for_display(@degree_type, 25) + printable[:end_month] = format_for_display(@end_month, nil) + printable[:end_year] = format_for_display(@end_year, nil) + printable[:school] = format_for_display(@school, 25) + printable[:start_month] = format_for_display(@start_month, nil) + printable[:start_year] = format_for_display(@start_year, nil) + printable + end + + # @return [String] + def to_table_line + printable = table_printable_values + out_str = String.new + out_str << format('| %- 16s', printable[:degree_domain]) + out_str << format('| %- 26s', printable[:degree_type]) + out_str << format('| %- 10s', printable[:end_month]) + out_str << format('| %- 9s', printable[:end_year]) + out_str << format('| %- 26s', printable[:school]) + out_str << format('| %- 12s', printable[:start_month]) + out_str << format('| %- 11s', printable[:start_year]) + out_str << '|' + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Domain: #{printable[:degree_domain]}" + out_str << "\n :Degree: #{printable[:degree_type]}" + out_str << "\n :End Month: #{printable[:end_month]}" + out_str << "\n :End Year: #{printable[:end_year]}" + out_str << "\n :School: #{printable[:school]}" + out_str << "\n :Start Month: #{printable[:start_month]}" + out_str << "\n :Start Year: #{printable[:start_year]}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/product/us/us_mail/us_mail_v3_recipient_addresses.rb b/lib/mindee/v1/product/resume/resume_v1_educations.rb similarity index 56% rename from lib/mindee/product/us/us_mail/us_mail_v3_recipient_addresses.rb rename to lib/mindee/v1/product/resume/resume_v1_educations.rb index 2bd0cbd53..29678070a 100644 --- a/lib/mindee/product/us/us_mail/us_mail_v3_recipient_addresses.rb +++ b/lib/mindee/v1/product/resume/resume_v1_educations.rb @@ -1,23 +1,26 @@ # frozen_string_literal: true -require_relative 'us_mail_v3_sender_address' -require_relative 'us_mail_v3_recipient_address' +require_relative 'resume_v1_social_networks_url' +require_relative 'resume_v1_language' +require_relative 'resume_v1_education' +require_relative 'resume_v1_professional_experience' +require_relative 'resume_v1_certificate' module Mindee - module Product - module US - module UsMail - # The addresses of the recipients. - class UsMailV3RecipientAddresses < Array + module V1 + module Product + module Resume + # The list of the candidate's educational background. + class ResumeV1Educations < Array # Entries. - # @return [Array] + # @return [Array] attr_reader :entries # @param prediction [Array] # @param page_id [Integer, nil] def initialize(prediction, page_id) entries = prediction.map do |entry| - UsMail::UsMailV3RecipientAddress.new(entry, page_id) + Resume::ResumeV1Education.new(entry, page_id) end super(entries) end @@ -28,13 +31,12 @@ def initialize(prediction, page_id) def self.line_items_separator(char) out_str = String.new out_str << "+#{char * 17}" - out_str << "+#{char * 37}" - out_str << "+#{char * 19}" - out_str << "+#{char * 13}" - out_str << "+#{char * 24}" - out_str << "+#{char * 7}" out_str << "+#{char * 27}" - out_str << "+#{char * 17}" + out_str << "+#{char * 11}" + out_str << "+#{char * 10}" + out_str << "+#{char * 27}" + out_str << "+#{char * 13}" + out_str << "+#{char * 12}" out_str end @@ -47,14 +49,13 @@ def to_s end.join out_str = String.new out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | City ' - out_str << ' | Complete Address ' - out_str << ' | Is Address Change' - out_str << ' | Postal Code' - out_str << ' | Private Mailbox Number' - out_str << ' | State' - out_str << ' | Street ' - out_str << ' | Unit ' + out_str << ' | Domain ' + out_str << ' | Degree ' + out_str << ' | End Month' + out_str << ' | End Year' + out_str << ' | School ' + out_str << ' | Start Month' + out_str << ' | Start Year' out_str << " |\n#{self.class.line_items_separator('=')}" out_str + lines end diff --git a/lib/mindee/v1/product/resume/resume_v1_language.rb b/lib/mindee/v1/product/resume/resume_v1_language.rb new file mode 100644 index 000000000..0eb9b49ff --- /dev/null +++ b/lib/mindee/v1/product/resume/resume_v1_language.rb @@ -0,0 +1,66 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module Resume + # The list of languages that the candidate is proficient in. + class ResumeV1Language < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # The language's ISO 639 code. + # @return [String] + attr_reader :language + # The candidate's level for the language. + # @return [String] + attr_reader :level + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @language = prediction['language'] + @level = prediction['level'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:language] = format_for_display(@language) + printable[:level] = format_for_display(@level) + printable + end + + # @return [Hash] + def table_printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:language] = format_for_display(@language, nil) + printable[:level] = format_for_display(@level, 20) + printable + end + + # @return [String] + def to_table_line + printable = table_printable_values + out_str = String.new + out_str << format('| %- 9s', printable[:language]) + out_str << format('| %- 21s', printable[:level]) + out_str << '|' + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Language: #{printable[:language]}" + out_str << "\n :Level: #{printable[:level]}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/resume/resume_v1_languages.rb b/lib/mindee/v1/product/resume/resume_v1_languages.rb new file mode 100644 index 000000000..c0e0b77ce --- /dev/null +++ b/lib/mindee/v1/product/resume/resume_v1_languages.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require_relative 'resume_v1_social_networks_url' +require_relative 'resume_v1_language' +require_relative 'resume_v1_education' +require_relative 'resume_v1_professional_experience' +require_relative 'resume_v1_certificate' + +module Mindee + module V1 + module Product + module Resume + # The list of languages that the candidate is proficient in. + class ResumeV1Languages < Array + # Entries. + # @return [Array] + attr_reader :entries + + # @param prediction [Array] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + entries = prediction.map do |entry| + Resume::ResumeV1Language.new(entry, page_id) + end + super(entries) + end + + # Creates a line of rST table-compliant string separators. + # @param char [String] Character to use as a separator. + # @return [String] + def self.line_items_separator(char) + out_str = String.new + out_str << "+#{char * 10}" + out_str << "+#{char * 22}" + out_str + end + + # @return [String] + def to_s + return '' if empty? + + lines = map do |entry| + "\n #{entry.to_table_line}\n#{self.class.line_items_separator('-')}" + end.join + out_str = String.new + out_str << "\n#{self.class.line_items_separator('-')}\n " + out_str << ' | Language' + out_str << ' | Level ' + out_str << " |\n#{self.class.line_items_separator('=')}" + out_str + lines + end + end + end + end + end +end diff --git a/lib/mindee/product/us/us_mail/us_mail_v3_page.rb b/lib/mindee/v1/product/resume/resume_v1_page.rb similarity index 62% rename from lib/mindee/product/us/us_mail/us_mail_v3_page.rb rename to lib/mindee/v1/product/resume/resume_v1_page.rb index 6241c3251..cbe6b43f8 100644 --- a/lib/mindee/product/us/us_mail/us_mail_v3_page.rb +++ b/lib/mindee/v1/product/resume/resume_v1_page.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'us_mail_v3_document' +require_relative '../../parsing' +require_relative 'resume_v1_document' module Mindee - module Product - module US - module UsMail - # US Mail API version 3.0 page data. - class UsMailV3Page < Mindee::Parsing::Common::Page + module V1 + module Product + module Resume + # Resume API version 1.2 page data. + class ResumeV1Page < Mindee::V1::Parsing::Common::Page # @param prediction [Hash] def initialize(prediction) super @prediction = if prediction['prediction'].empty? nil else - UsMailV3PagePrediction.new( + ResumeV1PagePrediction.new( prediction['prediction'], prediction['id'] ) @@ -23,8 +23,8 @@ def initialize(prediction) end end - # US Mail V3 page prediction. - class UsMailV3PagePrediction < UsMailV3Document + # Resume V1 page prediction. + class ResumeV1PagePrediction < ResumeV1Document # @return [String] def to_s out_str = String.new diff --git a/lib/mindee/v1/product/resume/resume_v1_professional_experience.rb b/lib/mindee/v1/product/resume/resume_v1_professional_experience.rb new file mode 100644 index 000000000..769c4afcf --- /dev/null +++ b/lib/mindee/v1/product/resume/resume_v1_professional_experience.rb @@ -0,0 +1,122 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module Resume + # The list of the candidate's professional experiences. + class ResumeV1ProfessionalExperience < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # The type of contract for the professional experience. + # @return [String] + attr_reader :contract_type + # The specific department or division within the company. + # @return [String] + attr_reader :department + # The description of the professional experience as written in the document. + # @return [String] + attr_reader :description + # The name of the company or organization. + # @return [String] + attr_reader :employer + # The month when the professional experience ended. + # @return [String] + attr_reader :end_month + # The year when the professional experience ended. + # @return [String] + attr_reader :end_year + # The position or job title held by the candidate. + # @return [String] + attr_reader :role + # The month when the professional experience began. + # @return [String] + attr_reader :start_month + # The year when the professional experience began. + # @return [String] + attr_reader :start_year + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @contract_type = prediction['contract_type'] + @department = prediction['department'] + @description = prediction['description'] + @employer = prediction['employer'] + @end_month = prediction['end_month'] + @end_year = prediction['end_year'] + @role = prediction['role'] + @start_month = prediction['start_month'] + @start_year = prediction['start_year'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:contract_type] = format_for_display(@contract_type) + printable[:department] = format_for_display(@department) + printable[:description] = format_for_display(@description) + printable[:employer] = format_for_display(@employer) + printable[:end_month] = format_for_display(@end_month) + printable[:end_year] = format_for_display(@end_year) + printable[:role] = format_for_display(@role) + printable[:start_month] = format_for_display(@start_month) + printable[:start_year] = format_for_display(@start_year) + printable + end + + # @return [Hash] + def table_printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:contract_type] = format_for_display(@contract_type, 15) + printable[:department] = format_for_display(@department, 10) + printable[:description] = format_for_display(@description, 36) + printable[:employer] = format_for_display(@employer, 25) + printable[:end_month] = format_for_display(@end_month, nil) + printable[:end_year] = format_for_display(@end_year, nil) + printable[:role] = format_for_display(@role, 20) + printable[:start_month] = format_for_display(@start_month, nil) + printable[:start_year] = format_for_display(@start_year, nil) + printable + end + + # @return [String] + def to_table_line + printable = table_printable_values + out_str = String.new + out_str << format('| %- 16s', printable[:contract_type]) + out_str << format('| %- 11s', printable[:department]) + out_str << format('| %- 37s', printable[:description]) + out_str << format('| %- 26s', printable[:employer]) + out_str << format('| %- 10s', printable[:end_month]) + out_str << format('| %- 9s', printable[:end_year]) + out_str << format('| %- 21s', printable[:role]) + out_str << format('| %- 12s', printable[:start_month]) + out_str << format('| %- 11s', printable[:start_year]) + out_str << '|' + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Contract Type: #{printable[:contract_type]}" + out_str << "\n :Department: #{printable[:department]}" + out_str << "\n :Description: #{printable[:description]}" + out_str << "\n :Employer: #{printable[:employer]}" + out_str << "\n :End Month: #{printable[:end_month]}" + out_str << "\n :End Year: #{printable[:end_year]}" + out_str << "\n :Role: #{printable[:role]}" + out_str << "\n :Start Month: #{printable[:start_month]}" + out_str << "\n :Start Year: #{printable[:start_year]}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_usages.rb b/lib/mindee/v1/product/resume/resume_v1_professional_experiences.rb similarity index 60% rename from lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_usages.rb rename to lib/mindee/v1/product/resume/resume_v1_professional_experiences.rb index 108b8640e..4ac171c41 100644 --- a/lib/mindee/product/fr/energy_bill/energy_bill_v1_energy_usages.rb +++ b/lib/mindee/v1/product/resume/resume_v1_professional_experiences.rb @@ -1,27 +1,26 @@ # frozen_string_literal: true -require_relative 'energy_bill_v1_energy_supplier' -require_relative 'energy_bill_v1_energy_consumer' -require_relative 'energy_bill_v1_subscription' -require_relative 'energy_bill_v1_energy_usage' -require_relative 'energy_bill_v1_taxes_and_contribution' -require_relative 'energy_bill_v1_meter_detail' +require_relative 'resume_v1_social_networks_url' +require_relative 'resume_v1_language' +require_relative 'resume_v1_education' +require_relative 'resume_v1_professional_experience' +require_relative 'resume_v1_certificate' module Mindee - module Product - module FR - module EnergyBill - # Details of energy consumption. - class EnergyBillV1EnergyUsages < Array + module V1 + module Product + module Resume + # The list of the candidate's professional experiences. + class ResumeV1ProfessionalExperiences < Array # Entries. - # @return [Array] + # @return [Array] attr_reader :entries # @param prediction [Array] # @param page_id [Integer, nil] def initialize(prediction, page_id) entries = prediction.map do |entry| - EnergyBill::EnergyBillV1EnergyUsage.new(entry, page_id) + Resume::ResumeV1ProfessionalExperience.new(entry, page_id) end super(entries) end @@ -31,13 +30,14 @@ def initialize(prediction, page_id) # @return [String] def self.line_items_separator(char) out_str = String.new - out_str << "+#{char * 13}" - out_str << "+#{char * 38}" - out_str << "+#{char * 12}" + out_str << "+#{char * 17}" out_str << "+#{char * 12}" - out_str << "+#{char * 10}" + out_str << "+#{char * 38}" + out_str << "+#{char * 27}" out_str << "+#{char * 11}" - out_str << "+#{char * 17}" + out_str << "+#{char * 10}" + out_str << "+#{char * 22}" + out_str << "+#{char * 13}" out_str << "+#{char * 12}" out_str end @@ -51,14 +51,15 @@ def to_s end.join out_str = String.new out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Consumption' + out_str << ' | Contract Type ' + out_str << ' | Department' out_str << ' | Description ' - out_str << ' | End Date ' - out_str << ' | Start Date' - out_str << ' | Tax Rate' - out_str << ' | Total ' - out_str << ' | Unit of Measure' - out_str << ' | Unit Price' + out_str << ' | Employer ' + out_str << ' | End Month' + out_str << ' | End Year' + out_str << ' | Role ' + out_str << ' | Start Month' + out_str << ' | Start Year' out_str << " |\n#{self.class.line_items_separator('=')}" out_str + lines end diff --git a/lib/mindee/v1/product/resume/resume_v1_social_networks_url.rb b/lib/mindee/v1/product/resume/resume_v1_social_networks_url.rb new file mode 100644 index 000000000..c6f579a53 --- /dev/null +++ b/lib/mindee/v1/product/resume/resume_v1_social_networks_url.rb @@ -0,0 +1,66 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module Resume + # The list of social network profiles of the candidate. + class ResumeV1SocialNetworksUrl < Mindee::V1::Parsing::Standard::FeatureField + include Mindee::V1::Parsing::Standard + + # The name of the social network. + # @return [String] + attr_reader :name + # The URL of the social network. + # @return [String] + attr_reader :url + + # @param prediction [Hash] + # @param page_id [Integer, nil] + def initialize(prediction, page_id) + super + @name = prediction['name'] + @url = prediction['url'] + @page_id = page_id + end + + # @return [Hash] + def printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:name] = format_for_display(@name) + printable[:url] = format_for_display(@url) + printable + end + + # @return [Hash] + def table_printable_values + printable = {} # @type var printable: Hash[Symbol, String] + printable[:name] = format_for_display(@name, 20) + printable[:url] = format_for_display(@url, 50) + printable + end + + # @return [String] + def to_table_line + printable = table_printable_values + out_str = String.new + out_str << format('| %- 21s', printable[:name]) + out_str << format('| %- 51s', printable[:url]) + out_str << '|' + end + + # @return [String] + def to_s + printable = printable_values + out_str = String.new + out_str << "\n :Name: #{printable[:name]}" + out_str << "\n :URL: #{printable[:url]}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/product/fr/payslip/payslip_v3_salary_details.rb b/lib/mindee/v1/product/resume/resume_v1_social_networks_urls.rb similarity index 51% rename from lib/mindee/product/fr/payslip/payslip_v3_salary_details.rb rename to lib/mindee/v1/product/resume/resume_v1_social_networks_urls.rb index 9c1d542ae..a098c9d6b 100644 --- a/lib/mindee/product/fr/payslip/payslip_v3_salary_details.rb +++ b/lib/mindee/v1/product/resume/resume_v1_social_networks_urls.rb @@ -1,29 +1,26 @@ # frozen_string_literal: true -require_relative 'payslip_v3_pay_period' -require_relative 'payslip_v3_employee' -require_relative 'payslip_v3_employer' -require_relative 'payslip_v3_bank_account_detail' -require_relative 'payslip_v3_employment' -require_relative 'payslip_v3_salary_detail' -require_relative 'payslip_v3_pay_detail' -require_relative 'payslip_v3_paid_time_off' +require_relative 'resume_v1_social_networks_url' +require_relative 'resume_v1_language' +require_relative 'resume_v1_education' +require_relative 'resume_v1_professional_experience' +require_relative 'resume_v1_certificate' module Mindee - module Product - module FR - module Payslip - # Detailed information about the earnings. - class PayslipV3SalaryDetails < Array + module V1 + module Product + module Resume + # The list of social network profiles of the candidate. + class ResumeV1SocialNetworksUrls < Array # Entries. - # @return [Array] + # @return [Array] attr_reader :entries # @param prediction [Array] # @param page_id [Integer, nil] def initialize(prediction, page_id) entries = prediction.map do |entry| - Payslip::PayslipV3SalaryDetail.new(entry, page_id) + Resume::ResumeV1SocialNetworksUrl.new(entry, page_id) end super(entries) end @@ -33,11 +30,8 @@ def initialize(prediction, page_id) # @return [String] def self.line_items_separator(char) out_str = String.new - out_str << "+#{char * 14}" - out_str << "+#{char * 11}" - out_str << "+#{char * 38}" - out_str << "+#{char * 8}" - out_str << "+#{char * 11}" + out_str << "+#{char * 22}" + out_str << "+#{char * 52}" out_str end @@ -50,11 +44,8 @@ def to_s end.join out_str = String.new out_str << "\n#{self.class.line_items_separator('-')}\n " - out_str << ' | Amount ' - out_str << ' | Base ' - out_str << ' | Description ' - out_str << ' | Number' - out_str << ' | Rate ' + out_str << ' | Name ' + out_str << ' | URL ' out_str << " |\n#{self.class.line_items_separator('=')}" out_str + lines end diff --git a/lib/mindee/product/fr/health_card/health_card_v1.rb b/lib/mindee/v1/product/universal/universal.rb similarity index 54% rename from lib/mindee/product/fr/health_card/health_card_v1.rb rename to lib/mindee/v1/product/universal/universal.rb index 0869f4d91..036312f2b 100644 --- a/lib/mindee/product/fr/health_card/health_card_v1.rb +++ b/lib/mindee/v1/product/universal/universal.rb @@ -1,28 +1,29 @@ # frozen_string_literal: true -require_relative '../../../parsing' -require_relative 'health_card_v1_document' -require_relative 'health_card_v1_page' +require_relative 'universal_document' +require_relative 'universal_page' module Mindee - module Product - module FR - # Health Card module. - module HealthCard - # Health Card API version 1 inference prediction. - class HealthCardV1 < Mindee::Parsing::Common::Inference - @endpoint_name = 'french_healthcard' - @endpoint_version = '1' + module V1 + module Product + # Universal product module. + module Universal + # Universal Document V1 prediction inference. + class Universal < Mindee::V1::Parsing::Common::Inference + @endpoint_name = '' + @endpoint_version = '' + @has_sync = true @has_async = true - @has_sync = false # @param prediction [Hash] def initialize(prediction) super - @prediction = HealthCardV1Document.new(prediction['prediction'], nil) - @pages = [] + @prediction = UniversalDocument.new(prediction['prediction']) + @pages = [] # : Array[Mindee::V1::Parsing::Common::Page] prediction['pages'].each do |page| - @pages.push(HealthCardV1Page.new(page)) + if page.key?('prediction') && !page['prediction'].nil? && !page['prediction'].empty? + @pages.push(UniversalPage.new(page)) + end end end diff --git a/lib/mindee/v1/product/universal/universal_document.rb b/lib/mindee/v1/product/universal/universal_document.rb new file mode 100644 index 000000000..5a470b6df --- /dev/null +++ b/lib/mindee/v1/product/universal/universal_document.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'universal_prediction' + +module Mindee + module V1 + module Product + module Universal + # Universal Document V1 prediction + class UniversalDocument < Mindee::V1::Product::Universal::UniversalPrediction + include Mindee::V1::Parsing::Standard + + # @param raw_prediction [Hash] + def initialize(raw_prediction) + super + raw_prediction.each do |field_name, field_contents| + if field_contents.is_a?(Array) + @fields[field_name] = Parsing::Universal::UniversalListField.new(field_contents) + elsif field_contents.is_a?(Hash) && Parsing::Universal.universal_object?(field_contents) + @fields[field_name] = Parsing::Universal::UniversalObjectField.new(field_contents) + else + field_contents_str = field_contents.dup + if field_contents_str.key?('value') && field_contents_str['value'].nil? == false + field_contents_str['value'] = field_contents_str['value'].to_s + end + @fields[field_name] = Mindee::V1::Parsing::Standard::StringField.new(field_contents_str) + end + end + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/universal/universal_page.rb b/lib/mindee/v1/product/universal/universal_page.rb new file mode 100644 index 000000000..e0cb9a86b --- /dev/null +++ b/lib/mindee/v1/product/universal/universal_page.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +require_relative '../../parsing' +require_relative 'universal_prediction' + +module Mindee + module V1 + module Product + module Universal + # Universal Document V1 page. + class UniversalPage < Mindee::V1::Parsing::Common::Page + # @param prediction [Hash] + def initialize(prediction) + super + @prediction = UniversalPagePrediction.new( + prediction['prediction'], + prediction['id'] + ) + end + end + + # Universal Document V1 page prediction. + class UniversalPagePrediction < UniversalPrediction + include Mindee::V1::Parsing::Standard + include Mindee::V1::Parsing::Universal + + def initialize(raw_prediction, page_id = nil) + super(raw_prediction) + raw_prediction.each do |field_name, field_contents| + if field_contents.is_a?(Array) + @fields[field_name] = Mindee::V1::Parsing::Universal::UniversalListField.new(field_contents, page_id) + elsif field_contents.is_a?(Hash) && Parsing::Universal.universal_object?(field_contents) + @fields[field_name] = Mindee::V1::Parsing::Universal::UniversalObjectField.new(field_contents, page_id) + else + field_contents_str = field_contents.dup + if field_contents_str.key?('value') && !field_contents_str['value'].nil? + field_contents_str['value'] = field_contents_str['value'].to_s + end + @fields[field_name] = Mindee::V1::Parsing::Standard::StringField.new(field_contents_str, page_id) + end + end + end + + # @return [String] + def to_s + out_str = String.new + out_str << "\n#{super}" + out_str + end + end + end + end + end +end diff --git a/lib/mindee/v1/product/universal/universal_prediction.rb b/lib/mindee/v1/product/universal/universal_prediction.rb new file mode 100644 index 000000000..c06fdec15 --- /dev/null +++ b/lib/mindee/v1/product/universal/universal_prediction.rb @@ -0,0 +1,128 @@ +# frozen_string_literal: true + +require_relative '../../parsing' + +module Mindee + module V1 + module Product + module Universal + # Universal Document V1 page. + class UniversalPrediction < Mindee::V1::Parsing::Common::Prediction + include Mindee::V1::Parsing::Common + include Mindee::V1::Parsing::Standard + include Mindee::V1::Parsing::Universal + + # All value fields in the document + # @return [Hash] + attr_reader :fields + + def initialize(_ = nil) + super + @fields = {} # : Hash[String | Symbol, untyped] + end + + # String representation. + def to_s + out_str = '' + pattern = %r{^(\n* *)( {2}):} + @fields.each do |field_name, field_value| + str_value = if field_value.is_a?( + Mindee::V1::Parsing::Universal::UniversalListField + ) && field_value.values.length.positive? + generate_field_string(field_name, field_value, pattern) + else + field_value.to_s + end + out_str += "\n:#{field_name}:" + + out_str += " #{str_value}".sub(%r{^\s+\n}, "\n") if str_value.length.positive? + end + out_str.sub("\n", '') + end + + private + + def generate_field_string(field_name, field_value, pattern) + values = field_value.values + return '' if values.nil? || values.empty? + + str_value = '' + first_value = values[0] + str_value += if first_value.is_a?(Parsing::Universal::UniversalObjectField) + first_value.str_level(1).sub(pattern, '\\1* :') + else + "#{first_value.to_s.sub(pattern, '\\1* :')}\n" + end + Array(values[1..]).each do |sub_value| + str_value += if sub_value.is_a?(Parsing::Universal::UniversalObjectField) + sub_value.str_level(1).sub(pattern, '\\1* :') + else + "#{' ' * (field_name.length + 2)} #{sub_value}\n" + end + end + + str_value.rstrip + end + + def generate_list_field_string(field_name, field_value, pattern) + str_value = '' + field_value.each_value do |sub_value| + str_value += generate_sub_value_string(field_name, sub_value, pattern) + end + str_value.rstrip + end + + def generate_sub_value_string(field_name, sub_value, pattern) + if sub_value.is_a?(Mindee::V1::Parsing::Universal::UniversalObjectField) + sub_value.str_level(1).gsub(pattern, '\1* :') + else + (' ' * (field_name.length + 2)) + "#{sub_value}\n" + end + end + + # Returns a hash of all fields that aren't a collection + # @return [Hash] + def single_fields + single_fields = {} # : Hash[String | Symbol, untyped] + @fields.each do |field_name, field_value| + single_fields[field_name] = field_value if field_value.is_a?(Mindee::V1::Parsing::Standard::StringField) + end + single_fields + end + + # Returns a hash of all list-like fields + # @return [Hash] + def list_fields + list_fields = {} # : Hash[String | Symbol, Mindee::V1::Parsing::Universal::UniversalListField] + @fields.each do |field_name, field_value| + if field_value.is_a?(Mindee::V1::Parsing::Universal::UniversalListField) + list_fields[field_name] = + field_value + end + end + list_fields + end + + # Returns a hash of all object-like fields + # @return [Hash] + def object_fields + object_fields = {} # : Hash[String | Symbol, untyped] + @fields.each do |field_name, field_value| + if field_value.is_a?(Mindee::V1::Parsing::Universal::UniversalObjectField) + object_fields[field_name] = + field_value + end + end + object_fields + end + + # Lists names of all top-level field keys + # @return [Array] + def list_field_names + @fields.keys.map(&:to_s) + end + end + end + end + end +end diff --git a/lib/mindee/v2.rb b/lib/mindee/v2.rb index 6950e5f93..94303ea91 100644 --- a/lib/mindee/v2.rb +++ b/lib/mindee/v2.rb @@ -1,4 +1,7 @@ # frozen_string_literal: true -require_relative 'parsing' -require_relative 'product' +require_relative 'v2/client' +require_relative 'v2/http' +require_relative 'v2/file_operation' if Mindee::Dependency.all_deps_available? +require_relative 'v2/parsing' +require_relative 'v2/product' diff --git a/lib/mindee/v2/client.rb b/lib/mindee/v2/client.rb new file mode 100644 index 000000000..24cbf4c19 --- /dev/null +++ b/lib/mindee/v2/client.rb @@ -0,0 +1,132 @@ +# frozen_string_literal: true + +require_relative '../input' +require_relative '../http' +require_relative 'product' +require_relative 'parsing/job' +require_relative '../logging' + +module Mindee + module V2 + # Mindee V2 API Client. + class Client + # @return [V2::HTTP::MindeeApiV2] + private attr_reader :mindee_api + + # @param api_key [String] + def initialize(api_key: '') + @mindee_api = Mindee::V2::HTTP::MindeeApiV2.new(api_key: api_key) + end + + # Retrieves a result from a given queue or URL to the result. + # @param product [Class] The return class. + # @param resource [String] ID of the inference or URL to the result. + # @return [Mindee::V2::Parsing::BaseResponse] + def get_result(product, resource) + @mindee_api.req_get_result(product, resource) + end + + # Retrieves an inference from a given queue or URL to the job. + # @param job_id [String] ID of the job. + # @return [Mindee::V2::Parsing::JobResponse] + def get_job(job_id) + @mindee_api.req_get_job(job_id) + end + + # Enqueue a document for async parsing. + # @param product [Class] The return class. + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # The source of the input document (local file or URL). + # @param params [Hash, Input::BaseParameters] Parameters for the inference. + # @return [Mindee::V2::Parsing::JobResponse] + def enqueue( + product, + input_source, + params + ) + normalized_params = normalize_parameters(product.params_type, params) + normalized_params.validate_async_params + logger.debug("Enqueueing document to model '#{normalized_params.model_id}'.") + + @mindee_api.req_post_enqueue(input_source, normalized_params) + end + + # Enqueues to an asynchronous endpoint and automatically polls for a response. + # + # @param product [Class] The return class. + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # The source of the input document (local file or URL). + # @param params [Hash, Input::BaseParameters] Parameters for the inference. + # @return [Parsing::BaseResponse] + def enqueue_and_get_result( + product, + input_source, + params + ) + enqueue_response = enqueue(product, input_source, params) + normalized_params = normalize_parameters(product.params_type, params) + normalized_params.validate_async_params + + if enqueue_response.job.id.nil? || enqueue_response.job.id.empty? + logger.error("Failed enqueueing:\n#{enqueue_response.raw_http}") + raise Mindee::Error::MindeeError, 'Enqueueing of the document failed.' + end + + job_id = enqueue_response.job.id + logger.debug("Successfully enqueued document with job id: #{job_id}.") + + sleep(normalized_params.polling_options.initial_delay_sec) + retry_counter = 1 + poll_results = get_job(job_id) + + while retry_counter < normalized_params.polling_options.max_retries + if poll_results.job.status == 'Failed' + break + elsif !poll_results.job.result_url.nil? + return get_result(product, poll_results.job.result_url) + end + + logger.debug( + "Successfully enqueued inference with job id: #{job_id}.\n" \ + "Attempt n°#{retry_counter}/#{normalized_params.polling_options.max_retries}.\n" \ + "Job status: #{poll_results.job.status}." + ) + + sleep(normalized_params.polling_options.delay_sec) + poll_results = get_job(job_id) + retry_counter += 1 + end + + error = poll_results.job.error + unless error.nil? + err_to_raise = Mindee::Error::MindeeHTTPErrorV2.new(error) + # NOTE: purposefully decoupled from the line above, otherwise rubocop thinks `error` is a `message` param. + raise err_to_raise + end + + sec_count = normalized_params.polling_options.delay_sec * retry_counter + raise Mindee::Error::MindeeError, + "Asynchronous parsing request timed out after #{sec_count} seconds" + end + + # Searches for a list of available models for the given API key. + # @param model_name [String] + # @param model_type [String] + # @return [Mindee::V2::Parsing::Search::SearchResponse] + def search_models(model_name, model_type) + @mindee_api.search_models(model_name, model_type) + end + + private + + # If needed, converts the parsing options provided as a hash into a proper BaseParameters subclass object. + # @param params [Hash, Class] Params. + # @return [BaseParameters] + def normalize_parameters(param_class, params) + return param_class.from_hash(params: params) if params.is_a?(Hash) + + params + end + end + end +end diff --git a/lib/mindee/v2/file_operation.rb b/lib/mindee/v2/file_operation.rb new file mode 100644 index 000000000..60547647d --- /dev/null +++ b/lib/mindee/v2/file_operation.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +require_relative 'file_operation/crop' +require_relative 'file_operation/crop_files' +require_relative 'file_operation/split' +require_relative 'file_operation/split_files' diff --git a/lib/mindee/v2/file_operation/crop.rb b/lib/mindee/v2/file_operation/crop.rb new file mode 100644 index 000000000..7746f9e01 --- /dev/null +++ b/lib/mindee/v2/file_operation/crop.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +module Mindee + module V2 + module FileOperation + # Crop operations. + module Crop + # Extracts a single crop as complete PDFs from the document. + # + # @param input_source [LocalInputSource] Local Input Source to extract sub-receipts from. + # @param crop [FieldLocation] Crop to extract. + # @return [ExtractedImage] + def self.extract_single_crop(input_source, crop) + polygons = [crop.polygon] + Mindee::Image::ImageExtractor.extract_multiple_images_from_source( + input_source, crop.page, polygons + ).first + end + + # Extracts individual receipts from multi-receipts documents. + # + # @param input_source [LocalInputSource] Local Input Source to extract sub-receipts from. + # @param crops [Array] List of crops. + # @return [CropFiles] Individual extracted receipts as an array of ExtractedImage. + # @raise [MindeeError] if the crops array is empty. + def self.extract_crops(input_source, crops) + if crops.nil? || crops.empty? + raise Mindee::Error::MindeeError, + 'No possible candidates found for Crop extraction.' + end + + polygons = Array.new(input_source.page_count) { [] } + + crops.each do |crop| + polygons[crop.location.page] << crop.location.polygon + end + + images = [] # @type var images: Array[Image::ExtractedImage] + polygons.each_with_index do |page_polygons, page_index| + extracted = Mindee::Image::ImageExtractor.extract_multiple_images_from_source( + input_source, page_index, page_polygons + ) + images.concat(extracted) + end + + CropFiles.new(images) + end + end + end + end +end diff --git a/lib/mindee/v2/file_operation/crop_files.rb b/lib/mindee/v2/file_operation/crop_files.rb new file mode 100644 index 000000000..c57db2463 --- /dev/null +++ b/lib/mindee/v2/file_operation/crop_files.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +module Mindee + module V2 + module FileOperation + # Collection of cropped files. + class CropFiles < Array + # Save all extracted crops to disk. + # + # @param path [String, Pathname] Path to save the extracted crops to. + # @param prefix [String] Prefix to add to the filename, defaults to 'crop'. + # @param file_format [String, nil] File format to save the crops as, defaults to jpg if nil.] + def save_all_to_disk(path, prefix: 'crop', file_format: nil) + FileUtils.mkdir_p(path) + each.with_index(1) do |crop, idx| + filename = "#{prefix}_#{format('%03d', idx)}.jpg" + file_path = File.join(path.to_s, filename) + + crop.write_to_file(file_path, file_format) + end + end + end + end + end +end diff --git a/lib/mindee/v2/file_operation/split.rb b/lib/mindee/v2/file_operation/split.rb new file mode 100644 index 000000000..60dea7fcf --- /dev/null +++ b/lib/mindee/v2/file_operation/split.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +module Mindee + module V2 + module FileOperation + # Split operations. + module Split + # Extracts a single split as a complete PDF from the document. + # + # @param input_source [LocalInputSource] Input source to split. + # @param split [Array] List of pages to keep. + # @return [ExtractedPDF] Extracted PDF + def self.extract_single_split(input_source, split) + extract_splits(input_source, [split]).first + end + + # Extracts splits as complete PDFs from the document. + # + # @param input_source [LocalInputSource] Input source to split. + # @param splits [Array>] List of sub-lists of pages to keep. + # @return [SplitFiles] A list of extracted invoices. + # @raise [MindeeError] if no indexes are provided. + def self.extract_splits(input_source, splits) + raise Mindee::Error::MindeeError, 'No indexes provided.' if splits.nil? || splits.empty? + + pdf_extractor = Mindee::PDF::PDFExtractor.new(input_source) + + page_groups = splits.map do |split| + (split[0]..split[1]).to_a + end + + SplitFiles.new(pdf_extractor.extract_sub_documents(page_groups)) + end + end + end + end +end diff --git a/lib/mindee/v2/file_operation/split_files.rb b/lib/mindee/v2/file_operation/split_files.rb new file mode 100644 index 000000000..d75b3f46d --- /dev/null +++ b/lib/mindee/v2/file_operation/split_files.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +module Mindee + module V2 + module FileOperation + # Collection of split files. + class SplitFiles < Array + # Save all extracted splits to disk. + # + # @param path [String, Pathname] Path to save the extracted splits to. + # @param prefix [String] Prefix to add to the filename, defaults to 'split'. + def save_all_to_disk(path, prefix: 'split') + FileUtils.mkdir_p(path) + + each.with_index(1) do |split, idx| + filename = "#{prefix}_#{format('%03d', idx)}.pdf" + file_path = File.join(path.to_s, filename) + + split.write_to_file(file_path) + end + end + end + end + end +end diff --git a/lib/mindee/v2/http.rb b/lib/mindee/v2/http.rb new file mode 100644 index 000000000..45d7948e7 --- /dev/null +++ b/lib/mindee/v2/http.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +require_relative 'http/api_v2_settings' +require_relative 'http/mindee_api_v2' diff --git a/lib/mindee/v2/http/.rubocop.yml b/lib/mindee/v2/http/.rubocop.yml new file mode 100644 index 000000000..acea271ec --- /dev/null +++ b/lib/mindee/v2/http/.rubocop.yml @@ -0,0 +1,7 @@ +inherit_from: ../../../../.rubocop.yml + +Metrics/CyclomaticComplexity: + Max: 10 + +Metrics/PerceivedComplexity: + Max: 10 diff --git a/lib/mindee/v2/http/api_v2_settings.rb b/lib/mindee/v2/http/api_v2_settings.rb new file mode 100644 index 000000000..1b3e4864c --- /dev/null +++ b/lib/mindee/v2/http/api_v2_settings.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +require_relative '../../version' + +module Mindee + module V2 + module HTTP + # API client for version 2. + class ApiV2Settings + # V2 API key's default environment key name. + MINDEE_V2_API_KEY_ENV_NAME = 'MINDEE_V2_API_KEY' + # V2 API key's default value. + MINDEE_V2_API_KEY_DEFAULT = nil + + # V2 base URL default environment key name. + MINDEE_V2_BASE_URL_ENV_NAME = 'MINDEE_V2_BASE_URL' + # V2 base URL default value. + MINDEE_V2_BASE_URL_DEFAULT = 'https://api-v2.mindee.net' + + # HTTP request timeout default environment key name. + MINDEE_V2_REQUEST_TIMEOUT_ENV_NAME = 'MINDEE_V2_REQUEST_TIMEOUT' + # HTTP request timeout default value. + MINDEE_V2_TIMEOUT_DEFAULT = 120 + + # Default value for the user agent (same as V1). + USER_AGENT = "mindee-api-ruby@v#{Mindee::VERSION} ruby-v#{RUBY_VERSION} #{Mindee::PLATFORM}".freeze + + # @return [String] + attr_reader :api_key + # @return [Integer] + attr_reader :request_timeout + # @return [String] + attr_reader :base_url + # @return [String] + attr_reader :user_agent + + def initialize(api_key: nil) + @request_timeout = ENV.fetch(MINDEE_V2_REQUEST_TIMEOUT_ENV_NAME, MINDEE_V2_TIMEOUT_DEFAULT).to_i + if api_key.nil? && !ENV.fetch(MINDEE_V2_API_KEY_ENV_NAME, MINDEE_V2_API_KEY_DEFAULT).to_s.empty? + logger.debug('API key set from environment') + end + @api_key = if api_key.nil? || api_key.empty? + ENV.fetch(MINDEE_V2_API_KEY_ENV_NAME, + MINDEE_V2_API_KEY_DEFAULT) + else + api_key + end + @base_url = ENV.fetch(MINDEE_V2_BASE_URL_ENV_NAME, MINDEE_V2_BASE_URL_DEFAULT).chomp('/') + @user_agent = USER_AGENT + end + + # Checks API key for a value. + # @return + # @raise [Error::MindeeAPIError] Raises if the api key is empty or nil. + def check_api_key + return unless @api_key.nil? || @api_key.to_s.empty? + + raise Error::MindeeAPIError, + "Missing API key. check your Client Configuration.\nYou can set this using the " \ + "'#{MINDEE_V2_API_KEY_ENV_NAME}' environment variable." + end + end + end + end +end diff --git a/lib/mindee/v2/http/mindee_api_v2.rb b/lib/mindee/v2/http/mindee_api_v2.rb new file mode 100644 index 000000000..29631f18c --- /dev/null +++ b/lib/mindee/v2/http/mindee_api_v2.rb @@ -0,0 +1,230 @@ +# frozen_string_literal: true + +require_relative '../../input' +require_relative '../../http' +require_relative '../../error' + +module Mindee + module V2 + module HTTP + # API client for version 2. + class MindeeApiV2 + # @return [ApiV2Settings] + attr_reader :settings + + # @param api_key [String, nil] + def initialize(api_key: nil) + @settings = ApiV2Settings.new(api_key: api_key) + end + + # Sends a file to the queue. + # + # @param input_source [Input::Source::LocalInputSource, Input::Source::URLInputSource] + # @param params [Input::BaseParameters] + # @return [Mindee::V2::Parsing::JobResponse] + # @raise [Mindee::Error::MindeeHttpErrorV2] + def req_post_enqueue(input_source, params) + @settings.check_api_key + response = enqueue( + input_source, + params + ) + Mindee::V2::Parsing::JobResponse.new(process_response(response)) + end + + # Retrieves a result from a given queue. + # @param product [Class] The return class. + # @param resource [String] ID of the inference or URL to the result. + # @return [Mindee::V2::Parsing::BaseResponse] + def req_get_result(product, resource) + return req_get_result_url(product.response_type, resource) if uri?(resource) + + @settings.check_api_key + response = result_req_get( + resource, + product + ) + product.response_type.new(process_response(response)) + end + + # Retrieves a queued job. + # + # @param job_id [String] ID of the job or URL to the job. + # @return [Mindee::V2::Parsing::JobResponse] + def req_get_job(job_id) + @settings.check_api_key + response = poll("#{@settings.base_url}/v2/jobs/#{job_id}") + Mindee::V2::Parsing::JobResponse.new(process_response(response)) + end + + # Retrieves a list of models. + # @param model_name [String, nil] + # @param model_type [String, nil] + # @return [Mindee::V2::Parsing::Search::SearchResponse] + def search_models(model_name, model_type) + Mindee::V2::Parsing::Search::SearchResponse.new(process_response(req_get_search_models(model_name, + model_type))) + end + + private + + # Retrieves a list of models. + # @param model_name [String, nil] + # @param model_type [String, nil] + # @return [Net::HTTPResponse] + def req_get_search_models(model_name, model_type) + url = "#{@settings.base_url}/v2/search/models" + uri = URI(url) + + query_params = {} # @type var query_params: Hash[Symbol, String | nil] + query_params[:name] = model_name if model_name + query_params[:model_type] = model_type if model_type + uri.query = URI.encode_www_form(query_params) unless query_params.empty? + + headers = { + 'Authorization' => @settings.api_key, + 'User-Agent' => @settings.user_agent, + } + req = Net::HTTP::Get.new(uri, headers) + req['Transfer-Encoding'] = 'chunked' + + Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @settings.request_timeout) do |http| + return http.request(req) + end + raise Mindee::Error::MindeeError, 'Could not resolve server response.' + end + + # @param resource [String] Resource to check. + # @return [Boolean] + def uri?(resource) + uri = URI.parse(resource) + throw Mindee::Error::MindeeError, 'HTTP is not supported.' if uri.scheme == 'http' + uri.scheme == 'https' + rescue URI::BadURIError, URI::InvalidURIError + false + end + + # Retrieves a queued job. + # + # @param url [String] + # @return [Mindee::V2::Parsing::JobResponse] + def req_get_job_url(url) + @settings.check_api_key + response = poll(url) + Mindee::V2::Parsing::JobResponse.new(process_response(response)) + end + + # Retrieves a queued job. + # + # @param result_class [Class] + # @param url [String] + # @return [Mindee::V2::Parsing::BaseResponse] + def req_get_result_url(result_class, url) + @settings.check_api_key + response = poll(url) + result_class.new(process_response(response)) + end + + # Converts an HTTP response to a parsed response object. + # + # @param response [Net::HTTPResponse, nil] + # @return [Hash] + # @raise Throws if the server returned an error. + def process_response(response) + if !response.nil? && response.respond_to?(:body) && + Mindee::HTTP::ResponseValidation.valid_v2_response?(response) + return JSON.parse(response.body, object_class: Hash) + end + + response_body = if response.nil? || !response.respond_to?(:body) + '{ "status": -1, + "detail": "Empty server response." }' + else + response.body + end + raise Mindee::HTTP::ErrorHandler.generate_v2_error(JSON.parse(response_body).transform_keys(&:to_sym)) + end + + # Polls a queue for either a result or a job. + # @param url [String] URL, passed as a string. + # @return [Net::HTTPResponse] + def poll(url) + uri = URI(url) + headers = { + 'Authorization' => @settings.api_key, + 'User-Agent' => @settings.user_agent, + } + req = Net::HTTP::Get.new(uri, headers) + req['Transfer-Encoding'] = 'chunked' + + Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @settings.request_timeout) do |http| + return http.request(req) + end + raise Mindee::Error::MindeeError, 'Could not resolve server response.' + end + + # Polls the API for the result of an inference. + # + # @param queue_id [String] ID of the queue. + # @param product [Class] The return class. + # @return [Net::HTTPResponse] + def result_req_get(queue_id, product) + poll("#{@settings.base_url}/v2/products/#{product.slug}/results/#{queue_id}") + end + + # Handle parameters for the enqueue form + # @param form_data [Array] Array of form fields + # @param params [V2::Product::Extraction::Params::ExtractionParameters] Inference options. + def enqueue_form_options(form_data, params) + form_data.push(['rag', params.rag.to_s]) unless params.rag.nil? + form_data.push(['raw_text', params.raw_text.to_s]) unless params.raw_text.nil? + form_data.push(['polygon', params.polygon.to_s]) unless params.polygon.nil? + form_data.push(['confidence', params.confidence.to_s]) unless params.confidence.nil? + form_data.push ['text_context', params.text_context] if params.text_context + form_data.push ['data_schema', params.data_schema.to_s] if params.data_schema + unless params.webhook_ids.nil? || params.webhook_ids.empty? + params.webhook_ids.each do |webhook_id| + form_data.push ['webhook_ids[]', webhook_id] + end + end + form_data + end + + # @param input_source [Mindee::Input::Source::LocalInputSource, Mindee::Input::Source::URLInputSource] + # @param params [Input::BaseParameters] Inference options. + # @return [Net::HTTPResponse, nil] + def enqueue(input_source, params) + uri = URI("#{@settings.base_url}/v2/products/#{params.slug}/enqueue") + + form_data = if input_source.is_a?(Mindee::Input::Source::URLInputSource) + [['url', input_source.url]] # : Array[Array[untyped]] + else + file_data, file_metadata = input_source.read_contents(close: params.close_file) + [['file', file_data, file_metadata]] # : Array[Array[untyped]] + end + form_data.push(['model_id', params.model_id]) + form_data.push ['file_alias', params.file_alias] if params.file_alias + if params.is_a?(V2::Product::Extraction::Params::ExtractionParameters) + form_data = enqueue_form_options(form_data, params) + end + + form_data = params.append_form_data(form_data) + + headers = { + 'Authorization' => @settings.api_key, + 'User-Agent' => @settings.user_agent, + } + req = Net::HTTP::Post.new(uri, headers) + + req.set_form(form_data, 'multipart/form-data') + req['Transfer-Encoding'] = 'chunked' + + Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: @settings.request_timeout) do |http| + return http.request(req) + end + raise Mindee::Error::MindeeError, 'Could not resolve server response.' + end + end + end + end +end diff --git a/lib/mindee/v2/parsing.rb b/lib/mindee/v2/parsing.rb new file mode 100644 index 000000000..46fd19e4b --- /dev/null +++ b/lib/mindee/v2/parsing.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require_relative 'parsing/common_response' +require_relative 'parsing/error_response' +require_relative 'parsing/field' +require_relative 'parsing/inference_file' +require_relative 'parsing/inference_job' +require_relative 'parsing/inference_model' +require_relative 'parsing/inference_active_options' +require_relative 'parsing/job' +require_relative 'parsing/job_response' +require_relative 'parsing/job_webhook' +require_relative 'parsing/rag_metadata' +require_relative 'parsing/raw_text' +require_relative 'parsing/raw_text_page' +require_relative 'parsing/search' diff --git a/lib/mindee/v2/parsing/base_inference.rb b/lib/mindee/v2/parsing/base_inference.rb index 31cbe87cf..8e62cf022 100644 --- a/lib/mindee/v2/parsing/base_inference.rb +++ b/lib/mindee/v2/parsing/base_inference.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require_relative '../product/base_product' -require_relative '../../parsing/v2/inference_response' +require_relative '../parsing' module Mindee module V2 @@ -10,9 +10,9 @@ module Parsing class BaseInference < Mindee::V2::Product::BaseProduct # @return [InferenceJob] Metadata about the job. attr_reader :job - # @return [Parsing::V2::InferenceModel] Model info for the inference. + # @return [V2::Parsing::InferenceModel] Model info for the inference. attr_reader :model - # @return [Parsing::V2::InferenceFile] File info for the inference. + # @return [V2::Parsing::InferenceFile] File info for the inference. attr_reader :file # @return [String] ID of the inference. attr_reader :id @@ -21,10 +21,10 @@ def initialize(http_response) raise ArgumentError, 'Server response must be a Hash' unless http_response.is_a?(Hash) super() - @model = Mindee::Parsing::V2::InferenceModel.new(http_response['model']) - @file = Mindee::Parsing::V2::InferenceFile.new(http_response['file']) + @model = Mindee::V2::Parsing::InferenceModel.new(http_response['model']) + @file = Mindee::V2::Parsing::InferenceFile.new(http_response['file']) @id = http_response['id'] - @job = Mindee::Parsing::V2::InferenceJob.new(http_response['job']) if http_response.key?('job') + @job = Mindee::V2::Parsing::InferenceJob.new(http_response['job']) if http_response.key?('job') end # String representation. diff --git a/lib/mindee/v2/parsing/base_response.rb b/lib/mindee/v2/parsing/base_response.rb index a604e1564..126baeec5 100644 --- a/lib/mindee/v2/parsing/base_response.rb +++ b/lib/mindee/v2/parsing/base_response.rb @@ -1,10 +1,12 @@ # frozen_string_literal: true +require_relative 'common_response' + module Mindee module V2 module Parsing # Base class for V2 inference responses. - class BaseResponse < Mindee::Parsing::V2::CommonResponse + class BaseResponse < Mindee::V2::Parsing::CommonResponse # @return [BaseInference] The inference result for a split utility request attr_reader :inference end diff --git a/lib/mindee/parsing/v2/common_response.rb b/lib/mindee/v2/parsing/common_response.rb similarity index 69% rename from lib/mindee/parsing/v2/common_response.rb rename to lib/mindee/v2/parsing/common_response.rb index b28938042..bcdb7223a 100644 --- a/lib/mindee/parsing/v2/common_response.rb +++ b/lib/mindee/v2/parsing/common_response.rb @@ -1,16 +1,18 @@ # frozen_string_literal: true +require 'json' + module Mindee - module Parsing - module V2 + module V2 + module Parsing # Base class for inference and job responses on the V2 API. class CommonResponse - # @return [Hash] + # @return [String] attr_reader :raw_http # @param http_response [Hash] def initialize(http_response) - @raw_http = http_response + @raw_http = JSON.generate(http_response) end end end diff --git a/lib/mindee/parsing/v2/error_item.rb b/lib/mindee/v2/parsing/error_item.rb similarity index 94% rename from lib/mindee/parsing/v2/error_item.rb rename to lib/mindee/v2/parsing/error_item.rb index bc81da6a0..d77475783 100644 --- a/lib/mindee/parsing/v2/error_item.rb +++ b/lib/mindee/v2/parsing/error_item.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module Mindee - module Parsing - module V2 + module V2 + module Parsing # Individual error item. class ErrorItem # @return [String, nil] A JSON Pointer to the location of the body property. diff --git a/lib/mindee/parsing/v2/error_response.rb b/lib/mindee/v2/parsing/error_response.rb similarity index 98% rename from lib/mindee/parsing/v2/error_response.rb rename to lib/mindee/v2/parsing/error_response.rb index 6745603e3..cec156101 100644 --- a/lib/mindee/parsing/v2/error_response.rb +++ b/lib/mindee/v2/parsing/error_response.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module Mindee - module Parsing - module V2 + module V2 + module Parsing # Encapsulates information returned by the API when an error occurs. class ErrorResponse # @return [Integer] The HTTP status code returned by the server. diff --git a/lib/mindee/parsing/v2/field.rb b/lib/mindee/v2/parsing/field.rb similarity index 100% rename from lib/mindee/parsing/v2/field.rb rename to lib/mindee/v2/parsing/field.rb diff --git a/lib/mindee/parsing/v2/field/base_field.rb b/lib/mindee/v2/parsing/field/base_field.rb similarity index 94% rename from lib/mindee/parsing/v2/field/base_field.rb rename to lib/mindee/v2/parsing/field/base_field.rb index 1256c6425..53482da94 100644 --- a/lib/mindee/parsing/v2/field/base_field.rb +++ b/lib/mindee/v2/parsing/field/base_field.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module Mindee - module Parsing - module V2 + module V2 + module Parsing # Field submodule for V2. module Field # Base class for V2 fields. @@ -54,7 +54,7 @@ def self.create_field(raw_prediction, indent_level = 0) return SimpleField.new(raw_prediction, indent_level) end - raise Errors::MindeeError, "Unrecognized field format in #{raw_prediction.to_json}" + raise Error::MindeeError, "Unrecognized field format in #{raw_prediction.to_json}" end end end diff --git a/lib/mindee/parsing/v2/field/field_confidence.rb b/lib/mindee/v2/parsing/field/field_confidence.rb similarity index 99% rename from lib/mindee/parsing/v2/field/field_confidence.rb rename to lib/mindee/v2/parsing/field/field_confidence.rb index 0570b7a90..647196742 100644 --- a/lib/mindee/parsing/v2/field/field_confidence.rb +++ b/lib/mindee/v2/parsing/field/field_confidence.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field # Confidence level of a field as returned by the V2 API. class FieldConfidence diff --git a/lib/mindee/parsing/v2/field/field_location.rb b/lib/mindee/v2/parsing/field/field_location.rb similarity index 96% rename from lib/mindee/parsing/v2/field/field_location.rb rename to lib/mindee/v2/parsing/field/field_location.rb index d5869b57a..5b1e49bcd 100644 --- a/lib/mindee/parsing/v2/field/field_location.rb +++ b/lib/mindee/v2/parsing/field/field_location.rb @@ -3,8 +3,8 @@ require_relative '../../../geometry/polygon' module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field # Location of a field. class FieldLocation diff --git a/lib/mindee/parsing/v2/field/inference_fields.rb b/lib/mindee/v2/parsing/field/inference_fields.rb similarity index 97% rename from lib/mindee/parsing/v2/field/inference_fields.rb rename to lib/mindee/v2/parsing/field/inference_fields.rb index 8d1094c90..e7d0431f3 100644 --- a/lib/mindee/parsing/v2/field/inference_fields.rb +++ b/lib/mindee/v2/parsing/field/inference_fields.rb @@ -3,8 +3,8 @@ require_relative 'base_field' module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field # Represents a hash-like collection of inference fields, providing methods for # retrieval and string representation. @@ -73,7 +73,7 @@ def to_s(indent = 0) indent ||= @indent_level padding = ' ' * indent - lines = [] + lines = [] # @type var lines: Array[String] each do |field_key, field_value| line = "#{padding}:#{field_key}:" diff --git a/lib/mindee/parsing/v2/field/list_field.rb b/lib/mindee/v2/parsing/field/list_field.rb similarity index 92% rename from lib/mindee/parsing/v2/field/list_field.rb rename to lib/mindee/v2/parsing/field/list_field.rb index 33bb5470e..9d6a7effb 100644 --- a/lib/mindee/parsing/v2/field/list_field.rb +++ b/lib/mindee/v2/parsing/field/list_field.rb @@ -3,8 +3,8 @@ require_relative 'base_field' module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field # Represents a field that contains a list of items. class ListField < BaseField @@ -18,7 +18,7 @@ def initialize(server_response, indent_level = 0) super unless server_response.key?('items') && server_response['items'].is_a?(Array) - raise Errors::MindeeError, + raise Error::MindeeError, "Expected \"items\" to be an array in #{server_response.to_json}." end @@ -32,7 +32,7 @@ def initialize(server_response, indent_level = 0) # @return [Array] Simple fields contained in the list. # @raise [TypeError] If the fields are not SimpleField. def simple_items - fields = [] + fields = [] # @type var fields: Array[SimpleField] @items.each do |item| raise TypeError, "Invalid field type detected: #{item.class}" unless item.is_a?(SimpleField) @@ -45,7 +45,7 @@ def simple_items # @return [Array] Object fields contained in the list. # @raise [TypeError] If the fields are not ObjectField. def object_items - fields = [] + fields = [] # @type var fields: Array[ObjectField] @items.each do |item| raise TypeError, "Invalid field type detected: #{item.class}" unless item.is_a?(ObjectField) diff --git a/lib/mindee/parsing/v2/field/object_field.rb b/lib/mindee/v2/parsing/field/object_field.rb similarity index 87% rename from lib/mindee/parsing/v2/field/object_field.rb rename to lib/mindee/v2/parsing/field/object_field.rb index 39a1f548b..c9d7feaa9 100644 --- a/lib/mindee/parsing/v2/field/object_field.rb +++ b/lib/mindee/v2/parsing/field/object_field.rb @@ -4,8 +4,8 @@ require_relative 'inference_fields' module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field # A field containing a nested set of inference fields. class ObjectField < BaseField @@ -111,22 +111,25 @@ def get_object_field(key) # Get all simple fields. # @return [Hash] Simple fields contained in the object. def simple_fields - # @type var fields: Hash - @fields.select { |_, value| value.is_a?(SimpleField) } + # @type var result: Hash[String, SimpleField] + result = @fields.select { |_, value| value.is_a?(SimpleField) } # rubocop:disable Style/RedundantAssignment + result end # Get all list fields. # @return [Hash] List fields contained in the object. def list_fields - # @type var fields: Hash - @fields.select { |_, value| value.is_a?(ListField) } + # @type var result: Hash[String, ListField] + result = @fields.select { |_, value| value.is_a?(ListField) } # rubocop:disable Style/RedundantAssignment + result end # Get all object fields. # @return [Hash] Object fields contained in the object. def object_fields - # @type var fields: Hash - @fields.select { |_, value| value.is_a?(ObjectField) } + # @type var result: Hash[String, ObjectField] + result = @fields.select { |_, value| value.is_a?(ObjectField) } # rubocop:disable Style/RedundantAssignment + result end end end diff --git a/lib/mindee/parsing/v2/field/simple_field.rb b/lib/mindee/v2/parsing/field/simple_field.rb similarity index 98% rename from lib/mindee/parsing/v2/field/simple_field.rb rename to lib/mindee/v2/parsing/field/simple_field.rb index f5e1903e2..2bc8f675c 100644 --- a/lib/mindee/parsing/v2/field/simple_field.rb +++ b/lib/mindee/v2/parsing/field/simple_field.rb @@ -3,8 +3,8 @@ require_relative 'base_field' module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field # A simple field with a scalar value. class SimpleField < BaseField diff --git a/lib/mindee/parsing/v2/inference_active_options.rb b/lib/mindee/v2/parsing/inference_active_options.rb similarity index 98% rename from lib/mindee/parsing/v2/inference_active_options.rb rename to lib/mindee/v2/parsing/inference_active_options.rb index 47d884730..32db887a3 100644 --- a/lib/mindee/parsing/v2/inference_active_options.rb +++ b/lib/mindee/v2/parsing/inference_active_options.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module Mindee - module Parsing - module V2 + module V2 + module Parsing # Data schema options activated during the inference. class DataSchemaActiveOption # @return [Boolean] diff --git a/lib/mindee/parsing/v2/inference_file.rb b/lib/mindee/v2/parsing/inference_file.rb similarity index 97% rename from lib/mindee/parsing/v2/inference_file.rb rename to lib/mindee/v2/parsing/inference_file.rb index 78dda706b..6758c6984 100644 --- a/lib/mindee/parsing/v2/inference_file.rb +++ b/lib/mindee/v2/parsing/inference_file.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module Mindee - module Parsing - module V2 + module V2 + module Parsing # Information about a file returned in an inference. class InferenceFile # @return [String] File name. diff --git a/lib/mindee/parsing/v2/inference_job.rb b/lib/mindee/v2/parsing/inference_job.rb similarity index 94% rename from lib/mindee/parsing/v2/inference_job.rb rename to lib/mindee/v2/parsing/inference_job.rb index e6b6f4b6a..c6e3c4764 100644 --- a/lib/mindee/parsing/v2/inference_job.rb +++ b/lib/mindee/v2/parsing/inference_job.rb @@ -4,8 +4,8 @@ require_relative 'job' module Mindee - module Parsing - module V2 + module V2 + module Parsing # HTTP response wrapper that embeds a V2 job. class InferenceJob # @return [String] UUID of the Job. diff --git a/lib/mindee/parsing/v2/inference_model.rb b/lib/mindee/v2/parsing/inference_model.rb similarity index 95% rename from lib/mindee/parsing/v2/inference_model.rb rename to lib/mindee/v2/parsing/inference_model.rb index 85cb4eb8d..fa6b19f9d 100644 --- a/lib/mindee/parsing/v2/inference_model.rb +++ b/lib/mindee/v2/parsing/inference_model.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module Mindee - module Parsing - module V2 + module V2 + module Parsing # ID of the model that produced the inference. class InferenceModel # @return [String] Identifier of the model. diff --git a/lib/mindee/parsing/v2/job.rb b/lib/mindee/v2/parsing/job.rb similarity index 97% rename from lib/mindee/parsing/v2/job.rb rename to lib/mindee/v2/parsing/job.rb index 3185397f4..e3f726d8e 100644 --- a/lib/mindee/parsing/v2/job.rb +++ b/lib/mindee/v2/parsing/job.rb @@ -5,8 +5,8 @@ require_relative 'job_webhook' module Mindee - module Parsing - module V2 + module V2 + module Parsing # Metadata returned when polling a job (asynchronous request). class Job # @return [String] Unique job identifier. @@ -81,7 +81,7 @@ def to_s '', 'Webhooks', '=========', - @webhooks.map(&:to_s).join("\n\n"), + @webhooks.join("\n\n"), ] end diff --git a/lib/mindee/parsing/v2/job_response.rb b/lib/mindee/v2/parsing/job_response.rb similarity index 95% rename from lib/mindee/parsing/v2/job_response.rb rename to lib/mindee/v2/parsing/job_response.rb index 70aab84ac..5515a11ba 100644 --- a/lib/mindee/parsing/v2/job_response.rb +++ b/lib/mindee/v2/parsing/job_response.rb @@ -4,8 +4,8 @@ require_relative 'job' module Mindee - module Parsing - module V2 + module V2 + module Parsing # HTTP response wrapper that embeds a V2 job. class JobResponse < CommonResponse # @return [Job] Parsed job payload. diff --git a/lib/mindee/parsing/v2/job_webhook.rb b/lib/mindee/v2/parsing/job_webhook.rb similarity index 95% rename from lib/mindee/parsing/v2/job_webhook.rb rename to lib/mindee/v2/parsing/job_webhook.rb index ac291a0b3..15aae54ad 100644 --- a/lib/mindee/parsing/v2/job_webhook.rb +++ b/lib/mindee/v2/parsing/job_webhook.rb @@ -1,12 +1,11 @@ -# lib/mindee/parsing/v2/job_response_webhook.rb # frozen_string_literal: true require 'date' require_relative 'error_response' module Mindee - module Parsing - module V2 + module V2 + module Parsing # Information about a webhook created for a job response. class JobWebhook # @return [String] Identifier of the webhook. diff --git a/lib/mindee/parsing/v2/rag_metadata.rb b/lib/mindee/v2/parsing/rag_metadata.rb similarity index 92% rename from lib/mindee/parsing/v2/rag_metadata.rb rename to lib/mindee/v2/parsing/rag_metadata.rb index 5bebc6033..e9682413d 100644 --- a/lib/mindee/parsing/v2/rag_metadata.rb +++ b/lib/mindee/v2/parsing/rag_metadata.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module Mindee - module Parsing - module V2 + module V2 + module Parsing # Metadata about the RAG operation. class RAGMetadata # The UUID of the matched document used during the RAG operation. diff --git a/lib/mindee/parsing/v2/raw_text.rb b/lib/mindee/v2/parsing/raw_text.rb similarity index 72% rename from lib/mindee/parsing/v2/raw_text.rb rename to lib/mindee/v2/parsing/raw_text.rb index 9fa829f88..73841dcc0 100644 --- a/lib/mindee/parsing/v2/raw_text.rb +++ b/lib/mindee/v2/parsing/raw_text.rb @@ -1,11 +1,11 @@ # frozen_string_literal: true module Mindee - module Parsing - module V2 + module V2 + module Parsing # Raw text extracted from all pages in the document. class RawText - # @return [Array[Mindee::Parsing::V2::RawTextPage]] List of pages with their extracted text content. + # @return [Array[Mindee::V2::Parsing::RawTextPage]] List of pages with their extracted text content. attr_reader :pages # @param server_response [Hash] Raw JSON parsed into a Hash. @@ -16,8 +16,10 @@ def initialize(server_response) end end + # String representation. + # @return [String] def to_s - "#{@pages.map(&:to_s).join("\n\n")}\n" + "#{@pages.join("\n\n")}\n" end end end diff --git a/lib/mindee/parsing/v2/raw_text_page.rb b/lib/mindee/v2/parsing/raw_text_page.rb similarity index 84% rename from lib/mindee/parsing/v2/raw_text_page.rb rename to lib/mindee/v2/parsing/raw_text_page.rb index 3b952b626..625fca71d 100644 --- a/lib/mindee/parsing/v2/raw_text_page.rb +++ b/lib/mindee/v2/parsing/raw_text_page.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module Mindee - module Parsing - module V2 + module V2 + module Parsing # Raw text extracted from a single page. class RawTextPage # @return [String] Text content of the page as a single string. '\n' is used to separate lines. @@ -13,6 +13,8 @@ def initialize(server_response) @content = server_response['content'] end + # String representation. + # @return [String] def to_s @content end diff --git a/lib/mindee/v2/parsing/search.rb b/lib/mindee/v2/parsing/search.rb new file mode 100644 index 000000000..4972c44e8 --- /dev/null +++ b/lib/mindee/v2/parsing/search.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +require_relative 'search/pagination_metadata' +require_relative 'search/search_model' +require_relative 'search/search_models' +require_relative 'search/search_response' diff --git a/lib/mindee/v2/parsing/search/pagination_metadata.rb b/lib/mindee/v2/parsing/search/pagination_metadata.rb new file mode 100644 index 000000000..207a068a4 --- /dev/null +++ b/lib/mindee/v2/parsing/search/pagination_metadata.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +module Mindee + module V2 + module Parsing + module Search + # Pagination Metadata data associated with model search. + class PaginationMetadata + # @return [Integer] Number of items per page. + attr_reader :per_page + + # @return [Integer] 1-indexed page number. + attr_reader :page + + # @return [Integer] Total items. + attr_reader :total_items + + # @return [Integer] Total number of pages. + attr_reader :total_pages + + # @param raw_response [Hash] The parsed JSON payload mapping to pagination metadata. + def initialize(raw_response) + @per_page = raw_response['per_page'] + @page = raw_response['page'] + @total_items = raw_response['total_items'] + @total_pages = raw_response['total_pages'] + end + + # String representation of the pagination metadata. + # @return [String] + def to_s + [ + ":Per Page: #{@per_page}", + ":Page: #{@page}", + ":Total Items: #{@total_items}", + ":Total Pages: #{@total_pages}", + '', + ].join("\n") + end + end + end + end + end +end diff --git a/lib/mindee/v2/parsing/search/search_model.rb b/lib/mindee/v2/parsing/search/search_model.rb new file mode 100644 index 000000000..ee3ec5edc --- /dev/null +++ b/lib/mindee/v2/parsing/search/search_model.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +module Mindee + module V2 + module Parsing + module Search + # Individual model information. + class SearchModel + # @return [String] ID of the model. + attr_reader :id + + # @return [String] Name of the model. + attr_reader :name + + # @return [String] Type of the model. + attr_reader :model_type + + # @param payload [Hash] The parsed JSON payload mapping to the search model. + def initialize(payload) + @id = payload['id'] + @name = payload['name'] + @model_type = payload['model_type'] + end + + # String representation of the model. + # @return [String] + def to_s + [ + ":Name: #{@name}", + ":ID: #{@id}", + ":Model Type: #{@model_type}", + ].join("\n") + end + end + end + end + end +end diff --git a/lib/mindee/v2/parsing/search/search_models.rb b/lib/mindee/v2/parsing/search/search_models.rb new file mode 100644 index 000000000..9e90f0d62 --- /dev/null +++ b/lib/mindee/v2/parsing/search/search_models.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +module Mindee + module V2 + module Parsing + module Search + # Array of search models. + class SearchModels < Array + def initialize(prediction) + super(prediction.map { |entry| SearchModel.new(entry) }) + end + + # Default string representation. + # @return [String] + def to_s + return "\n" if empty? + + lines = flat_map do |model| + [ + "* :Name: #{model.name}", + " :ID: #{model.id}", + " :Model Type: #{model.model_type}", + ] + end + + # Joins all lines with a newline and appends a final newline + # to perfectly match the C# StringBuilder output. + "#{lines.join("\n")}\n" + end + end + end + end + end +end diff --git a/lib/mindee/v2/parsing/search/search_response.rb b/lib/mindee/v2/parsing/search/search_response.rb new file mode 100644 index 000000000..9195a5e5f --- /dev/null +++ b/lib/mindee/v2/parsing/search/search_response.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +module Mindee + module V2 + module Parsing + module Search + # Models search response. + class SearchResponse < CommonResponse + # @return [Search::Search] Parsed search payload. + attr_reader :models + # @return [Search::Search] Pagination metadata. + attr_reader :pagination_metadata + + def initialize(server_response) + super + + @models = Search::SearchModels.new(server_response['models']) + @pagination_metadata = PaginationMetadata.new(server_response['pagination']) + end + + # String representation. + # @return [String] + def to_s + [ + 'Models', + '######', + models.to_s, + 'Pagination Metadata', + '###################', + pagination_metadata.to_s, + '', + ].join("\n") + end + end + end + end + end +end diff --git a/lib/mindee/v2/product/base_product.rb b/lib/mindee/v2/product/base_product.rb index a11e0eb1a..d6633a707 100644 --- a/lib/mindee/v2/product/base_product.rb +++ b/lib/mindee/v2/product/base_product.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative '../parsing/base_response' +require_relative '../../input/base_parameters' module Mindee module V2 diff --git a/lib/mindee/v2/product/classification/classification.rb b/lib/mindee/v2/product/classification/classification.rb index 0eff57a8f..cfea179aa 100644 --- a/lib/mindee/v2/product/classification/classification.rb +++ b/lib/mindee/v2/product/classification/classification.rb @@ -6,6 +6,7 @@ module Mindee module V2 module Product + # Classification module. module Classification # Classification product. class Classification < BaseProduct diff --git a/lib/mindee/v2/product/classification/classification_inference.rb b/lib/mindee/v2/product/classification/classification_inference.rb index 837c19c27..da7042e5a 100644 --- a/lib/mindee/v2/product/classification/classification_inference.rb +++ b/lib/mindee/v2/product/classification/classification_inference.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative 'classification_result' +require_relative '../../parsing/base_inference' module Mindee module V2 diff --git a/lib/mindee/v2/product/classification/params/classification_parameters.rb b/lib/mindee/v2/product/classification/params/classification_parameters.rb index 398b218e5..2fcd57dab 100644 --- a/lib/mindee/v2/product/classification/params/classification_parameters.rb +++ b/lib/mindee/v2/product/classification/params/classification_parameters.rb @@ -4,6 +4,7 @@ module Mindee module V2 module Product module Classification + # Classification parameters. module Params # Parameters accepted by the classification utility v2 endpoint. class ClassificationParameters < Mindee::Input::BaseParameters diff --git a/lib/mindee/v2/product/crop/crop.rb b/lib/mindee/v2/product/crop/crop.rb index 24211cfb3..edcec424f 100644 --- a/lib/mindee/v2/product/crop/crop.rb +++ b/lib/mindee/v2/product/crop/crop.rb @@ -6,6 +6,7 @@ module Mindee module V2 module Product + # Crop module. module Crop # Crop product. class Crop < BaseProduct diff --git a/lib/mindee/v2/product/crop/crop_item.rb b/lib/mindee/v2/product/crop/crop_item.rb index 036b8c433..74f024d4c 100644 --- a/lib/mindee/v2/product/crop/crop_item.rb +++ b/lib/mindee/v2/product/crop/crop_item.rb @@ -8,13 +8,13 @@ module Crop class CropItem # @return [String] Type or classification of the detected object. attr_reader :object_type - # @return [Parsing::V2::Field::FieldLocation] Coordinates of the detected object on the document. + # @return [V2::Parsing::Field::FieldLocation] Coordinates of the detected object on the document. attr_reader :location # @param server_response [Hash] Hash representation of the JSON returned by the service. def initialize(server_response) @object_type = server_response['object_type'] - @location = Mindee::Parsing::V2::Field::FieldLocation.new(server_response['location']) + @location = Mindee::V2::Parsing::Field::FieldLocation.new(server_response['location']) end # String representation. @@ -22,6 +22,16 @@ def initialize(server_response) def to_s "* :Location: #{location}\n :Object Type: #{object_type}" end + + # Extract all crop items from this page + # + # @param input_source [Mindee::Input::Source::LocalInputSource] Local file to extract from + # @return [ExtractedImage] + def extract_from_file(input_source) + Image::ImageExtractor.extract_multiple_images_from_source( + input_source, @location.page, [@location.polygon] + )[0] + end end end end diff --git a/lib/mindee/v2/product/crop/crop_response.rb b/lib/mindee/v2/product/crop/crop_response.rb index 90ada7242..c2ec8f4f7 100644 --- a/lib/mindee/v2/product/crop/crop_response.rb +++ b/lib/mindee/v2/product/crop/crop_response.rb @@ -25,6 +25,14 @@ def initialize(server_response) def to_s @inference.to_s end + + # Apply the crop inference to a file and return a list of extracted images. + # + # @param input_source [Mindee::Input::Source::LocalInputSource] Local file to extract from + # @return [FileOperation::CropFiles] List of extracted PDFs + def extract_from_file(input_source) + FileOperation::Crop.extract_crops(input_source, @inference.result.crops) + end end end end diff --git a/lib/mindee/v2/product/crop/params/crop_parameters.rb b/lib/mindee/v2/product/crop/params/crop_parameters.rb index 712fe7cec..0b52c4ec4 100644 --- a/lib/mindee/v2/product/crop/params/crop_parameters.rb +++ b/lib/mindee/v2/product/crop/params/crop_parameters.rb @@ -4,6 +4,7 @@ module Mindee module V2 module Product module Crop + # Crop parameters. module Params # Parameters accepted by the crop utility v2 endpoint. class CropParameters < Mindee::Input::BaseParameters diff --git a/lib/mindee/v2/product/extraction/extraction.rb b/lib/mindee/v2/product/extraction/extraction.rb index c01afee31..e318214fd 100644 --- a/lib/mindee/v2/product/extraction/extraction.rb +++ b/lib/mindee/v2/product/extraction/extraction.rb @@ -6,10 +6,12 @@ module Mindee module V2 module Product + # Extraction module. module Extraction # Extraction product. # Note: currently a placeholder for the `Inference` class. - class Extraction < Mindee::Parsing::V2::Inference + class Extraction < Product::BaseProduct + @slug = 'extraction' @params_type = Product::Extraction::Params::ExtractionParameters @response_type = Product::Extraction::ExtractionResponse end diff --git a/lib/mindee/v2/product/extraction/extraction_inference.rb b/lib/mindee/v2/product/extraction/extraction_inference.rb index 08f66d173..e8cc017bb 100644 --- a/lib/mindee/v2/product/extraction/extraction_inference.rb +++ b/lib/mindee/v2/product/extraction/extraction_inference.rb @@ -1,22 +1,37 @@ # frozen_string_literal: true -require_relative '../../../parsing/v2/inference' +require_relative 'extraction_response' require_relative 'extraction_result' +require_relative 'params/extraction_parameters' module Mindee module V2 module Product module Extraction # Extraction inference. - class ExtractionInference < Mindee::Parsing::V2::Inference - # @return [ExtractionResult] Parsed inference payload. + class ExtractionInference < Mindee::V2::Parsing::BaseInference + # @return [InferenceActiveOptions] Options which were activated during the inference. + attr_reader :active_options + # @return [ExtractionResult] Result contents. attr_reader :result # @param server_response [Hash] Hash representation of the JSON returned by the service. def initialize(server_response) super - @result = Mindee::V2::Product::Extraction::ExtractionResult.new(server_response['result']) + @active_options = V2::Parsing::InferenceActiveOptions.new(server_response['active_options']) + @result = ExtractionResult.new(server_response['result']) + end + + # String representation. + # @return [String] + def to_s + [ + super, + @active_options.to_s, + @result.to_s, + '', + ].join("\n") end end end diff --git a/lib/mindee/v2/product/extraction/extraction_response.rb b/lib/mindee/v2/product/extraction/extraction_response.rb index 5b9f29b7f..af85cad30 100644 --- a/lib/mindee/v2/product/extraction/extraction_response.rb +++ b/lib/mindee/v2/product/extraction/extraction_response.rb @@ -1,6 +1,5 @@ # frozen_string_literal: true -require_relative '../../../parsing/v2/inference_response' require_relative 'extraction_inference' module Mindee @@ -8,14 +7,24 @@ module V2 module Product module Extraction # HTTP response wrapper that embeds a V2 Inference. - class ExtractionResponse < Mindee::Parsing::V2::InferenceResponse + class ExtractionResponse < Mindee::V2::Parsing::BaseResponse # @return [ExtractionInference] Parsed inference payload. attr_reader :inference + @slug = 'extraction' + @_params_type = Params::ExtractionParameters + def initialize(server_response) super + @inference = Mindee::V2::Product::Extraction::ExtractionInference.new(server_response['inference']) end + + # String representation. + # @return [String] + def to_s + @inference.to_s + end end end end diff --git a/lib/mindee/v2/product/extraction/extraction_result.rb b/lib/mindee/v2/product/extraction/extraction_result.rb index ac080ea3d..132052433 100644 --- a/lib/mindee/v2/product/extraction/extraction_result.rb +++ b/lib/mindee/v2/product/extraction/extraction_result.rb @@ -1,13 +1,42 @@ # frozen_string_literal: true -require_relative '../../../parsing/v2/inference_result' +require_relative '../../parsing' module Mindee module V2 module Product module Extraction # Result of an extraction utility inference. - class ExtractionResult < Mindee::Parsing::V2::InferenceResult + class ExtractionResult + # @return [Mindee::V2::Parsing::Field::InferenceFields] Fields produced by the model. + attr_reader :fields + # @return [Mindee::V2::Parsing::RawText, nil] Optional extra data. + attr_reader :raw_text + # @return [Mindee::V2::Parsing::RAGMetadata, nil] Optional RAG metadata. + attr_reader :rag + + # @param server_response [Hash] Hash version of the JSON returned by the API. + def initialize(server_response) + raise ArgumentError, 'server_response must be a Hash' unless server_response.is_a?(Hash) + + @fields = Parsing::Field::InferenceFields.new(server_response['fields']) + + @raw_text = server_response['raw_text'] ? Parsing::RawText.new(server_response['raw_text']) : nil + return unless server_response.key?('rag') && server_response['rag'] + + @rag = Parsing::RAGMetadata.new(server_response['rag']) + end + + # String representation. + # @return [String] + def to_s + parts = [ + 'Fields', + '======', + @fields.to_s, + ] + parts.join("\n") + end end end end diff --git a/lib/mindee/v2/product/extraction/params/data_schema.rb b/lib/mindee/v2/product/extraction/params/data_schema.rb new file mode 100644 index 000000000..84b72cbfa --- /dev/null +++ b/lib/mindee/v2/product/extraction/params/data_schema.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require_relative 'data_schema_replace' + +module Mindee + module V2 + module Product + module Extraction + # Extraction parameters. + module Params + # Modify the Data Schema. + class DataSchema + # @return [Mindee::V2::Product::Extraction::Params::DataSchemaReplace] + attr_reader :replace + + # @param data_schema [Hash, String] + def initialize(data_schema) + case data_schema + when String + parsed = JSON.parse(data_schema.to_s, object_class: Hash) + parsed.transform_keys!(&:to_sym) + @replace = DataSchemaReplace.new(parsed[:replace]) + when Hash + data_schema.transform_keys!(&:to_sym) + @replace = if data_schema[:replace].is_a?(DataSchemaReplace) + data_schema[:replace] + else + DataSchemaReplace.new(data_schema[:replace]) + end + when DataSchema + @replace = data_schema.replace + else + raise TypeError, 'Invalid Data Schema provided.' + end + end + + # @return [Hash] + def to_hash + { replace: @replace.to_hash } + end + + # @return [String] + def to_s + to_hash.to_json + end + end + end + end + end + end +end diff --git a/lib/mindee/v2/product/extraction/params/data_schema_field.rb b/lib/mindee/v2/product/extraction/params/data_schema_field.rb new file mode 100644 index 000000000..5d824842c --- /dev/null +++ b/lib/mindee/v2/product/extraction/params/data_schema_field.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +module Mindee + module V2 + module Product + module Extraction + module Params + # Data Schema Field. + class DataSchemaField + # @return [String] Display name for the field, also impacts inference results. + attr_reader :title + # @return [String] Name of the field in the data schema. + attr_reader :name + # @return [Boolean] Whether this field can contain multiple values. + attr_reader :is_array + # @return [String] Data type of the field. + attr_reader :type + # @return [Array, nil] Allowed values when type is `classification`. Leave empty for other types. + attr_reader :classification_values + # @return [Boolean, nil] Whether to remove duplicate values in the array. + # Only applicable if `is_array` is True. + attr_reader :unique_values + # @return [String, nil] Detailed description of what this field represents. + attr_reader :description + # @return [String, nil] Optional extraction guidelines. + attr_reader :guidelines + # @return [Array, nil] Nested fields. + attr_reader :nested_fields + + # @param field [Hash] + def initialize(field) + field.transform_keys!(&:to_sym) + @name = field[:name] + @title = field[:title] + @is_array = field[:is_array] + @type = field[:type] + @classification_values = field[:classification_values] + @unique_values = field[:unique_values] + @description = field[:description] + @guidelines = field[:guidelines] + @nested_fields = field[:nested_fields] + end + + # @return [Hash] + def to_hash + out = { + name: @name, + title: @title, + is_array: @is_array, + type: @type, + } # @type var out: Hash[Symbol, untyped] + out[:classification_values] = @classification_values unless @classification_values.nil? + out[:unique_values] = @unique_values unless @unique_values.nil? + out[:description] = @description unless @description.nil? + out[:guidelines] = @guidelines unless @guidelines.nil? + out[:nested_fields] = @nested_fields unless @nested_fields.nil? + out + end + + # @return [String] + def to_s + to_hash.to_json + end + end + end + end + end + end +end diff --git a/lib/mindee/v2/product/extraction/params/data_schema_replace.rb b/lib/mindee/v2/product/extraction/params/data_schema_replace.rb new file mode 100644 index 000000000..8ad45ce79 --- /dev/null +++ b/lib/mindee/v2/product/extraction/params/data_schema_replace.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +require_relative 'data_schema_field' + +module Mindee + module V2 + module Product + module Extraction + module Params + # The structure to completely replace the data schema of the model. + class DataSchemaReplace + # @return [Array] Subfields when type is `nested_object`. Leave empty for other types. + attr_reader :fields + + # @param data_schema_replace [Hash] + def initialize(data_schema_replace) + data_schema_replace.transform_keys!(&:to_sym) + fields_list = data_schema_replace[:fields] + raise Mindee::Error::MindeeError, 'Invalid Data Schema provided.' if fields_list.nil? + raise TypeError, 'Data Schema replacement fields cannot be empty.' if fields_list.empty? + + @fields = fields_list.map { |field| DataSchemaField.new(field) } + end + + # @return [Hash] + def to_hash + { fields: @fields.map(&:to_hash) } + end + + # @return [String] + def to_s + to_hash.to_json + end + end + end + end + end + end +end diff --git a/lib/mindee/v2/product/extraction/params/extraction_parameters.rb b/lib/mindee/v2/product/extraction/params/extraction_parameters.rb index daabbc72a..4eb17afd1 100644 --- a/lib/mindee/v2/product/extraction/params/extraction_parameters.rb +++ b/lib/mindee/v2/product/extraction/params/extraction_parameters.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true -require_relative '../../../../input/inference_parameters' +require_relative '../../../../input/base_parameters' +require_relative 'data_schema' module Mindee module V2 @@ -8,8 +9,114 @@ module Product module Extraction module Params # Parameters accepted by the extraction v2 endpoint. - # Currently a placeholder for the InferenceParameters class. - class ExtractionParameters < Input::InferenceParameters + class ExtractionParameters < Mindee::Input::BaseParameters + # @return [Boolean, nil] Enhance extraction accuracy with Retrieval-Augmented Generation. + attr_reader :rag + + # @return [Boolean, nil] Extract the full text content from the document as strings, + # and fill the raw_text` attribute. + attr_reader :raw_text + + # @return [Boolean, nil] Calculate bounding box polygons for all fields, + # and fill their `locations` attribute. + attr_reader :polygon + + # @return [Boolean, nil] Boost the precision and accuracy of all extractions. + # Calculate confidence scores for all fields, and fill their confidence attribute. + attr_reader :confidence + + # @return [String, nil] Additional text context used by the model during inference. + # Not recommended, for specific use only. + attr_reader :text_context + + # @return [DataSchemaField] + attr_reader :data_schema + + # @return [String] Slug for the endpoint. + def self.slug + 'extraction' + end + + # rubocop:disable Metrics/ParameterLists + # @param [String] model_id ID of the model + # @param [Boolean, nil] rag Whether to enable RAG. + # @param [Boolean, nil] raw_text Whether to enable rax text. + # @param [Boolean, nil] polygon Whether to enable polygons. + # @param [Boolean, nil] confidence Whether to enable confidence scores. + # @param [String, nil] file_alias File alias, if applicable. + # @param [Array, nil] webhook_ids + # @param [String, nil] text_context + # @param [Hash, nil] polling_options + # @param [Boolean, nil] close_file + # @param [DataSchemaField, String, Hash nil] data_schema + def initialize( + model_id, + rag: nil, + raw_text: nil, + polygon: nil, + confidence: nil, + file_alias: nil, + webhook_ids: nil, + text_context: nil, + polling_options: nil, + close_file: true, + data_schema: nil + ) + super( + model_id, + file_alias: file_alias, + webhook_ids: webhook_ids, + polling_options: polling_options, + close_file: close_file + ) + + @rag = rag + @raw_text = raw_text + @polygon = polygon + @confidence = confidence + @text_context = text_context + @data_schema = DataSchema.new(data_schema) unless data_schema.nil? + # rubocop:enable Metrics/ParameterLists + end + + # Appends inference-specific form data to the provided array. + # @param [Array] form_data Array of form fields + # @return [Array] + def append_form_data(form_data) + new_form_data = super + + new_form_data.push(['rag', @rag.to_s]) unless @rag.nil? + new_form_data.push(['raw_text', @raw_text.to_s]) unless @raw_text.nil? + new_form_data.push(['polygon', @polygon.to_s]) unless @polygon.nil? + new_form_data.push(['confidence', @confidence.to_s]) unless @confidence.nil? + new_form_data.push(['text_context', @text_context]) if @text_context + new_form_data.push(['data_schema', @data_schema.to_s]) if @data_schema + + new_form_data + end + + # Loads a prediction from a Hash. + # @param [Hash] params Parameters to provide as a hash. + # @return [ExtractionParameters] + def self.from_hash(params: {}) + rag = params.fetch(:rag, nil) + raw_text = params.fetch(:raw_text, nil) + polygon = params.fetch(:polygon, nil) + confidence = params.fetch(:confidence, nil) + base_params = load_from_hash(params: params) + new_params = base_params.merge(rag: rag, raw_text: raw_text, polygon: polygon, confidence: confidence) + model_id = new_params.fetch(:model_id) + + ExtractionParameters.new( + model_id, rag: rag, + raw_text: raw_text, + polygon: polygon, + confidence: confidence, + file_alias: params.fetch(:file_alias, nil), + webhook_ids: params.fetch(:webhook_ids, nil), + close_file: params.fetch(:close_file, true) + ) + end end end end diff --git a/lib/mindee/v2/product/ocr/ocr.rb b/lib/mindee/v2/product/ocr/ocr.rb index 50ff9e80b..9f81147cb 100644 --- a/lib/mindee/v2/product/ocr/ocr.rb +++ b/lib/mindee/v2/product/ocr/ocr.rb @@ -6,12 +6,13 @@ module Mindee module V2 module Product - module Ocr - # Ocr product. - class Ocr < BaseProduct + # OCR module. + module OCR + # OCR product. + class OCR < BaseProduct @slug = 'ocr' - @params_type = Mindee::V2::Product::Ocr::Params::OcrParameters - @response_type = Mindee::V2::Product::Ocr::OcrResponse + @params_type = Mindee::V2::Product::OCR::Params::OCRParameters + @response_type = Mindee::V2::Product::OCR::OCRResponse end end end diff --git a/lib/mindee/v2/product/ocr/ocr_inference.rb b/lib/mindee/v2/product/ocr/ocr_inference.rb index 5daeb0628..63937ba30 100644 --- a/lib/mindee/v2/product/ocr/ocr_inference.rb +++ b/lib/mindee/v2/product/ocr/ocr_inference.rb @@ -5,17 +5,17 @@ module Mindee module V2 module Product - module Ocr + module OCR # The inference result for an OCR utility request. - class OcrInference < Mindee::V2::Parsing::BaseInference - # @return [OcrResult] Parsed inference payload. + class OCRInference < Mindee::V2::Parsing::BaseInference + # @return [OCRResult] Parsed inference payload. attr_reader :result # @param server_response [Hash] Hash representation of the JSON returned by the service. def initialize(server_response) super - @result = OcrResult.new(server_response['result']) + @result = OCRResult.new(server_response['result']) end # String representation. diff --git a/lib/mindee/v2/product/ocr/ocr_page.rb b/lib/mindee/v2/product/ocr/ocr_page.rb index 5de396885..1da88823f 100644 --- a/lib/mindee/v2/product/ocr/ocr_page.rb +++ b/lib/mindee/v2/product/ocr/ocr_page.rb @@ -5,17 +5,17 @@ module Mindee module V2 module Product - module Ocr + module OCR # OCR result for a single page. - class OcrPage - # @return [Array] List of words extracted from the document page. + class OCRPage + # @return [Array] List of words extracted from the document page. attr_reader :words # @return [String] Full text content extracted from the document page. attr_reader :content # @param server_response [Hash] Hash representation of the JSON returned by the service. def initialize(server_response) - @words = server_response['words'].map { |word| OcrWord.new(word) } + @words = server_response['words'].map { |word| OCRWord.new(word) } @content = server_response['content'] end @@ -23,7 +23,7 @@ def initialize(server_response) # @return [String] def to_s ocr_words = "\n" - ocr_words += @words.map(&:to_s).join("\n\n") if @words&.any? + ocr_words += @words.join("\n\n") if @words&.any? "OCR Words\n======#{ocr_words}\n\n:Content: #{@content}" end end diff --git a/lib/mindee/v2/product/ocr/ocr_response.rb b/lib/mindee/v2/product/ocr/ocr_response.rb index 3bac4d1e9..0516e5356 100644 --- a/lib/mindee/v2/product/ocr/ocr_response.rb +++ b/lib/mindee/v2/product/ocr/ocr_response.rb @@ -7,17 +7,17 @@ module Mindee module V2 module Product - module Ocr + module OCR # HTTP response wrapper that embeds a V2 Inference. - class OcrResponse < Mindee::V2::Parsing::BaseResponse - # @return [OcrInference] Parsed inference payload. + class OCRResponse < Mindee::V2::Parsing::BaseResponse + # @return [OCRInference] Parsed inference payload. attr_reader :inference # @param server_response [Hash] Hash parsed from the API JSON response. def initialize(server_response) super - @inference = OcrInference.new(server_response['inference']) + @inference = OCRInference.new(server_response['inference']) end # String representation. diff --git a/lib/mindee/v2/product/ocr/ocr_result.rb b/lib/mindee/v2/product/ocr/ocr_result.rb index 093a6ae9d..c0eebb8eb 100644 --- a/lib/mindee/v2/product/ocr/ocr_result.rb +++ b/lib/mindee/v2/product/ocr/ocr_result.rb @@ -5,17 +5,17 @@ module Mindee module V2 module Product - module Ocr + module OCR # Result of a ocr utility inference. - class OcrResult - # @return [Array] List of OCR results for each page in the document. + class OCRResult + # @return [Array] List of OCR results for each page in the document. attr_reader :pages # @param server_response [Hash] Hash representation of the JSON returned by the service. def initialize(server_response) @pages = if server_response.key?('pages') server_response['pages'].map do |pages| - OcrPage.new(pages) + OCRPage.new(pages) end end end diff --git a/lib/mindee/v2/product/ocr/ocr_word.rb b/lib/mindee/v2/product/ocr/ocr_word.rb index 489c7dc85..3e5cce3a6 100644 --- a/lib/mindee/v2/product/ocr/ocr_word.rb +++ b/lib/mindee/v2/product/ocr/ocr_word.rb @@ -3,9 +3,9 @@ module Mindee module V2 module Product - module Ocr + module OCR # OCR result for a single word extracted from the document page. - class OcrWord + class OCRWord # @return [String] Text content of the word. attr_reader :content # @return [Mindee::Geometry::Polygon] Position information as a list of points in clockwise order. diff --git a/lib/mindee/v2/product/ocr/params/ocr_parameters.rb b/lib/mindee/v2/product/ocr/params/ocr_parameters.rb index ca068c83a..976423150 100644 --- a/lib/mindee/v2/product/ocr/params/ocr_parameters.rb +++ b/lib/mindee/v2/product/ocr/params/ocr_parameters.rb @@ -3,10 +3,11 @@ module Mindee module V2 module Product - module Ocr + module OCR + # OCR Parameters. module Params # Parameters accepted by the ocr utility v2 endpoint. - class OcrParameters < Mindee::Input::BaseParameters + class OCRParameters < Mindee::Input::BaseParameters # @return [String] Slug for the endpoint. def self.slug 'ocr' @@ -29,9 +30,9 @@ def initialize( # Loads the parameters from a Hash. # @param [Hash] params Parameters to provide as a hash. - # @return [OcrParameters] + # @return [OCRParameters] def self.from_hash(params: {}) - OcrParameters.new( + OCRParameters.new( params.fetch(:model_id), file_alias: params.fetch(:file_alias, nil), webhook_ids: params.fetch(:webhook_ids, nil), diff --git a/lib/mindee/v2/product/split/params/split_parameters.rb b/lib/mindee/v2/product/split/params/split_parameters.rb index 57dd79b8b..f06b7fd00 100644 --- a/lib/mindee/v2/product/split/params/split_parameters.rb +++ b/lib/mindee/v2/product/split/params/split_parameters.rb @@ -3,7 +3,9 @@ module Mindee module V2 module Product + # Split module. module Split + # Split parameters. module Params # Parameters accepted by the split utility v2 endpoint. class SplitParameters < Mindee::Input::BaseParameters diff --git a/lib/mindee/v2/product/split/split_range.rb b/lib/mindee/v2/product/split/split_range.rb index 6eaabd12c..f53d81f31 100644 --- a/lib/mindee/v2/product/split/split_range.rb +++ b/lib/mindee/v2/product/split/split_range.rb @@ -23,6 +23,14 @@ def initialize(server_response) def to_s "* :Page Range: #{@page_range}\n :Document Type: #{@document_type}" end + + # Apply the split range inference to a file and return a single extracted PDF. + # + # @param input_source [Mindee::Input::Source::LocalInputSource] Local file to extract from + # @return [PDF::ExtractedPDF] + def extract_from_file(input_source) + FileOperation::Split.extract_single_split(input_source, @page_range) + end end end end diff --git a/lib/mindee/v2/product/split/split_response.rb b/lib/mindee/v2/product/split/split_response.rb index 9fdafae18..53d552bbe 100644 --- a/lib/mindee/v2/product/split/split_response.rb +++ b/lib/mindee/v2/product/split/split_response.rb @@ -25,6 +25,14 @@ def initialize(server_response) def to_s @inference.to_s end + + # Extracts the crops from the input source. + # @param input_source [Mindee::Input::Source::LocalInputSource] Path to the file or a File object. + # @return [FileOperation::SplitFiles] + def extract_from_file(input_source) + splits = @inference.result.splits.map(&:page_range) + FileOperation::Split.extract_splits(input_source, splits) + end end end end diff --git a/lib/mindee/version.rb b/lib/mindee/version.rb index 548479647..16c9cec1d 100644 --- a/lib/mindee/version.rb +++ b/lib/mindee/version.rb @@ -3,7 +3,7 @@ # Mindee module Mindee # Current version. - VERSION = '4.13.0' + VERSION = '5.0.0.alpha1' # Finds and return the current platform. # @return [Symbol, Hash[String | Symbol, Regexp], Nil?] diff --git a/mindee-lite.gemspec b/mindee-lite.gemspec new file mode 100644 index 000000000..5d894ea86 --- /dev/null +++ b/mindee-lite.gemspec @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require_relative 'lib/mindee/version' + +Gem::Specification.new do |spec| + spec.name = 'mindee-lite' + spec.version = Mindee::VERSION + spec.authors = ['Mindee, SA'] + spec.email = ['opensource@mindee.co'] + + spec.summary = 'Mindee API Helper Library for Ruby (Lite)' + spec.description = "Quickly and easily connect to Mindee's API services using Ruby. This lite version omits " \ + 'heavy image and PDF processing dependencies.' + spec.homepage = 'https://github.com/mindee/mindee-api-ruby' + spec.license = 'MIT' + + spec.metadata['homepage_uri'] = 'https://mindee.com/' + spec.metadata['source_code_uri'] = 'https://github.com/mindee/mindee-api-ruby' + spec.metadata['changelog_uri'] = 'https://github.com/mindee/mindee-api-ruby/blob/main/CHANGELOG.md' + spec.metadata['rubygems_mfa_required'] = 'true' + + spec.files = Dir.chdir(File.expand_path(__dir__)) do + `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(.github|spec|features)/}) } + end + spec.bindir = 'bin' + spec.executables = Dir.children('bin') + .select { |f| File.file?(File.join('bin', f)) } + .reject { |f| f == 'products.rb' } + spec.require_paths = ['lib'] + + spec.required_ruby_version = Gem::Requirement.new('>= 3.2') + + spec.add_dependency 'base64', '~> 0.3' + spec.add_dependency 'logger', '~> 1.7' + spec.add_dependency 'marcel', '~> 1.1' +end diff --git a/mindee.gemspec b/mindee.gemspec index eeba5d4e2..ed46b531c 100644 --- a/mindee.gemspec +++ b/mindee.gemspec @@ -22,23 +22,23 @@ Gem::Specification.new do |spec| `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(.github|spec|features)/}) } end spec.bindir = 'bin' - spec.executables = Dir['bin/*'].map { |f| File.basename(f) }.reject { |f| f == 'cli_products.rb' } + spec.executables = Dir.children('bin') + .select { |f| File.file?(File.join('bin', f)) } + .reject { |f| f == 'products.rb' } spec.require_paths = ['lib'] - spec.required_ruby_version = Gem::Requirement.new('>= 3.0') + spec.required_ruby_version = Gem::Requirement.new('>= 3.2') - spec.add_dependency 'base64', '~> 0.1' - spec.add_dependency 'marcel', '~> 1.0' + spec.add_dependency 'base64', '~> 0.3' + spec.add_dependency 'logger', '~> 1.7' + spec.add_dependency 'marcel', '~> 1.1' spec.add_dependency 'mini_magick', '>= 4', '< 6' spec.add_dependency 'origamindee', '~> 4.0' - spec.add_dependency 'pdf-reader', '~> 2.14' - - spec.add_development_dependency 'openssl', '~> 3.3.2' - spec.add_development_dependency 'prism', '~> 1.3' - spec.add_development_dependency 'rake', '~> 13.2' - spec.add_development_dependency 'rbs', '~> 3.6' - spec.add_development_dependency 'rspec', '~> 3.13' - spec.add_development_dependency 'rubocop', '~> 1.76.0' - spec.add_development_dependency 'steep', '~> 1.7' + spec.add_dependency 'pdf-reader', '~> 2.15' + + spec.add_development_dependency 'bundle-audit', '~> 0.2.0' + spec.add_development_dependency 'rbs', '~> 3.10' + spec.add_development_dependency 'rubocop', '~> 1.86' + spec.add_development_dependency 'steep', '~> 1.10' spec.add_development_dependency 'yard', '~> 0.9' end diff --git a/sig/custom/marcel.rbs b/sig/custom/marcel.rbs index d78347361..dd147354a 100644 --- a/sig/custom/marcel.rbs +++ b/sig/custom/marcel.rbs @@ -1,3 +1,3 @@ module Marcel MimeType: untyped -end \ No newline at end of file +end diff --git a/sig/custom/net_http.rbs b/sig/custom/net_http.rbs index 9d24bc515..c53bad3b8 100644 --- a/sig/custom/net_http.rbs +++ b/sig/custom/net_http.rbs @@ -40,4 +40,4 @@ module Net def body: -> untyped def code: -> String? end -end \ No newline at end of file +end diff --git a/sig/custom/origami.rbs b/sig/custom/origami.rbs index f203f39bb..4a71b78b3 100644 --- a/sig/custom/origami.rbs +++ b/sig/custom/origami.rbs @@ -56,4 +56,4 @@ module Origami def data= : (String | StringIO) -> void def dictionary : -> Hash[Symbol, untyped] end -end \ No newline at end of file +end diff --git a/sig/mindee.rbs b/sig/mindee.rbs index 927d1ddb5..bdf2c27fb 100644 --- a/sig/mindee.rbs +++ b/sig/mindee.rbs @@ -1,10 +1,11 @@ class Object private + def logger: -> Logger end module Mindee - module Errors + module Error end module Extraction @@ -43,17 +44,19 @@ module Mindee end end - module Product - module EU - end + module V1 + module Product + module EU + end - module FR - end + module FR + end - module IND - end + module IND + end - module US + module US + end end end end diff --git a/sig/mindee/client.rbs b/sig/mindee/client.rbs deleted file mode 100644 index f4311337b..000000000 --- a/sig/mindee/client.rbs +++ /dev/null @@ -1,61 +0,0 @@ -# lib/mindee/client.rb - -module Mindee - OTS_OWNER: String - - class ParseOptions - attr_accessor all_words: bool - attr_accessor full_text: bool - attr_accessor close_file: bool - attr_accessor page_options: PageOptions - attr_accessor cropper: bool - attr_accessor rag: bool - attr_accessor workflow_id: String? - attr_accessor initial_delay_sec: Integer | Float - attr_accessor delay_sec: Integer | Float - attr_accessor max_retries: Integer - - def initialize: (params: Hash[String | Symbol, untyped]) -> void - end - - class WorkflowOptions - attr_accessor document_alias: (String?) - attr_accessor priority: (Symbol?) - attr_accessor full_text: bool - attr_accessor rag: bool? - attr_accessor public_url: (String?) - attr_accessor page_options: (PageOptions) - attr_accessor close_file: bool - - def initialize: (params: Hash[String | Symbol, untyped]) -> void - end - - class Client - @api_key: String? - - def initialize: (?api_key: String) -> void - def logger: () -> Logging - def parse: (Input::Source::LocalInputSource | Input::Source::URLInputSource, singleton(Parsing::Common::Inference), ?endpoint: (HTTP::Endpoint?), options: ParseOptions | Hash[String | Symbol, untyped]) -> Parsing::Common::ApiResponse - def parse_sync: (Input::Source::LocalInputSource | Input::Source::URLInputSource, singleton(Parsing::Common::Inference), HTTP::Endpoint, ParseOptions) -> Parsing::Common::ApiResponse - def enqueue: (Input::Source::LocalInputSource | Input::Source::URLInputSource, singleton(Parsing::Common::Inference), ?endpoint: (HTTP::Endpoint?), options: ParseOptions|Hash[String | Symbol, untyped]) -> Parsing::Common::ApiResponse - def parse_queued: (String, singleton(Parsing::Common::Inference), ?endpoint: HTTP::Endpoint?) -> Parsing::Common::ApiResponse - def enqueue_and_parse: (Input::Source::URLInputSource|Input::Source::LocalInputSource, singleton(Parsing::Common::Inference), HTTP::Endpoint, ParseOptions) -> Parsing::Common::ApiResponse - def execute_workflow: (Input::Source::URLInputSource|Input::Source::LocalInputSource, String, options: (Hash[String | Symbol, untyped] | WorkflowOptions)) -> Parsing::Common::WorkflowResponse - def load_prediction: (singleton(Parsing::Common::Inference), Input::LocalResponse) -> Parsing::Common::ApiResponse - def source_from_path: (String, ?repair_pdf: bool) -> Input::Source::PathInputSource - def source_from_bytes: (String, String, ?repair_pdf: bool) -> Input::Source::BytesInputSource - def source_from_b64string: (String, String, ?repair_pdf: bool) -> Input::Source::Base64InputSource - def source_from_file: (File, String, ?repair_pdf: bool) -> Input::Source::FileInputSource - def source_from_url: (String) -> Input::Source::URLInputSource - def create_endpoint: (endpoint_name: String, account_name: String, version: String) -> HTTP::Endpoint - - private - def normalize_parse_options: ((Hash[String | Symbol, untyped] | ParseOptions)) -> ParseOptions - def process_pdf_if_required: (Input::Source::LocalInputSource, ParseOptions | WorkflowOptions) -> void - def initialize_endpoint: (singleton(Parsing::Common::Inference), ?endpoint_name: String, ?account_name: String, ?version: String) -> HTTP::Endpoint - def validate_async_params: (Integer | Float, Integer | Float, Integer) -> void - def fix_endpoint_name: (singleton(Parsing::Common::Inference), String?) -> String - def fix_account_name: (String) -> String - def fix_version: (singleton(Parsing::Common::Inference), String) -> String - end -end diff --git a/sig/mindee/client_v2.rbs b/sig/mindee/client_v2.rbs deleted file mode 100644 index 66b5409c2..000000000 --- a/sig/mindee/client_v2.rbs +++ /dev/null @@ -1,21 +0,0 @@ -# lib/mindee/client_v2.rb - -OTS_OWNER: String -module Mindee - class ClientV2 - private attr_reader mindee_api: HTTP::MindeeApiV2 - - def logger: () -> Logger - def initialize: (?api_key: String) -> void - def get_inference: (String inference_id) -> Parsing::V2::InferenceResponse - def get_result: [T] (HTTP::_ProductClass[T] product, String resource) -> T - def get_result_url: [T] (HTTP::_ResponseFactory[T] response_class, String inference_id) -> T - def get_job: (String job_id) -> Parsing::V2::JobResponse - def enqueue_inference: (Input::Source::LocalInputSource | Input::Source::URLInputSource, Hash[String | Symbol, untyped] | Input::InferenceParameters params, ?disable_redundant_warnings: bool) -> Parsing::V2::JobResponse - def enqueue: [T] (HTTP::_ProductClass[T] product, Input::Source::LocalInputSource | Input::Source::URLInputSource, Hash[String | Symbol, untyped] | Input::BaseParameters params) -> Parsing::V2::JobResponse - def enqueue_and_get_result: [T] (HTTP::_ProductClass[T] product, Input::Source::LocalInputSource | Input::Source::URLInputSource, Hash[String | Symbol, untyped] | Input::BaseParameters params) -> T - def enqueue_and_get_inference: (Input::Source::LocalInputSource | Input::Source::URLInputSource, Hash[String | Symbol, untyped] | Input::InferenceParameters params, ?disable_redundant_warnings: bool) -> Parsing::V2::InferenceResponse - def validate_async_params: (Integer | Float, Integer | Float, Integer) -> void - def normalize_parameters: (singleton(Input::BaseParameters) param_class, Hash[String | Symbol, untyped] | Input::BaseParameters params) -> Input::BaseParameters - end -end diff --git a/sig/mindee/dependency.rbs b/sig/mindee/dependency.rbs new file mode 100644 index 000000000..cb1da8200 --- /dev/null +++ b/sig/mindee/dependency.rbs @@ -0,0 +1,13 @@ +module Mindee + module Dependency + MINDEE_DEPENDENCIES_LOAD_ERROR: String + + self.@all_deps_available: bool + + def self.check_all_dependencies: -> bool + + def self.all_deps_available?: -> bool + def self.require_all_deps!: -> void + + end +end diff --git a/sig/mindee/errors/mindee_error.rbs b/sig/mindee/error/mindee_error.rbs similarity index 81% rename from sig/mindee/errors/mindee_error.rbs rename to sig/mindee/error/mindee_error.rbs index 10dac7a6a..2c1838d01 100644 --- a/sig/mindee/errors/mindee_error.rbs +++ b/sig/mindee/error/mindee_error.rbs @@ -1,6 +1,6 @@ -# lib/mindee/errors/mindee_error.rb +# lib/mindee/error/mindee_error.rb module Mindee - module Errors + module Error class MindeeError < StandardError end class MindeeAPIError < MindeeError diff --git a/sig/mindee/errors/mindee_http_error.rbs b/sig/mindee/error/mindee_http_error.rbs similarity index 78% rename from sig/mindee/errors/mindee_http_error.rbs rename to sig/mindee/error/mindee_http_error.rbs index 2811fa700..56322508b 100644 --- a/sig/mindee/errors/mindee_http_error.rbs +++ b/sig/mindee/error/mindee_http_error.rbs @@ -1,7 +1,7 @@ -# lib/mindee/errors/mindee_http_error.rb +# lib/mindee/error/mindee_http_error.rb module Mindee - module Errors - class MindeeHTTPError < Errors::MindeeError + module Error + class MindeeHTTPError < Error::MindeeError attr_reader api_code: Integer attr_reader api_details: String attr_reader api_message: String diff --git a/sig/mindee/errors/mindee_http_error_v2.rbs b/sig/mindee/error/mindee_http_error_v2.rbs similarity index 52% rename from sig/mindee/errors/mindee_http_error_v2.rbs rename to sig/mindee/error/mindee_http_error_v2.rbs index 02e403a18..e50c86a4e 100644 --- a/sig/mindee/errors/mindee_http_error_v2.rbs +++ b/sig/mindee/error/mindee_http_error_v2.rbs @@ -1,15 +1,15 @@ -# lib/mindee/errors/mindee_http_error_v2.rb +# lib/mindee/error/mindee_http_error_v2.rb module Mindee - module Errors + module Error # API V2 HttpError class MindeeHTTPErrorV2 < MindeeError attr_reader detail: String attr_reader status: Integer attr_reader code: String attr_reader title: String - attr_reader errors: Array[Parsing::V2::ErrorItem] + attr_reader errors: Array[V2::Parsing::ErrorItem] - def initialize: (Hash[String, untyped] | Mindee::Parsing::V2::ErrorResponse) -> void + def initialize: (Hash[String, untyped] | Mindee::V2::Parsing::ErrorResponse) -> void end end end diff --git a/sig/mindee/errors/mindee_http_unknown_error_v2.rbs b/sig/mindee/error/mindee_http_unknown_error_v2.rbs similarity index 73% rename from sig/mindee/errors/mindee_http_unknown_error_v2.rbs rename to sig/mindee/error/mindee_http_unknown_error_v2.rbs index 459cef087..e81b1e33a 100644 --- a/sig/mindee/errors/mindee_http_unknown_error_v2.rbs +++ b/sig/mindee/error/mindee_http_unknown_error_v2.rbs @@ -1,6 +1,6 @@ -# lib/mindee/errors/mindee_http_unknown_error_v2.rb +# lib/mindee/error/mindee_http_unknown_error_v2.rb module Mindee - module Errors + module Error # Unknown HTTP error for the V2 API. class MindeeHTTPUnknownErrorV2 < MindeeHTTPErrorV2 def initialize: (Hash[String|Symbol, untyped]) -> void diff --git a/sig/mindee/errors/mindee_input_error.rbs b/sig/mindee/error/mindee_input_error.rbs similarity index 86% rename from sig/mindee/errors/mindee_input_error.rbs rename to sig/mindee/error/mindee_input_error.rbs index 94fd985f5..9a34092e5 100644 --- a/sig/mindee/errors/mindee_input_error.rbs +++ b/sig/mindee/error/mindee_input_error.rbs @@ -1,6 +1,6 @@ -# lib/mindee/errors/mindee_input_error.rb +# lib/mindee/error/mindee_input_error.rb module Mindee - module Errors + module Error class MindeeInputError < MindeeError end class MindeeSourceError < MindeeInputError diff --git a/sig/mindee/extraction/multi_receipts_extractor.rbs b/sig/mindee/extraction/multi_receipts_extractor.rbs deleted file mode 100644 index ee8c191a6..000000000 --- a/sig/mindee/extraction/multi_receipts_extractor.rbs +++ /dev/null @@ -1,6 +0,0 @@ -# lib/mindee/extraction/multi_receipts_extractor.rb -module Mindee - module Extraction - def self.extract_receipts: (untyped, untyped) -> Array[untyped] - end -end diff --git a/sig/mindee/http/api_settings_v2.rbs b/sig/mindee/http/api_settings_v2.rbs deleted file mode 100644 index 594b926cd..000000000 --- a/sig/mindee/http/api_settings_v2.rbs +++ /dev/null @@ -1,23 +0,0 @@ -# lib/mindee/http/api_settings_v2.rb -module Mindee - module HTTP - class ApiSettingsV2 - MINDEE_V2_API_KEY_ENV_NAME: String - MINDEE_V2_API_KEY_DEFAULT: String? - MINDEE_V2_BASE_URL_ENV_NAME: String - MINDEE_V2_BASE_URL_DEFAULT: String - MINDEE_V2_REQUEST_TIMEOUT_ENV_NAME: String - MINDEE_V2_TIMEOUT_DEFAULT: Integer - USER_AGENT: String - - def logger: () -> Logger - attr_reader api_key: String? - attr_reader base_url: String - attr_reader request_timeout: Integer - attr_reader user_agent: String - - def initialize: (?api_key: String?) -> void - def check_api_key: -> void - end - end -end diff --git a/sig/mindee/http/endpoint.rbs b/sig/mindee/http/endpoint.rbs deleted file mode 100644 index 09909126b..000000000 --- a/sig/mindee/http/endpoint.rbs +++ /dev/null @@ -1,29 +0,0 @@ -# lib/mindee/http/endpoint.rb -module Mindee - module HTTP - API_KEY_ENV_NAME: String - API_KEY_DEFAULT: String? - BASE_URL_ENV_NAME: String - BASE_URL_DEFAULT: String - REQUEST_TIMEOUT_ENV_NAME: String - TIMEOUT_DEFAULT: Integer - USER_AGENT: String - class Endpoint - attr_reader api_key: String - attr_reader base_url: String - attr_reader request_timeout: Integer - attr_reader url_root: String - - def logger: () -> Logger - def initialize: (String, String, String?, ?api_key: String) -> String - def predict: (Input::Source::LocalInputSource | Input::Source::URLInputSource, ParseOptions) -> [Hash[String | Symbol, untyped], String] - def predict_async: (Input::Source::LocalInputSource | Input::Source::URLInputSource, ParseOptions) -> [Hash[String | Symbol, untyped], String] - def parse_async: (String) -> [Hash[String | Symbol, untyped], String] - def predict_req_post: (Input::Source::LocalInputSource | Input::Source::URLInputSource, ParseOptions) -> Net::HTTPResponse - def document_queue_req_post: (Input::Source::LocalInputSource | Input::Source::URLInputSource, ParseOptions) -> Net::HTTPResponse - def document_queue_req_get: (String) -> Net::HTTPResponse - def check_api_key: -> void - def configure_ssl: (Net::HTTP) -> void - end - end -end diff --git a/sig/mindee/http/http_error_handler.rbs b/sig/mindee/http/http_error_handler.rbs index 1ab8b3697..e5b30622b 100644 --- a/sig/mindee/http/http_error_handler.rbs +++ b/sig/mindee/http/http_error_handler.rbs @@ -4,11 +4,11 @@ module Mindee module ErrorHandler def extract_error: (Hash[String | Symbol, untyped]) -> Hash[String | Symbol, untyped]? def create_error_obj: (Hash[String | Symbol, untyped]) -> Hash[String | Symbol, untyped] - def self.generate_v2_error: (Hash[String, Integer | String]) -> Errors::MindeeHTTPErrorV2 - def generate_v2_error: (Hash[Symbol, String | Integer]) -> Errors::MindeeHTTPErrorV2 + def self.generate_v2_error: (Hash[String, Integer | String]) -> Error::MindeeHTTPErrorV2 + def generate_v2_error: (Hash[Symbol, String | Integer]) -> Error::MindeeHTTPErrorV2 - def self.handle_error: (String, Net::HTTPResponse) -> Errors::MindeeHTTPError - def handle_error: (String, Net::HTTPResponse) -> Errors::MindeeHTTPError + def self.handle_error: (String, Net::HTTPResponse) -> Error::MindeeHTTPError + def handle_error: (String, Net::HTTPResponse) -> Error::MindeeHTTPError def handle_v2_error: (Hash[String | Symbol, untyped]) -> void end end diff --git a/sig/mindee/http/mindee_api_v2.rbs b/sig/mindee/http/mindee_api_v2.rbs deleted file mode 100644 index c67b09b3a..000000000 --- a/sig/mindee/http/mindee_api_v2.rbs +++ /dev/null @@ -1,38 +0,0 @@ -# lib/mindee/http/mindee_api_v2.rbs -module Mindee - module HTTP - interface _ResponseFactory[T] - def new: (Hash[String | Symbol, untyped]) -> T - end - - interface _ProductClass[T] - def slug: () -> String - def response_type: () -> _ResponseFactory[T] - def params_type: () -> singleton(Input::BaseParameters) - end - - class MindeeApiV2 - attr_reader settings: ApiSettingsV2 - - def initialize: (?api_key: String?) -> void - - def req_get_result: [T] (_ProductClass[T] product, String resource) -> T - - def req_post_enqueue: (Input::Source::LocalInputSource | Input::Source::URLInputSource, Input::BaseParameters) -> Parsing::V2::JobResponse - def req_get_inference: (String) -> Parsing::V2::InferenceResponse - def req_get_job: (String) -> Parsing::V2::JobResponse - def process_response: (Net::HTTPResponse?) -> Hash[String | Symbol, untyped] - def poll: (String) -> Net::HTTPResponse - def inference_job_req_get: (String) -> Net::HTTPResponse - def inference_result_req_get: (String) -> Net::HTTPResponse - def result_req_get: [T] (String, _ProductClass[T] product) -> Net::HTTPResponse - def enqueue: (Input::Source::LocalInputSource | Input::Source::URLInputSource, Input::BaseParameters) -> Net::HTTPResponse? - - private - def req_get_job_url: (String) -> Parsing::V2::JobResponse - def req_get_result_url: [T] (_ResponseFactory[T] result_class, String url) -> T - def uri?: (String) -> bool - def enqueue_form_options: (Array[untyped], Input::InferenceParameters) -> Array[untyped] - end - end -end diff --git a/sig/mindee/http/workflow_endpoint.rbs b/sig/mindee/http/workflow_endpoint.rbs deleted file mode 100644 index 6795f44f2..000000000 --- a/sig/mindee/http/workflow_endpoint.rbs +++ /dev/null @@ -1,20 +0,0 @@ -# lib/mindee/http/workflow_endpoint.rb -module Mindee - module HTTP - class WorkflowEndpoint - def api_key: -> String - - def request_timeout: -> Integer - - def url: -> String - - def initialize: (untyped, ?api_key: String) -> String - - def execute_workflow: (Input::Source::LocalInputSource | Input::Source::URLInputSource, WorkflowOptions) -> [Hash[String, untyped], String] - - def workflow_execution_req_post: (Input::Source::LocalInputSource | Input::Source::URLInputSource, WorkflowOptions) -> Net::HTTPResponse? - - def check_api_key: -> nil - end - end -end diff --git a/sig/mindee/image/extracted_image.rbs b/sig/mindee/image/extracted_image.rbs index 8f7c3d872..f60abe127 100644 --- a/sig/mindee/image/extracted_image.rbs +++ b/sig/mindee/image/extracted_image.rbs @@ -6,10 +6,16 @@ module Mindee def page_id: -> Integer def element_id: -> Integer def buffer: -> StringIO - def internal_file_name: -> String - def initialize: (Input::Source::LocalInputSource, Integer, Integer) -> Integer + def filename: -> String + def initialize: ( + Input::Source::LocalInputSource | Input::Source::BytesInputSource, + Integer, + Integer?, + ?preserve_input_filename: bool + ) -> Integer def write_to_file: (String, ?String?) -> void def as_source: -> Input::Source::BytesInputSource + def as_input_source: -> Input::Source::BytesInputSource end end end diff --git a/sig/mindee/image/image_extractor.rbs b/sig/mindee/image/image_extractor.rbs index a92fe154c..5f57c5121 100644 --- a/sig/mindee/image/image_extractor.rbs +++ b/sig/mindee/image/image_extractor.rbs @@ -6,7 +6,7 @@ module Mindee def self.to_blob: () -> String def self.extract_multiple_images_from_source: (Input::Source::LocalInputSource, Integer, Array[Array[Geometry::Point] |Geometry::Polygon | Geometry::Quadrilateral]) -> Array[ExtractedImage] def self.extract_images_from_polygons: (Input::Source::LocalInputSource, StringIO | File, Integer, Array[Array[Geometry::Point] | Geometry::Polygon | Geometry::Quadrilateral]) -> Array[ExtractedImage] - def self.create_extracted_image: (StringIO | File, String, Integer, Integer) -> void + def self.create_extracted_image: (StringIO | File, String, Integer, Integer) -> ExtractedImage def self.load_input_source_pdf_page_as_stringio: (Input::Source::LocalInputSource, Integer) -> (StringIO | File) end end diff --git a/sig/mindee/input/data_schema.rbs b/sig/mindee/input/data_schema.rbs deleted file mode 100644 index d7c99d994..000000000 --- a/sig/mindee/input/data_schema.rbs +++ /dev/null @@ -1,34 +0,0 @@ -module Mindee - module Input - class DataSchemaField - attr_reader title: String - attr_reader name: String - attr_reader is_array: bool - attr_reader type: String - attr_reader classification_values: String|nil - attr_reader unique_values: bool|nil - attr_reader description: String|nil - attr_reader guidelines: String|nil - attr_reader nested_fields: Array[Hash[String|Symbol, untyped]]|nil - - def initialize: (Hash[Symbol, untyped]) -> void - def to_hash: () -> Hash[Symbol, untyped] - def to_string: () -> String - end - - class DataSchemaReplace - attr_reader fields: Array[DataSchemaField] - def initialize: (Hash[Symbol, untyped]) -> void - def to_hash: () -> Hash[Symbol, untyped] - def to_string: () -> String - end - - class DataSchema - attr_reader replace: DataSchemaReplace - - def initialize: (Hash[String|Symbol, untyped]|String|DataSchema) -> void - def to_hash: () -> Hash[Symbol, untyped] - def to_s: -> String - end - end -end diff --git a/sig/mindee/input/inference_parameters.rbs b/sig/mindee/input/inference_parameters.rbs deleted file mode 100644 index b88d8ef27..000000000 --- a/sig/mindee/input/inference_parameters.rbs +++ /dev/null @@ -1,32 +0,0 @@ -# lib/mindee/input/inference_parameters.rb -module Mindee - module Input - class InferenceParameters < BaseParameters - def self.slug: -> String - - attr_reader confidence: bool? - attr_reader polygon: bool? - attr_reader rag: bool? - attr_reader raw_text: bool? - attr_reader text_context: String? - attr_reader data_schema: DataSchema? - - def initialize: ( - String, - ?rag: bool?, - ?raw_text: bool?, - ?polygon: bool?, - ?confidence: bool?, - ?file_alias: String?, - ?text_context: String?, - ?webhook_ids: Array[String]?, - ?polling_options: Hash[Symbol | String, untyped] | PollingOptions?, - ?close_file: bool?, - ?data_schema: DataSchema|String|Hash[Symbol | String, untyped]? - ) -> void - - def self.from_hash: (params: Hash[String | Symbol, untyped]) -> InferenceParameters - def append_form_data: (Array[Array[untyped]]) -> Array[Array[untyped]] - end - end -end diff --git a/sig/mindee/input/local_response.rbs b/sig/mindee/input/local_response.rbs index 4f0468fba..6b384f018 100644 --- a/sig/mindee/input/local_response.rbs +++ b/sig/mindee/input/local_response.rbs @@ -8,7 +8,7 @@ module Mindee def self.process_secret_key: (String) -> String def get_hmac_signature: (String) -> String def valid_hmac_signature?: (String, String) -> bool - def deserialize_response: (singleton(Parsing::V2::CommonResponse))-> (Parsing::V2::JobResponse | Mindee::Parsing::V2::InferenceResponse) + def deserialize_response: (singleton(V2::Parsing::CommonResponse))-> (V2::Parsing::CommonResponse) end end end diff --git a/sig/mindee/input/sources/local_input_source.rbs b/sig/mindee/input/sources/local_input_source.rbs index 76ea28548..103ae5d82 100644 --- a/sig/mindee/input/sources/local_input_source.rbs +++ b/sig/mindee/input/sources/local_input_source.rbs @@ -20,7 +20,6 @@ module Mindee def process_pdf: (PageOptions) -> StringIO? def read_contents: (?close: bool) -> [String?, Hash[:filename, String]] def page_count: -> Integer - def count_pages: -> Integer def write_to_file: (String?) -> void def compress!: (?quality: Integer, ?max_width: Integer?, ?max_height: Integer?, ?force_source_text: bool, ?disable_source_text: bool) -> Integer def source_text?: -> bool? diff --git a/sig/mindee/parsing/common/api_request.rbs b/sig/mindee/parsing/common/api_request.rbs deleted file mode 100644 index 4f5e652be..000000000 --- a/sig/mindee/parsing/common/api_request.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/parsing/common/api_request.rb -module Mindee - module Parsing - module Common - class ApiRequest - def error: -> Hash[String, untyped] - def ressources: -> Array[String] - def status: -> [RequestStatus, Symbol] - def status_code: -> Integer - def url: -> String - def initialize: (Hash[String, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/parsing/common/api_response.rbs b/sig/mindee/parsing/common/api_response.rbs deleted file mode 100644 index 126363bd0..000000000 --- a/sig/mindee/parsing/common/api_response.rbs +++ /dev/null @@ -1,27 +0,0 @@ -# lib/mindee/parsing/common/api_response.rb -module Mindee - module Parsing - module Common - module JobStatus - WAITING: :waiting - PROCESSING: :processing - COMPLETED: :completed - FAILURE: :failed - end - module RequestStatus - FAILURE: :failure - SUCCESS: :success - end - - - class ApiResponse - def logger: () -> Logger - def document: -> Parsing::Common::Document? - def job: -> Parsing::Common::Job? - def api_request: -> Parsing::Common::ApiRequest? - def raw_http: -> String - def initialize: (singleton(Parsing::Common::Inference), Hash[String | Symbol, untyped] | Net::HTTPResponse, String) -> void - end - end - end -end diff --git a/sig/mindee/parsing/common/document.rbs b/sig/mindee/parsing/common/document.rbs deleted file mode 100644 index d3d63803d..000000000 --- a/sig/mindee/parsing/common/document.rbs +++ /dev/null @@ -1,20 +0,0 @@ -# lib/mindee/parsing/common/document.rb -module Mindee - module Parsing - module Common - class Document - def inference: -> Inference - def name: -> String - def id: -> String - def extras: -> Extras::Extras? - def ocr: -> OCR::OCR? - def n_pages: -> Integer - def self.load_ocr: (Hash[String | Symbol, untyped]) -> Parsing::Common::OCR::OCR? - def self.extract_extras: (Hash[String | Symbol, untyped]) -> Parsing::Common::Extras::Extras? - def initialize: (singleton(Parsing::Common::Inference), Hash[String | Symbol, untyped]) -> void - def to_s: -> String - def inject_full_text_ocr: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/parsing/common/execution.rbs b/sig/mindee/parsing/common/execution.rbs deleted file mode 100644 index 3ba71c11c..000000000 --- a/sig/mindee/parsing/common/execution.rbs +++ /dev/null @@ -1,24 +0,0 @@ -# lib/mindee/parsing/common/execution.rb -module Mindee - module Parsing - module Common - class Execution - attr_reader available_at: Time? - attr_reader batch_name: String - attr_reader created_at: Time - attr_reader file: ExecutionFile - attr_reader id: String - attr_reader inference: Inference - attr_reader priority: Symbol? - attr_reader reviewed_at: Time? - attr_reader reviewed_prediction: Prediction? - attr_reader status: Symbol - attr_reader type: String? - attr_reader uploaded_at: Time? - attr_reader workflow_id: String - - def initialize: (singleton(Parsing::Common::Inference), Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/parsing/common/execution_file.rbs b/sig/mindee/parsing/common/execution_file.rbs deleted file mode 100644 index 4d8d16f00..000000000 --- a/sig/mindee/parsing/common/execution_file.rbs +++ /dev/null @@ -1,12 +0,0 @@ -# lib/mindee/parsing/common/execution_file.rb -module Mindee - module Parsing - module Common - class ExecutionFile - def name: -> String - def alias: -> String? - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/parsing/common/execution_priority.rbs b/sig/mindee/parsing/common/execution_priority.rbs deleted file mode 100644 index b8a053291..000000000 --- a/sig/mindee/parsing/common/execution_priority.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/parsing/common/execution_priority.rb -module Mindee - module Parsing - module Common - module ExecutionPriority - LOW: :low - MEDIUM: :medium - HIGH: :high - def self.to_priority: (untyped) -> (:high | :low | :medium)? - end - end - end -end diff --git a/sig/mindee/parsing/common/extras/cropper_extra.rbs b/sig/mindee/parsing/common/extras/cropper_extra.rbs deleted file mode 100644 index 958c5201d..000000000 --- a/sig/mindee/parsing/common/extras/cropper_extra.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/parsing/common/extras/cropper_extra.rb -module Mindee - module Parsing - module Common - module Extras - class CropperExtra - attr_reader croppings: Array[Standard::PositionField] - - def initialize: (Hash[String | Symbol, untyped], ?Integer?) -> void - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/parsing/common/extras/extras.rbs b/sig/mindee/parsing/common/extras/extras.rbs deleted file mode 100644 index 9c549a234..000000000 --- a/sig/mindee/parsing/common/extras/extras.rbs +++ /dev/null @@ -1,19 +0,0 @@ -# lib/mindee/parsing/common/extras/extras.rb -module Mindee - module Parsing - module Common - module Extras - class Extras - attr_reader cropper: CropperExtra? - attr_reader full_text_ocr: FullTextOCRExtra - attr_reader rag: RAGExtra? - - def initialize: (Hash[String | Symbol, untyped]) -> void - def to_s: -> String - def add_artificial_extra: (Hash[String | Symbol, untyped]) -> void - end - def empty?: -> bool - end - end - end -end diff --git a/sig/mindee/parsing/common/extras/full_text_ocr_extra.rbs b/sig/mindee/parsing/common/extras/full_text_ocr_extra.rbs deleted file mode 100644 index a7eb65dff..000000000 --- a/sig/mindee/parsing/common/extras/full_text_ocr_extra.rbs +++ /dev/null @@ -1,16 +0,0 @@ -# lib/mindee/parsing/common/extras/full_text_ocr_extra.rb -module Mindee - module Parsing - module Common - module Extras - class FullTextOCRExtra - def contents: -> String? - def language: -> String? - def initialize: (Hash[String | Symbol, untyped]) -> nil - def to_s: -> String - def <<: (?untyped?) -> untyped - end - end - end - end -end diff --git a/sig/mindee/parsing/common/extras/rag_extra.rbs b/sig/mindee/parsing/common/extras/rag_extra.rbs deleted file mode 100644 index 9ddf0eb11..000000000 --- a/sig/mindee/parsing/common/extras/rag_extra.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/parsing/common/extras/rag_extra.rb - -module Mindee - module Parsing - module Common - module Extras - class RAGExtra - def matching_document_id: -> String? - def initialize: (untyped) -> nil - def to_s: -> String - end - end - end - end -end \ No newline at end of file diff --git a/sig/mindee/parsing/common/inference.rbs b/sig/mindee/parsing/common/inference.rbs deleted file mode 100644 index a1a02e0cc..000000000 --- a/sig/mindee/parsing/common/inference.rbs +++ /dev/null @@ -1,26 +0,0 @@ -# lib/mindee/parsing/common/inference.rb -module Mindee - module Parsing - module Common - class Inference - def self.endpoint_name: () -> String? - def self.endpoint_version: () -> String? - def self.has_async: () -> bool - def self.has_sync: () -> bool - - attr_reader endpoint_name: String - attr_reader endpoint_version: String - attr_reader extras: Extras::Extras - attr_reader has_async: bool - attr_reader has_sync: bool - attr_reader is_rotation_applied: bool - attr_reader pages: Array[Page] - attr_reader prediction: Prediction - attr_reader product: Product - - def initialize: (Hash[String | Symbol, untyped]) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/parsing/common/job.rbs b/sig/mindee/parsing/common/job.rbs deleted file mode 100644 index 2e89dc643..000000000 --- a/sig/mindee/parsing/common/job.rbs +++ /dev/null @@ -1,16 +0,0 @@ -# lib/mindee/parsing/common/job.rb -module Mindee - module Parsing - module Common - class Job - def id: -> String - def issued_at: -> Time - def available_at: -> Time - def status: () -> (:waiting | :processing | :completed | :failed) - def millisecs_taken: -> Integer - def error: -> Hash[String | Symbol, untyped] - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/parsing/common/ocr/mvision_v1.rbs b/sig/mindee/parsing/common/ocr/mvision_v1.rbs deleted file mode 100644 index aeaf6b25f..000000000 --- a/sig/mindee/parsing/common/ocr/mvision_v1.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/parsing/common/ocr/mvision_v1.rb -module Mindee - module Parsing - module Common - module OCR - class MVisionV1 - def pages: -> [] - def initialize: (Hash[String | Symbol, untyped]) -> void - def to_s: -> String - def reconstruct_vertically: (Array[Geometry::Point], Integer, Float) -> OCRLine - end - end - end - end -end diff --git a/sig/mindee/parsing/common/ocr/ocr.rbs b/sig/mindee/parsing/common/ocr/ocr.rbs deleted file mode 100644 index e902ab574..000000000 --- a/sig/mindee/parsing/common/ocr/ocr.rbs +++ /dev/null @@ -1,41 +0,0 @@ -# lib/mindee/parsing/common/ocr/ocr.rb -module Mindee - module Parsing - module Common - module OCR - class OCRWord - attr_reader bounding_box: Geometry::Quadrilateral - attr_accessor confidence: Float - attr_reader polygon: Geometry::Polygon - attr_reader text: String - - def initialize: (Hash[String | Symbol, untyped]) -> void - def to_s: -> String - end - class OCRLine < Array[OCRWord] - def initialize: (?Array[untyped]?, ?Array[OCRWord]?) -> void - def sort_on_x: -> OCRLine - def to_s: -> String - end - class OCRPage - attr_reader all_words: Array[OCRWord] - attr_reader lines: Array[OCRLine] - - def initialize: (Hash[String | Symbol, untyped]) -> void - def all_lines: -> Array[OCRLine] - def to_s: -> String - def parse_one: (Array[OCRWord], OCRWord?, Array[Integer], Array[OCRLine]) -> Array[OCRLine]? - def to_lines: -> Array[OCRLine] - def words_on_same_line?: (OCRWord, OCRWord) -> bool - end - class OCR - attr_reader mvision_v1: MVisionV1 - - def initialize: (Hash[String | Symbol, untyped]) -> void - def to_s: -> String - def reconstruct_vertically: (Array[Geometry::Point], Integer, ?Float) -> OCRLine - end - end - end - end -end diff --git a/sig/mindee/parsing/common/orientation.rbs b/sig/mindee/parsing/common/orientation.rbs deleted file mode 100644 index 3e0438978..000000000 --- a/sig/mindee/parsing/common/orientation.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/parsing/common/orientation.rb -module Mindee - module Parsing - module Common - class Orientation - attr_reader page_id: Integer? - attr_reader value: Integer? - - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - end - end - end -end diff --git a/sig/mindee/parsing/common/page.rbs b/sig/mindee/parsing/common/page.rbs deleted file mode 100644 index e86768565..000000000 --- a/sig/mindee/parsing/common/page.rbs +++ /dev/null @@ -1,16 +0,0 @@ -# lib/mindee/parsing/common/page.rb -module Mindee - module Parsing - module Common - class Page - attr_reader extras: Extras::Extras - attr_reader orientation: Common::Orientation - attr_reader page_id: Integer - attr_reader prediction: Common::Prediction - - def initialize: (Hash[String | Symbol, untyped]) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/parsing/common/prediction.rbs b/sig/mindee/parsing/common/prediction.rbs deleted file mode 100644 index 20902f7c9..000000000 --- a/sig/mindee/parsing/common/prediction.rbs +++ /dev/null @@ -1,11 +0,0 @@ -# lib/mindee/parsing/common/prediction.rb -module Mindee - module Parsing - module Common - class Prediction - def to_s: -> String - def initialize: (untyped?, untyped?) -> void - end - end - end -end diff --git a/sig/mindee/parsing/common/product.rbs b/sig/mindee/parsing/common/product.rbs deleted file mode 100644 index e9b1c873e..000000000 --- a/sig/mindee/parsing/common/product.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/parsing/common/product.rb -module Mindee - module Parsing - module Common - class Product - attr_reader name: String - attr_reader type: String? - attr_reader version: String - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/parsing/common/workflow_response.rbs b/sig/mindee/parsing/common/workflow_response.rbs deleted file mode 100644 index 40fa84a42..000000000 --- a/sig/mindee/parsing/common/workflow_response.rbs +++ /dev/null @@ -1,17 +0,0 @@ -# lib/mindee/parsing/common/workflow_response.rb -module Mindee - module Parsing - module Common - class WorkflowResponse - @api_request: ApiRequest - @execution: Execution - @raw_http: String - - def execution: -> Execution - def api_request: -> ApiRequest - def raw_http: -> String - def initialize: (singleton(Parsing::Common::Inference), Hash[String | Symbol, untyped] | Net::HTTPResponse, String) -> void - end - end - end -end diff --git a/sig/mindee/parsing/standard/abstract_field.rbs b/sig/mindee/parsing/standard/abstract_field.rbs deleted file mode 100644 index a870301b4..000000000 --- a/sig/mindee/parsing/standard/abstract_field.rbs +++ /dev/null @@ -1,19 +0,0 @@ -# lib/mindee/parsing/standard/abstract_field.rb -module Mindee - module Parsing - module Standard - class AbstractField - def bounding_box: -> Geometry::Polygon? - def polygon: -> Geometry::Polygon? - def page_id: -> Integer? - def confidence: -> Float? - def confidence=: (Float?) -> Float? - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - def self.array_confidence: (Array[untyped]) -> Float - def self.array_sum: (Array[untyped]) -> Float - def self.float_to_string: (Float, ?Integer) -> String - end - end - end -end diff --git a/sig/mindee/parsing/standard/address_field.rbs b/sig/mindee/parsing/standard/address_field.rbs deleted file mode 100644 index aff39e679..000000000 --- a/sig/mindee/parsing/standard/address_field.rbs +++ /dev/null @@ -1,18 +0,0 @@ -# lib/mindee/parsing/standard/address_field.rb -module Mindee - module Parsing - module Standard - class AddressField < StringField - def street_number: -> String - def street_name: -> String - def po_box: -> String - def address_complement: -> String - def city: -> String - def postal_code: -> String - def state: -> String - def country: -> String - def initialize: (Hash[String | Symbol, untyped], ?Integer?, ?reconstructed: bool) -> void - end - end - end -end diff --git a/sig/mindee/parsing/standard/amount_field.rbs b/sig/mindee/parsing/standard/amount_field.rbs deleted file mode 100644 index e3ceaff5e..000000000 --- a/sig/mindee/parsing/standard/amount_field.rbs +++ /dev/null @@ -1,14 +0,0 @@ -# lib/mindee/parsing/standard/amount_field.rb -module Mindee - module Parsing - module Standard - class AmountField < BaseField - attr_reader value: Float? - - - def initialize: (Hash[String | Symbol, untyped], Integer?, ?reconstructed: bool) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/parsing/standard/base_field.rbs b/sig/mindee/parsing/standard/base_field.rbs deleted file mode 100644 index 3db3db896..000000000 --- a/sig/mindee/parsing/standard/base_field.rbs +++ /dev/null @@ -1,12 +0,0 @@ -# lib/mindee/parsing/standard/base_field.rb -module Mindee - module Parsing - module Standard - class BaseField < Parsing::Standard::AbstractField - def initialize: (Hash[String | Symbol, untyped], Integer?, ?reconstructed: bool) -> void - def value: -> (String | Float | Integer | bool) - def reconstructed: -> bool - end - end - end -end diff --git a/sig/mindee/parsing/standard/boolean_field.rbs b/sig/mindee/parsing/standard/boolean_field.rbs deleted file mode 100644 index 05f165438..000000000 --- a/sig/mindee/parsing/standard/boolean_field.rbs +++ /dev/null @@ -1,12 +0,0 @@ -# lib/mindee/parsing/standard/boolean_field.rb -module Mindee - module Parsing - module Standard - class BooleanField < BaseField - def value: -> bool? - def initialize: (Hash[String | Symbol, untyped], ?Integer?, ?reconstructed: false) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/parsing/standard/classification_field.rbs b/sig/mindee/parsing/standard/classification_field.rbs deleted file mode 100644 index 81cfd5363..000000000 --- a/sig/mindee/parsing/standard/classification_field.rbs +++ /dev/null @@ -1,10 +0,0 @@ -# lib/mindee/parsing/standard/classification_field.rb -module Mindee - module Parsing - module Standard - class ClassificationField < BaseField - def value: -> String - end - end - end -end diff --git a/sig/mindee/parsing/standard/company_registration_field.rbs b/sig/mindee/parsing/standard/company_registration_field.rbs deleted file mode 100644 index 58b38d9cf..000000000 --- a/sig/mindee/parsing/standard/company_registration_field.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/parsing/standard/company_registration_field.rb -module Mindee - module Parsing - module Standard - class CompanyRegistrationField < BaseField - attr_reader type: String - - def initialize: (Hash[String | Symbol, untyped], Integer?, ?reconstructed: false) -> void - def to_table_line: -> String - def to_s: -> String - def printable_values: -> Hash[String, untyped] - end - end - end -end diff --git a/sig/mindee/parsing/standard/date_field.rbs b/sig/mindee/parsing/standard/date_field.rbs deleted file mode 100644 index a10222acd..000000000 --- a/sig/mindee/parsing/standard/date_field.rbs +++ /dev/null @@ -1,14 +0,0 @@ -# lib/mindee/parsing/standard/date_field.rb -module Mindee - module Parsing - module Standard - class DateField < BaseField - def date_object: -> DateTime - def value: -> String? - def raw: -> String? - def is_computed: -> bool - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - end - end - end -end diff --git a/sig/mindee/parsing/standard/feature_field.rbs b/sig/mindee/parsing/standard/feature_field.rbs deleted file mode 100644 index 863439e16..000000000 --- a/sig/mindee/parsing/standard/feature_field.rbs +++ /dev/null @@ -1,10 +0,0 @@ -# lib/mindee/parsing/standard/feature_field.rb -module Mindee - module Parsing - module Standard - class FeatureField < BaseField - def format_for_display: (String | bool?, ?Integer?) -> String - end - end - end -end diff --git a/sig/mindee/parsing/standard/locale_field.rbs b/sig/mindee/parsing/standard/locale_field.rbs deleted file mode 100644 index 12d07782d..000000000 --- a/sig/mindee/parsing/standard/locale_field.rbs +++ /dev/null @@ -1,16 +0,0 @@ -# lib/mindee/parsing/standard/locale_field.rb -module Mindee - module Parsing - module Standard - class LocaleField - def confidence: -> Float? - def language: -> String? - def country: -> String? - def currency: -> String? - def value: -> String? - def initialize: (Hash[String | Symbol, untyped], ?Integer?) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/parsing/standard/payment_details_field.rbs b/sig/mindee/parsing/standard/payment_details_field.rbs deleted file mode 100644 index 5ef7739aa..000000000 --- a/sig/mindee/parsing/standard/payment_details_field.rbs +++ /dev/null @@ -1,16 +0,0 @@ -# lib/mindee/parsing/standard/payment_details_field.rb -module Mindee - module Parsing - module Standard - class PaymentDetailsField < BaseField - attr_reader account_number: String ? - attr_reader iban: String? - attr_reader routing_number: String? - attr_reader swift: String? - - def initialize: (Hash[String | Symbol, untyped], Integer?, ?reconstructed: bool) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/parsing/standard/position_field.rbs b/sig/mindee/parsing/standard/position_field.rbs deleted file mode 100644 index a2976c538..000000000 --- a/sig/mindee/parsing/standard/position_field.rbs +++ /dev/null @@ -1,17 +0,0 @@ -# lib/mindee/parsing/standard/position_field.rb -module Mindee - module Parsing - module Standard - class PositionField - def polygon: -> Geometry::Polygon - def value: -> Geometry::Polygon - def quadrangle: -> Geometry::Quadrilateral - def rectangle: -> Geometry::Quadrilateral - def bounding_box: -> Geometry::Quadrilateral - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - def to_quadrilateral: (Hash[String | Symbol, Array[untyped]], String) -> Geometry::Quadrilateral? - end - end - end -end diff --git a/sig/mindee/parsing/standard/string_field.rbs b/sig/mindee/parsing/standard/string_field.rbs deleted file mode 100644 index b569e7d1f..000000000 --- a/sig/mindee/parsing/standard/string_field.rbs +++ /dev/null @@ -1,12 +0,0 @@ -# lib/mindee/parsing/standard/string_field.rb -module Mindee - module Parsing - module Standard - class StringField < BaseField - def value: -> String - def raw_value: -> String - def initialize: (Hash[String | Symbol, untyped], ?Integer?, ?reconstructed: bool) -> void - end - end - end -end diff --git a/sig/mindee/parsing/standard/tax_field.rbs b/sig/mindee/parsing/standard/tax_field.rbs deleted file mode 100644 index 4f8faf2d2..000000000 --- a/sig/mindee/parsing/standard/tax_field.rbs +++ /dev/null @@ -1,24 +0,0 @@ -# lib/mindee/parsing/standard/tax_field.rb -module Mindee - module Parsing - module Standard - class TaxField < BaseField - attr_reader base: Float - attr_reader code: String - attr_reader rate: Float - attr_reader value: Float? - - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def print_float: (Float) -> String - def to_s: -> String - def printable_values: -> Hash[untyped, String] - def to_table_line: -> String - end - class Taxes < Array[TaxField] - def initialize: (Array[untyped], Integer?) -> void - def line_separator: (String) -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/parsing/universal/universal_list_field.rbs b/sig/mindee/parsing/universal/universal_list_field.rbs deleted file mode 100644 index 4bccf4149..000000000 --- a/sig/mindee/parsing/universal/universal_list_field.rbs +++ /dev/null @@ -1,16 +0,0 @@ -# lib/mindee/parsing/universal/universal_list_field.rb -module Mindee - module Parsing - module Universal - class UniversalListField - attr_reader page_id: Integer - attr_reader values: Array[UniversalObjectField | Standard::StringField] - - def initialize: (Array[Hash[String | Symbol, untyped]], ?Integer?) -> void - def contents_list: -> Array[String] - def contents_string: (?String) -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/parsing/universal/universal_object_field.rbs b/sig/mindee/parsing/universal/universal_object_field.rbs deleted file mode 100644 index 54f641d41..000000000 --- a/sig/mindee/parsing/universal/universal_object_field.rbs +++ /dev/null @@ -1,29 +0,0 @@ -# lib/mindee/parsing/universal/universal_object_field.rb -module Mindee - module Parsing - module Universal - class UniversalObjectField - attr_reader all_values: Hash[String | Symbol, String | Standard::PositionField?] - attr_reader confidence: Float - attr_reader page_id: Integer - attr_reader raw_value: String - - def initialize: (Hash[String | Symbol, untyped], ?Integer?) -> void - def str_level: (?Integer) -> String - def method_missing: (Symbol, *untyped, untyped) - -> (String - | Integer - | Float - | bool - | Standard::PositionField - | Hash[String | Symbol, untyped] - ?) - def respond_to_missing?: (Symbol, ?bool) -> bool - def to_s: -> String - def handle_position_field: (String | Symbol, Hash[String | Symbol, untyped] | Integer | String | Float | bool?, Integer?) -> void - def handle_default_field: (String | Symbol, Hash[String | Symbol, untyped] | Integer | String | Float | bool?) -> void - end - def self.universal_object?: (Hash[String | Symbol, untyped]) -> bool - end - end -end diff --git a/sig/mindee/parsing/v2/common_response.rbs b/sig/mindee/parsing/v2/common_response.rbs deleted file mode 100644 index 8c94189a8..000000000 --- a/sig/mindee/parsing/v2/common_response.rbs +++ /dev/null @@ -1,11 +0,0 @@ -# lib/mindee/parsing/v2/common_response.rb -module Mindee - module Parsing - module V2 - class CommonResponse - attr_reader raw_http: Hash[String | Symbol, untyped] - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/parsing/v2/error_item.rbs b/sig/mindee/parsing/v2/error_item.rbs deleted file mode 100644 index 04b4e6756..000000000 --- a/sig/mindee/parsing/v2/error_item.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/parsing/v2/error_item.rb -module Mindee - module Parsing - module V2 - class ErrorItem - attr_reader pointer: String - attr_reader detail: String|nil - - def initialize: (Hash[String|Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/parsing/v2/inference.rbs b/sig/mindee/parsing/v2/inference.rbs deleted file mode 100644 index b6584c95a..000000000 --- a/sig/mindee/parsing/v2/inference.rbs +++ /dev/null @@ -1,18 +0,0 @@ -# lib/mindee/parsing/v2/inference.rb -module Mindee - module Parsing - module V2 - class Inference < Mindee::V2::Parsing::BaseInference - attr_reader self.params_type: singleton(Input::InferenceParameters) - attr_reader self.response_type: singleton(InferenceResponse) - attr_reader self.slug: String - - attr_reader active_options: InferenceActiveOptions - attr_reader result: InferenceResult - - def initialize: (Hash[String | Symbol, untyped]) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/parsing/v2/inference_response.rbs b/sig/mindee/parsing/v2/inference_response.rbs deleted file mode 100644 index 051387484..000000000 --- a/sig/mindee/parsing/v2/inference_response.rbs +++ /dev/null @@ -1,21 +0,0 @@ -# lib/mindee/parsing/v2/inference_response.rb -module Mindee - module Parsing - module V2 - class InferenceResponse < Mindee::V2::Parsing::BaseResponse[Mindee::Parsing::V2::Inference] - - self.@slug: String - self.@_params_type: singleton(Input::BaseParameters) - - attr_reader inference: Mindee::Parsing::V2::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - - def _params_type: -> singleton(Input::InferenceParameters) - - def to_s: -> String - def self._params_type: () -> singleton(Input::InferenceParameters) - def self.slug: () -> String - end - end - end -end diff --git a/sig/mindee/parsing/v2/inference_result.rbs b/sig/mindee/parsing/v2/inference_result.rbs deleted file mode 100644 index a83427809..000000000 --- a/sig/mindee/parsing/v2/inference_result.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/parsing/v2/inference_result.rb -module Mindee - module Parsing - module V2 - class InferenceResult - attr_reader fields: Field::InferenceFields - attr_reader raw_text: RawText? - attr_reader rag: RAGMetadata? - - def initialize: (Hash[String | Symbol, untyped]) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/pdf/extracted_pdf.rbs b/sig/mindee/pdf/extracted_pdf.rbs index d2f2427aa..937bd3d60 100644 --- a/sig/mindee/pdf/extracted_pdf.rbs +++ b/sig/mindee/pdf/extracted_pdf.rbs @@ -1,15 +1,17 @@ # lib/mindee/pdf/extracted_pdf.rb module Mindee module PDF - module PDFExtractor - class ExtractedPDF - attr_reader pdf_bytes: StringIO - attr_reader filename: String - def initialize: (StringIO, String) -> void - def page_count: -> Integer - def write_to_file: (String, ?override: bool) -> Integer - def as_input_source: -> Input::Source::BytesInputSource - end + class ExtractedPDF + attr_reader pdf_bytes: StringIO + attr_reader filename: String + + def initialize: (StringIO | File, String) -> void + + def page_count: -> Integer + + def write_to_file: (String, ?override: bool) -> void + + def as_input_source: -> Input::Source::BytesInputSource end end end diff --git a/sig/mindee/pdf/pdf_extractor.rbs b/sig/mindee/pdf/pdf_extractor.rbs index 38a5a1fb4..5007823ae 100644 --- a/sig/mindee/pdf/pdf_extractor.rbs +++ b/sig/mindee/pdf/pdf_extractor.rbs @@ -1,17 +1,19 @@ # lib/mindee/pdf/pdf_extractor.rb module Mindee module PDF - module PDFExtractor - class PDFExtractor - attr_reader filename: String - attr_reader source_pdf: StringIO + class PDFExtractor + attr_reader filename: String + attr_reader source_pdf: StringIO - def initialize: (Input::Source::LocalInputSource) -> void - def page_count: -> Integer - def cut_pages: (Array[Integer]) -> StringIO - def extract_sub_documents: (Array[Array[Integer]]) -> Array[ExtractedPDF] - def extract_invoices: (Array[Product::InvoiceSplitter::InvoiceSplitterV1InvoicePageGroup] | Array [Array[Integer]], ?strict: bool) -> Array[ExtractedPDF] - end + def initialize: (Input::Source::LocalInputSource) -> void + + def page_count: -> Integer + + def cut_pages: (Array[Integer]) -> StringIO + + def extract_sub_documents: (Array[Array[Integer]]) -> Array[ExtractedPDF] + + def extract_invoices: (Array[V1::Product::InvoiceSplitter::InvoiceSplitterV1InvoicePageGroup] | Array[Array[Integer]], ?strict: bool) -> Array[ExtractedPDF] end end end diff --git a/sig/mindee/pdf/pdf_tools.rbs b/sig/mindee/pdf/pdf_tools.rbs index dc8ae8e9d..a456ff4c4 100644 --- a/sig/mindee/pdf/pdf_tools.rbs +++ b/sig/mindee/pdf/pdf_tools.rbs @@ -8,6 +8,8 @@ module Mindee Height: Integer | Float Width: Integer | Float + def self.pdf_header?: (StringIO | File) -> bool + def to_io_stream: (?Hash[Symbol, untyped]) -> StringIO def intents_as_pdfa1: () -> void def delinearize!: () -> void diff --git a/sig/mindee/product/bill_of_lading/bill_of_lading_v1.rbs b/sig/mindee/product/bill_of_lading/bill_of_lading_v1.rbs deleted file mode 100644 index bc9546b5c..000000000 --- a/sig/mindee/product/bill_of_lading/bill_of_lading_v1.rbs +++ /dev/null @@ -1,11 +0,0 @@ -# lib/mindee/product/bill_of_lading/bill_of_lading_v1.rb - -module Mindee - module Product - module BillOfLading - class BillOfLadingV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_carrier.rbs b/sig/mindee/product/bill_of_lading/bill_of_lading_v1_carrier.rbs deleted file mode 100644 index b51db8bbe..000000000 --- a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_carrier.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module BillOfLading - class BillOfLadingV1Carrier < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def name: -> String - def professional_number: -> String - def scac: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_item.rbs b/sig/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_item.rbs deleted file mode 100644 index 024021651..000000000 --- a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_item.rbs +++ /dev/null @@ -1,19 +0,0 @@ -module Mindee - module Product - module BillOfLading - class BillOfLadingV1CarrierItem < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def description: -> String - def gross_weight: -> Float - def measurement: -> Float - def measurement_unit: -> String - def quantity: -> Float - def weight_unit: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_items.rbs b/sig/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_items.rbs deleted file mode 100644 index 550f23601..000000000 --- a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_carrier_items.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Product - module BillOfLading - class BillOfLadingV1CarrierItems < Array[BillOfLadingV1CarrierItem] - def initialize: (Array[untyped], Integer?) -> void - def self.line_items_separator: (String) -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_consignee.rbs b/sig/mindee/product/bill_of_lading/bill_of_lading_v1_consignee.rbs deleted file mode 100644 index 5640ae6ac..000000000 --- a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_consignee.rbs +++ /dev/null @@ -1,15 +0,0 @@ -module Mindee - module Product - module BillOfLading - class BillOfLadingV1Consignee < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address: -> String - def email: -> String - def name: -> String - def phone: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_document.rbs b/sig/mindee/product/bill_of_lading/bill_of_lading_v1_document.rbs deleted file mode 100644 index 9b459c7c2..000000000 --- a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_document.rbs +++ /dev/null @@ -1,25 +0,0 @@ -# lib/mindee/product/bill_of_lading/bill_of_lading_v1_document.rb - -module Mindee - module Product - module BillOfLading - class BillOfLadingV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def bill_of_lading_number: -> (Parsing::Standard::StringField) - def carrier: -> (Product::BillOfLading::BillOfLadingV1Carrier) - def carrier_items: -> (Product::BillOfLading::BillOfLadingV1CarrierItems) - def consignee: -> (Product::BillOfLading::BillOfLadingV1Consignee) - def date_of_issue: -> (Parsing::Standard::DateField) - def departure_date: -> (Parsing::Standard::DateField) - def notify_party: -> (Product::BillOfLading::BillOfLadingV1NotifyParty) - def place_of_delivery: -> (Parsing::Standard::StringField) - def port_of_discharge: -> (Parsing::Standard::StringField) - def port_of_loading: -> (Parsing::Standard::StringField) - def shipper: -> (Product::BillOfLading::BillOfLadingV1Shipper) - def carrier_items_separator: (String) -> String - def carrier_items_to_s: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_notify_party.rbs b/sig/mindee/product/bill_of_lading/bill_of_lading_v1_notify_party.rbs deleted file mode 100644 index f0fb65f0c..000000000 --- a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_notify_party.rbs +++ /dev/null @@ -1,15 +0,0 @@ -module Mindee - module Product - module BillOfLading - class BillOfLadingV1NotifyParty < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address: -> String - def email: -> String - def name: -> String - def phone: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_page.rbs b/sig/mindee/product/bill_of_lading/bill_of_lading_v1_page.rbs deleted file mode 100644 index 45964c572..000000000 --- a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_page.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/product/bill_of_lading/bill_of_lading_v1_page.rb - -module Mindee - module Product - module BillOfLading - class BillOfLadingV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class BillOfLadingV1PagePrediction < BillOfLadingV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_shipper.rbs b/sig/mindee/product/bill_of_lading/bill_of_lading_v1_shipper.rbs deleted file mode 100644 index 67af0cc3d..000000000 --- a/sig/mindee/product/bill_of_lading/bill_of_lading_v1_shipper.rbs +++ /dev/null @@ -1,15 +0,0 @@ -module Mindee - module Product - module BillOfLading - class BillOfLadingV1Shipper < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address: -> String - def email: -> String - def name: -> String - def phone: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/business_card/business_card_v1.rbs b/sig/mindee/product/business_card/business_card_v1.rbs deleted file mode 100644 index f6eb9c1b3..000000000 --- a/sig/mindee/product/business_card/business_card_v1.rbs +++ /dev/null @@ -1,11 +0,0 @@ -# lib/mindee/product/business_card/business_card_v1.rb - -module Mindee - module Product - module BusinessCard - class BusinessCardV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/product/business_card/business_card_v1_document.rbs b/sig/mindee/product/business_card/business_card_v1_document.rbs deleted file mode 100644 index 14286df57..000000000 --- a/sig/mindee/product/business_card/business_card_v1_document.rbs +++ /dev/null @@ -1,23 +0,0 @@ -# lib/mindee/product/business_card/business_card_v1_document.rb - -module Mindee - module Product - module BusinessCard - class BusinessCardV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address: -> (Parsing::Standard::StringField) - def company: -> (Parsing::Standard::StringField) - def email: -> (Parsing::Standard::StringField) - def fax_number: -> (Parsing::Standard::StringField) - def firstname: -> (Parsing::Standard::StringField) - def job_title: -> (Parsing::Standard::StringField) - def lastname: -> (Parsing::Standard::StringField) - def mobile_number: -> (Parsing::Standard::StringField) - def phone_number: -> (Parsing::Standard::StringField) - def social_media: -> (Array[Parsing::Standard::StringField]) - def website: -> (Parsing::Standard::StringField) - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/business_card/business_card_v1_page.rbs b/sig/mindee/product/business_card/business_card_v1_page.rbs deleted file mode 100644 index bc636440a..000000000 --- a/sig/mindee/product/business_card/business_card_v1_page.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/product/business_card/business_card_v1_page.rb - -module Mindee - module Product - module BusinessCard - class BusinessCardV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class BusinessCardV1PagePrediction < BusinessCardV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/delivery_note/delivery_note_v1.rbs b/sig/mindee/product/delivery_note/delivery_note_v1.rbs deleted file mode 100644 index 4eccee964..000000000 --- a/sig/mindee/product/delivery_note/delivery_note_v1.rbs +++ /dev/null @@ -1,11 +0,0 @@ -# lib/mindee/product/delivery_note/delivery_note_v1.rb - -module Mindee - module Product - module DeliveryNote - class DeliveryNoteV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/product/delivery_note/delivery_note_v1_document.rbs b/sig/mindee/product/delivery_note/delivery_note_v1_document.rbs deleted file mode 100644 index eb2059cea..000000000 --- a/sig/mindee/product/delivery_note/delivery_note_v1_document.rbs +++ /dev/null @@ -1,19 +0,0 @@ -# lib/mindee/product/delivery_note/delivery_note_v1_document.rb - -module Mindee - module Product - module DeliveryNote - class DeliveryNoteV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def customer_address: -> (Parsing::Standard::StringField) - def customer_name: -> (Parsing::Standard::StringField) - def delivery_date: -> (Parsing::Standard::DateField) - def delivery_number: -> (Parsing::Standard::StringField) - def supplier_address: -> (Parsing::Standard::StringField) - def supplier_name: -> (Parsing::Standard::StringField) - def total_amount: -> (Parsing::Standard::AmountField) - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/delivery_note/delivery_note_v1_page.rbs b/sig/mindee/product/delivery_note/delivery_note_v1_page.rbs deleted file mode 100644 index 24792b5bc..000000000 --- a/sig/mindee/product/delivery_note/delivery_note_v1_page.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/product/delivery_note/delivery_note_v1_page.rb - -module Mindee - module Product - module DeliveryNote - class DeliveryNoteV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class DeliveryNoteV1PagePrediction < DeliveryNoteV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/driver_license/driver_license_v1.rbs b/sig/mindee/product/driver_license/driver_license_v1.rbs deleted file mode 100644 index 70cf6686f..000000000 --- a/sig/mindee/product/driver_license/driver_license_v1.rbs +++ /dev/null @@ -1,11 +0,0 @@ -# lib/mindee/product/driver_license/driver_license_v1.rb - -module Mindee - module Product - module DriverLicense - class DriverLicenseV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/product/driver_license/driver_license_v1_document.rbs b/sig/mindee/product/driver_license/driver_license_v1_document.rbs deleted file mode 100644 index 9946d67fc..000000000 --- a/sig/mindee/product/driver_license/driver_license_v1_document.rbs +++ /dev/null @@ -1,25 +0,0 @@ -# lib/mindee/product/driver_license/driver_license_v1_document.rb - -module Mindee - module Product - module DriverLicense - class DriverLicenseV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def category: -> (Parsing::Standard::StringField) - def country_code: -> (Parsing::Standard::StringField) - def date_of_birth: -> (Parsing::Standard::DateField) - def dd_number: -> (Parsing::Standard::StringField) - def expiry_date: -> (Parsing::Standard::DateField) - def first_name: -> (Parsing::Standard::StringField) - def id: -> (Parsing::Standard::StringField) - def issued_date: -> (Parsing::Standard::DateField) - def issuing_authority: -> (Parsing::Standard::StringField) - def last_name: -> (Parsing::Standard::StringField) - def mrz: -> (Parsing::Standard::StringField) - def place_of_birth: -> (Parsing::Standard::StringField) - def state: -> (Parsing::Standard::StringField) - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/driver_license/driver_license_v1_page.rbs b/sig/mindee/product/driver_license/driver_license_v1_page.rbs deleted file mode 100644 index d59fc2de7..000000000 --- a/sig/mindee/product/driver_license/driver_license_v1_page.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/product/driver_license/driver_license_v1_page.rb - -module Mindee - module Product - module DriverLicense - class DriverLicenseV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class DriverLicenseV1PagePrediction < DriverLicenseV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/financial_document/financial_document_v1_line_item.rbs b/sig/mindee/product/financial_document/financial_document_v1_line_item.rbs deleted file mode 100644 index 21994be4d..000000000 --- a/sig/mindee/product/financial_document/financial_document_v1_line_item.rbs +++ /dev/null @@ -1,21 +0,0 @@ -module Mindee - module Product - module FinancialDocument - class FinancialDocumentV1LineItem < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def description: -> String - def product_code: -> String - def quantity: -> Float - def tax_amount: -> Float - def tax_rate: -> Float - def total_amount: -> Float - def unit_measure: -> String - def unit_price: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/fr/bank_account_details/bank_account_details_v2_bban.rbs b/sig/mindee/product/fr/bank_account_details/bank_account_details_v2_bban.rbs deleted file mode 100644 index c6db964df..000000000 --- a/sig/mindee/product/fr/bank_account_details/bank_account_details_v2_bban.rbs +++ /dev/null @@ -1,17 +0,0 @@ -module Mindee - module Product - module FR - module BankAccountDetails - class BankAccountDetailsV2Bban < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def bban_bank_code: -> String - def bban_branch_code: -> String - def bban_key: -> String - def bban_number: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/carte_grise/carte_grise_v1.rbs b/sig/mindee/product/fr/carte_grise/carte_grise_v1.rbs deleted file mode 100644 index eb2373bae..000000000 --- a/sig/mindee/product/fr/carte_grise/carte_grise_v1.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/product/../carte_grise/carte_grise_v1.rb - -module Mindee - module Product - module FR - module CarteGrise - class CarteGriseV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end - end -end diff --git a/sig/mindee/product/fr/carte_grise/carte_grise_v1_document.rbs b/sig/mindee/product/fr/carte_grise/carte_grise_v1_document.rbs deleted file mode 100644 index 752493dc0..000000000 --- a/sig/mindee/product/fr/carte_grise/carte_grise_v1_document.rbs +++ /dev/null @@ -1,55 +0,0 @@ -# lib/mindee/product/../carte_grise/carte_grise_v1_document.rb - -module Mindee - module Product - module FR - module CarteGrise - class CarteGriseV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def a: -> (Parsing::Standard::StringField) - def b: -> (Parsing::Standard::DateField) - def c1: -> (Parsing::Standard::StringField) - def c3: -> (Parsing::Standard::StringField) - def c41: -> (Parsing::Standard::StringField) - def c4a: -> (Parsing::Standard::StringField) - def d1: -> (Parsing::Standard::StringField) - def d3: -> (Parsing::Standard::StringField) - def e: -> (Parsing::Standard::StringField) - def f1: -> (Parsing::Standard::StringField) - def f2: -> (Parsing::Standard::StringField) - def f3: -> (Parsing::Standard::StringField) - def formula_number: -> (Parsing::Standard::StringField) - def g: -> (Parsing::Standard::StringField) - def g1: -> (Parsing::Standard::StringField) - def i: -> (Parsing::Standard::DateField) - def j: -> (Parsing::Standard::StringField) - def j1: -> (Parsing::Standard::StringField) - def j2: -> (Parsing::Standard::StringField) - def j3: -> (Parsing::Standard::StringField) - def mrz1: -> (Parsing::Standard::StringField) - def mrz2: -> (Parsing::Standard::StringField) - def owner_first_name: -> (Parsing::Standard::StringField) - def owner_surname: -> (Parsing::Standard::StringField) - def p1: -> (Parsing::Standard::StringField) - def p2: -> (Parsing::Standard::StringField) - def p3: -> (Parsing::Standard::StringField) - def p6: -> (Parsing::Standard::StringField) - def q: -> (Parsing::Standard::StringField) - def s1: -> (Parsing::Standard::StringField) - def s2: -> (Parsing::Standard::StringField) - def u1: -> (Parsing::Standard::StringField) - def u2: -> (Parsing::Standard::StringField) - def v7: -> (Parsing::Standard::StringField) - def x1: -> (Parsing::Standard::StringField) - def y1: -> (Parsing::Standard::StringField) - def y2: -> (Parsing::Standard::StringField) - def y3: -> (Parsing::Standard::StringField) - def y4: -> (Parsing::Standard::StringField) - def y5: -> (Parsing::Standard::StringField) - def y6: -> (Parsing::Standard::StringField) - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/carte_grise/carte_grise_v1_page.rbs b/sig/mindee/product/fr/carte_grise/carte_grise_v1_page.rbs deleted file mode 100644 index a17e25eb3..000000000 --- a/sig/mindee/product/fr/carte_grise/carte_grise_v1_page.rbs +++ /dev/null @@ -1,17 +0,0 @@ -# lib/mindee/product/../carte_grise/carte_grise_v1_page.rb - -module Mindee - module Product - module FR - module CarteGrise - class CarteGriseV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class CarteGriseV1PagePrediction < CarteGriseV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1.rbs b/sig/mindee/product/fr/energy_bill/energy_bill_v1.rbs deleted file mode 100644 index 2e94fe391..000000000 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/product/../energy_bill/energy_bill_v1.rb - -module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end - end -end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_document.rbs b/sig/mindee/product/fr/energy_bill/energy_bill_v1_document.rbs deleted file mode 100644 index 809ed576e..000000000 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_document.rbs +++ /dev/null @@ -1,34 +0,0 @@ -# lib/mindee/product/../energy_bill/energy_bill_v1_document.rb - -module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def contract_id: -> (Parsing::Standard::StringField) - def delivery_point: -> (Parsing::Standard::StringField) - def due_date: -> (Parsing::Standard::DateField) - def energy_consumer: -> (Product::FR::EnergyBill::EnergyBillV1EnergyConsumer) - def energy_supplier: -> (Product::FR::EnergyBill::EnergyBillV1EnergySupplier) - def energy_usage: -> (Product::FR::EnergyBill::EnergyBillV1EnergyUsages) - def invoice_date: -> (Parsing::Standard::DateField) - def invoice_number: -> (Parsing::Standard::StringField) - def meter_details: -> (Product::FR::EnergyBill::EnergyBillV1MeterDetail) - def subscription: -> (Product::FR::EnergyBill::EnergyBillV1Subscriptions) - def taxes_and_contributions: -> (Product::FR::EnergyBill::EnergyBillV1TaxesAndContributions) - def total_amount: -> (Parsing::Standard::AmountField) - def total_before_taxes: -> (Parsing::Standard::AmountField) - def total_taxes: -> (Parsing::Standard::AmountField) - def subscription_separator: (String) -> String - def subscription_to_s: -> String - def energy_usage_separator: (String) -> String - def energy_usage_to_s: -> String - def taxes_and_contributions_separator: (String) -> String - def taxes_and_contributions_to_s: -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_consumer.rbs b/sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_consumer.rbs deleted file mode 100644 index deb4f8194..000000000 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_consumer.rbs +++ /dev/null @@ -1,15 +0,0 @@ -module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1EnergyConsumer < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address: -> String - def name: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_supplier.rbs b/sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_supplier.rbs deleted file mode 100644 index 403898436..000000000 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_supplier.rbs +++ /dev/null @@ -1,15 +0,0 @@ -module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1EnergySupplier < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address: -> String - def name: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_meter_detail.rbs b/sig/mindee/product/fr/energy_bill/energy_bill_v1_meter_detail.rbs deleted file mode 100644 index 7183023c4..000000000 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_meter_detail.rbs +++ /dev/null @@ -1,16 +0,0 @@ -module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1MeterDetail < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def meter_number: -> String - def meter_type: -> String - def unit: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_page.rbs b/sig/mindee/product/fr/energy_bill/energy_bill_v1_page.rbs deleted file mode 100644 index 6b395bacd..000000000 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_page.rbs +++ /dev/null @@ -1,17 +0,0 @@ -# lib/mindee/product/../energy_bill/energy_bill_v1_page.rb - -module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class EnergyBillV1PagePrediction < EnergyBillV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_subscription.rbs b/sig/mindee/product/fr/energy_bill/energy_bill_v1_subscription.rbs deleted file mode 100644 index cd9ac17aa..000000000 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_subscription.rbs +++ /dev/null @@ -1,21 +0,0 @@ -module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1Subscription < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def description: -> String - def end_date: -> String - def start_date: -> String - def tax_rate: -> Float - def total: -> Float - def unit_price: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contribution.rbs b/sig/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contribution.rbs deleted file mode 100644 index 3c6ec333f..000000000 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contribution.rbs +++ /dev/null @@ -1,21 +0,0 @@ -module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1TaxesAndContribution < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def description: -> String - def end_date: -> String - def start_date: -> String - def tax_rate: -> Float - def total: -> Float - def unit_price: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contributions.rbs b/sig/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contributions.rbs deleted file mode 100644 index 6a9066fc5..000000000 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_taxes_and_contributions.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1TaxesAndContributions < Array[EnergyBillV1TaxesAndContribution] - def initialize: (Array[untyped], Integer?) -> void - def self.line_items_separator: (String) -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/health_card/health_card_v1.rbs b/sig/mindee/product/fr/health_card/health_card_v1.rbs deleted file mode 100644 index 497e22fb1..000000000 --- a/sig/mindee/product/fr/health_card/health_card_v1.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/product/../health_card/health_card_v1.rb - -module Mindee - module Product - module FR - module HealthCard - class HealthCardV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end - end -end diff --git a/sig/mindee/product/fr/health_card/health_card_v1_document.rbs b/sig/mindee/product/fr/health_card/health_card_v1_document.rbs deleted file mode 100644 index 50a8ea5f6..000000000 --- a/sig/mindee/product/fr/health_card/health_card_v1_document.rbs +++ /dev/null @@ -1,18 +0,0 @@ -# lib/mindee/product/../health_card/health_card_v1_document.rb - -module Mindee - module Product - module FR - module HealthCard - class HealthCardV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def given_names: -> (Array[Parsing::Standard::StringField]) - def issuance_date: -> (Parsing::Standard::DateField) - def social_security: -> (Parsing::Standard::StringField) - def surname: -> (Parsing::Standard::StringField) - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/health_card/health_card_v1_page.rbs b/sig/mindee/product/fr/health_card/health_card_v1_page.rbs deleted file mode 100644 index 6b8858de7..000000000 --- a/sig/mindee/product/fr/health_card/health_card_v1_page.rbs +++ /dev/null @@ -1,17 +0,0 @@ -# lib/mindee/product/../health_card/health_card_v1_page.rb - -module Mindee - module Product - module FR - module HealthCard - class HealthCardV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class HealthCardV1PagePrediction < HealthCardV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/id_card/id_card_v1.rbs b/sig/mindee/product/fr/id_card/id_card_v1.rbs deleted file mode 100644 index 42b46b187..000000000 --- a/sig/mindee/product/fr/id_card/id_card_v1.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/product/../id_card/id_card_v1.rb - -module Mindee - module Product - module FR - module IdCard - class IdCardV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3.rbs b/sig/mindee/product/fr/payslip/payslip_v3.rbs deleted file mode 100644 index ab2dbac6e..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/product/../payslip/payslip_v3.rb - -module Mindee - module Product - module FR - module Payslip - class PayslipV3 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_bank_account_detail.rbs b/sig/mindee/product/fr/payslip/payslip_v3_bank_account_detail.rbs deleted file mode 100644 index a5a161ca6..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3_bank_account_detail.rbs +++ /dev/null @@ -1,16 +0,0 @@ -module Mindee - module Product - module FR - module Payslip - class PayslipV3BankAccountDetail < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def bank_name: -> String - def iban: -> String - def swift: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_document.rbs b/sig/mindee/product/fr/payslip/payslip_v3_document.rbs deleted file mode 100644 index deab66dfa..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3_document.rbs +++ /dev/null @@ -1,26 +0,0 @@ -# lib/mindee/product/../payslip/payslip_v3_document.rb - -module Mindee - module Product - module FR - module Payslip - class PayslipV3Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def bank_account_details: -> (Product::FR::Payslip::PayslipV3BankAccountDetail) - def employee: -> (Product::FR::Payslip::PayslipV3Employee) - def employer: -> (Product::FR::Payslip::PayslipV3Employer) - def employment: -> (Product::FR::Payslip::PayslipV3Employment) - def paid_time_off: -> (Product::FR::Payslip::PayslipV3PaidTimeOffs) - def pay_detail: -> (Product::FR::Payslip::PayslipV3PayDetail) - def pay_period: -> (Product::FR::Payslip::PayslipV3PayPeriod) - def salary_details: -> (Product::FR::Payslip::PayslipV3SalaryDetails) - def salary_details_separator: (String) -> String - def salary_details_to_s: -> String - def paid_time_off_separator: (String) -> String - def paid_time_off_to_s: -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_employee.rbs b/sig/mindee/product/fr/payslip/payslip_v3_employee.rbs deleted file mode 100644 index 8935b9b86..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3_employee.rbs +++ /dev/null @@ -1,20 +0,0 @@ -module Mindee - module Product - module FR - module Payslip - class PayslipV3Employee < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address: -> String - def date_of_birth: -> String - def first_name: -> String - def last_name: -> String - def phone_number: -> String - def registration_number: -> String - def social_security_number: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_employer.rbs b/sig/mindee/product/fr/payslip/payslip_v3_employer.rbs deleted file mode 100644 index a05a20013..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3_employer.rbs +++ /dev/null @@ -1,20 +0,0 @@ -module Mindee - module Product - module FR - module Payslip - class PayslipV3Employer < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address: -> String - def company_id: -> String - def company_site: -> String - def naf_code: -> String - def name: -> String - def phone_number: -> String - def urssaf_number: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_employment.rbs b/sig/mindee/product/fr/payslip/payslip_v3_employment.rbs deleted file mode 100644 index 2856d1a85..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3_employment.rbs +++ /dev/null @@ -1,20 +0,0 @@ -module Mindee - module Product - module FR - module Payslip - class PayslipV3Employment < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def category: -> String - def coefficient: -> String - def collective_agreement: -> String - def job_title: -> String - def position_level: -> String - def seniority_date: -> String - def start_date: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_page.rbs b/sig/mindee/product/fr/payslip/payslip_v3_page.rbs deleted file mode 100644 index 771111d34..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3_page.rbs +++ /dev/null @@ -1,17 +0,0 @@ -# lib/mindee/product/../payslip/payslip_v3_page.rb - -module Mindee - module Product - module FR - module Payslip - class PayslipV3Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class PayslipV3PagePrediction < PayslipV3Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_paid_time_off.rbs b/sig/mindee/product/fr/payslip/payslip_v3_paid_time_off.rbs deleted file mode 100644 index 5ebb28a41..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3_paid_time_off.rbs +++ /dev/null @@ -1,20 +0,0 @@ -module Mindee - module Product - module FR - module Payslip - class PayslipV3PaidTimeOff < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def accrued: -> Float - def period: -> String - def pto_type: -> String - def remaining: -> Float - def used: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_pay_detail.rbs b/sig/mindee/product/fr/payslip/payslip_v3_pay_detail.rbs deleted file mode 100644 index da6b575c6..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3_pay_detail.rbs +++ /dev/null @@ -1,23 +0,0 @@ -module Mindee - module Product - module FR - module Payslip - class PayslipV3PayDetail < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def gross_salary: -> Float - def gross_salary_ytd: -> Float - def income_tax_rate: -> Float - def income_tax_withheld: -> Float - def net_paid: -> Float - def net_paid_before_tax: -> Float - def net_taxable: -> Float - def net_taxable_ytd: -> Float - def total_cost_employer: -> Float - def total_taxes_and_deductions: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_pay_period.rbs b/sig/mindee/product/fr/payslip/payslip_v3_pay_period.rbs deleted file mode 100644 index be74ceda7..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3_pay_period.rbs +++ /dev/null @@ -1,18 +0,0 @@ -module Mindee - module Product - module FR - module Payslip - class PayslipV3PayPeriod < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def end_date: -> String - def month: -> String - def payment_date: -> String - def start_date: -> String - def year: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_salary_detail.rbs b/sig/mindee/product/fr/payslip/payslip_v3_salary_detail.rbs deleted file mode 100644 index e560d1c20..000000000 --- a/sig/mindee/product/fr/payslip/payslip_v3_salary_detail.rbs +++ /dev/null @@ -1,20 +0,0 @@ -module Mindee - module Product - module FR - module Payslip - class PayslipV3SalaryDetail < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def amount: -> Float - def base: -> Float - def description: -> String - def number: -> Float - def rate: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/ind/indian_passport/indian_passport_v1.rbs b/sig/mindee/product/ind/indian_passport/indian_passport_v1.rbs deleted file mode 100644 index 09fa33b4f..000000000 --- a/sig/mindee/product/ind/indian_passport/indian_passport_v1.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/product/../indian_passport/indian_passport_v1.rb - -module Mindee - module Product - module IND - module IndianPassport - class IndianPassportV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end - end -end diff --git a/sig/mindee/product/ind/indian_passport/indian_passport_v1_document.rbs b/sig/mindee/product/ind/indian_passport/indian_passport_v1_document.rbs deleted file mode 100644 index dab7c5f73..000000000 --- a/sig/mindee/product/ind/indian_passport/indian_passport_v1_document.rbs +++ /dev/null @@ -1,37 +0,0 @@ -# lib/mindee/product/../indian_passport/indian_passport_v1_document.rb - -module Mindee - module Product - module IND - module IndianPassport - class IndianPassportV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address1: -> (Parsing::Standard::StringField) - def address2: -> (Parsing::Standard::StringField) - def address3: -> (Parsing::Standard::StringField) - def birth_date: -> (Parsing::Standard::DateField) - def birth_place: -> (Parsing::Standard::StringField) - def country: -> (Parsing::Standard::StringField) - def expiry_date: -> (Parsing::Standard::DateField) - def file_number: -> (Parsing::Standard::StringField) - def gender: -> (Parsing::Standard::ClassificationField) - def given_names: -> (Parsing::Standard::StringField) - def id_number: -> (Parsing::Standard::StringField) - def issuance_date: -> (Parsing::Standard::DateField) - def issuance_place: -> (Parsing::Standard::StringField) - def legal_guardian: -> (Parsing::Standard::StringField) - def mrz1: -> (Parsing::Standard::StringField) - def mrz2: -> (Parsing::Standard::StringField) - def name_of_mother: -> (Parsing::Standard::StringField) - def name_of_spouse: -> (Parsing::Standard::StringField) - def old_passport_date_of_issue: -> (Parsing::Standard::DateField) - def old_passport_number: -> (Parsing::Standard::StringField) - def old_passport_place_of_issue: -> (Parsing::Standard::StringField) - def page_number: -> (Parsing::Standard::ClassificationField) - def surname: -> (Parsing::Standard::StringField) - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/ind/indian_passport/indian_passport_v1_page.rbs b/sig/mindee/product/ind/indian_passport/indian_passport_v1_page.rbs deleted file mode 100644 index a5a04c18a..000000000 --- a/sig/mindee/product/ind/indian_passport/indian_passport_v1_page.rbs +++ /dev/null @@ -1,17 +0,0 @@ -# lib/mindee/product/../indian_passport/indian_passport_v1_page.rb - -module Mindee - module Product - module IND - module IndianPassport - class IndianPassportV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class IndianPassportV1PagePrediction < IndianPassportV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/invoice/invoice_v4_line_item.rbs b/sig/mindee/product/invoice/invoice_v4_line_item.rbs deleted file mode 100644 index b4217c6f1..000000000 --- a/sig/mindee/product/invoice/invoice_v4_line_item.rbs +++ /dev/null @@ -1,21 +0,0 @@ -module Mindee - module Product - module Invoice - class InvoiceV4LineItem < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def description: -> String - def product_code: -> String - def quantity: -> Float - def tax_amount: -> Float - def tax_rate: -> Float - def total_amount: -> Float - def unit_measure: -> String - def unit_price: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rbs b/sig/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rbs deleted file mode 100644 index 5782f3038..000000000 --- a/sig/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module InvoiceSplitter - class InvoiceSplitterV1InvoicePageGroup < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def page_indexes: -> Array[Integer] - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/multi_receipts_detector/multi_receipts_detector_v1.rbs b/sig/mindee/product/multi_receipts_detector/multi_receipts_detector_v1.rbs deleted file mode 100644 index 0a6979a95..000000000 --- a/sig/mindee/product/multi_receipts_detector/multi_receipts_detector_v1.rbs +++ /dev/null @@ -1,11 +0,0 @@ -# lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1.rb - -module Mindee - module Product - module MultiReceiptsDetector - class MultiReceiptsDetectorV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1.rbs deleted file mode 100644 index dd062e7ca..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1.rbs +++ /dev/null @@ -1,11 +0,0 @@ -# lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1.rb - -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_added_sugar.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_added_sugar.rbs deleted file mode 100644 index 5e68f62dc..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_added_sugar.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1AddedSugar < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_calorie.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_calorie.rbs deleted file mode 100644 index 5d7d0e157..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_calorie.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1Calorie < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_cholesterol.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_cholesterol.rbs deleted file mode 100644 index 64a333512..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_cholesterol.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1Cholesterol < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_dietary_fiber.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_dietary_fiber.rbs deleted file mode 100644 index 4c9d93cb3..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_dietary_fiber.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1DietaryFiber < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_document.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_document.rbs deleted file mode 100644 index 51cdef350..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_document.rbs +++ /dev/null @@ -1,28 +0,0 @@ -# lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_document.rb - -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def added_sugars: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1AddedSugar) - def calories: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1Calorie) - def cholesterol: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1Cholesterol) - def dietary_fiber: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1DietaryFiber) - def nutrients: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1Nutrients) - def protein: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1Protein) - def saturated_fat: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1SaturatedFat) - def serving_per_box: -> (Parsing::Standard::AmountField) - def serving_size: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1ServingSize) - def sodium: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1Sodium) - def total_carbohydrate: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1TotalCarbohydrate) - def total_fat: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1TotalFat) - def total_sugars: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1TotalSugar) - def trans_fat: -> (Product::NutritionFactsLabel::NutritionFactsLabelV1TransFat) - def nutrients_separator: (String) -> String - def nutrients_to_s: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrient.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrient.rbs deleted file mode 100644 index 4f25611a3..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrient.rbs +++ /dev/null @@ -1,18 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1Nutrient < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def name: -> String - def per_100g: -> Float - def per_serving: -> Float - def unit: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrients.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrients.rbs deleted file mode 100644 index 004d13725..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_nutrients.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1Nutrients < Array[NutritionFactsLabelV1Nutrient] - def initialize: (Array[untyped], Integer?) -> void - def self.line_items_separator: (String) -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_page.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_page.rbs deleted file mode 100644 index 55cb379c9..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_page.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_page.rb - -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class NutritionFactsLabelV1PagePrediction < NutritionFactsLabelV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_protein.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_protein.rbs deleted file mode 100644 index 8aa82f0e1..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_protein.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1Protein < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_saturated_fat.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_saturated_fat.rbs deleted file mode 100644 index 313412d7e..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_saturated_fat.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1SaturatedFat < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_serving_size.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_serving_size.rbs deleted file mode 100644 index 62b0671cb..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_serving_size.rbs +++ /dev/null @@ -1,13 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1ServingSize < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def amount: -> Float - def unit: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_sodium.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_sodium.rbs deleted file mode 100644 index 04114e225..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_sodium.rbs +++ /dev/null @@ -1,15 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1Sodium < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def unit: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_carbohydrate.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_carbohydrate.rbs deleted file mode 100644 index cfd0aa186..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_carbohydrate.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1TotalCarbohydrate < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_fat.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_fat.rbs deleted file mode 100644 index 9e80c01e4..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_fat.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1TotalFat < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_sugar.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_sugar.rbs deleted file mode 100644 index d259e2c16..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_total_sugar.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1TotalSugar < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_trans_fat.rbs b/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_trans_fat.rbs deleted file mode 100644 index 52084790b..000000000 --- a/sig/mindee/product/nutrition_facts_label/nutrition_facts_label_v1_trans_fat.rbs +++ /dev/null @@ -1,14 +0,0 @@ -module Mindee - module Product - module NutritionFactsLabel - class NutritionFactsLabelV1TransFat < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def daily_value: -> Float - def per_100g: -> Float - def per_serving: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/receipt/receipt_v5_line_item.rbs b/sig/mindee/product/receipt/receipt_v5_line_item.rbs deleted file mode 100644 index 35fdcd097..000000000 --- a/sig/mindee/product/receipt/receipt_v5_line_item.rbs +++ /dev/null @@ -1,17 +0,0 @@ -module Mindee - module Product - module Receipt - class ReceiptV5LineItem < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def description: -> String - def quantity: -> Float - def total_amount: -> Float - def unit_price: -> Float - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_certificate.rbs b/sig/mindee/product/resume/resume_v1_certificate.rbs deleted file mode 100644 index 4fb5c1b53..000000000 --- a/sig/mindee/product/resume/resume_v1_certificate.rbs +++ /dev/null @@ -1,17 +0,0 @@ -module Mindee - module Product - module Resume - class ResumeV1Certificate < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def grade: -> String - def name: -> String - def provider: -> String - def year: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_certificates.rbs b/sig/mindee/product/resume/resume_v1_certificates.rbs deleted file mode 100644 index ec424a0b2..000000000 --- a/sig/mindee/product/resume/resume_v1_certificates.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Product - module Resume - class ResumeV1Certificates < Array[ResumeV1Certificate] - def initialize: (Array[untyped], Integer?) -> void - def self.line_items_separator: (String) -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_document.rbs b/sig/mindee/product/resume/resume_v1_document.rbs deleted file mode 100644 index 4b0b83dd2..000000000 --- a/sig/mindee/product/resume/resume_v1_document.rbs +++ /dev/null @@ -1,39 +0,0 @@ -# lib/mindee/product/resume/resume_v1_document.rb - -module Mindee - module Product - module Resume - class ResumeV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address: -> (Parsing::Standard::StringField) - def certificates: -> (Product::Resume::ResumeV1Certificates) - def document_language: -> (Parsing::Standard::StringField) - def document_type: -> (Parsing::Standard::ClassificationField) - def education: -> (Product::Resume::ResumeV1Educations) - def email_address: -> (Parsing::Standard::StringField) - def given_names: -> (Array[Parsing::Standard::StringField]) - def hard_skills: -> (Array[Parsing::Standard::StringField]) - def job_applied: -> (Parsing::Standard::StringField) - def languages: -> (Product::Resume::ResumeV1Languages) - def nationality: -> (Parsing::Standard::StringField) - def phone_number: -> (Parsing::Standard::StringField) - def profession: -> (Parsing::Standard::StringField) - def professional_experiences: -> (Product::Resume::ResumeV1ProfessionalExperiences) - def social_networks_urls: -> (Product::Resume::ResumeV1SocialNetworksUrls) - def soft_skills: -> (Array[Parsing::Standard::StringField]) - def surnames: -> (Array[Parsing::Standard::StringField]) - def social_networks_urls_separator: (String) -> String - def social_networks_urls_to_s: -> String - def languages_separator: (String) -> String - def languages_to_s: -> String - def education_separator: (String) -> String - def education_to_s: -> String - def professional_experiences_separator: (String) -> String - def professional_experiences_to_s: -> String - def certificates_separator: (String) -> String - def certificates_to_s: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_education.rbs b/sig/mindee/product/resume/resume_v1_education.rbs deleted file mode 100644 index 8485ffaf8..000000000 --- a/sig/mindee/product/resume/resume_v1_education.rbs +++ /dev/null @@ -1,20 +0,0 @@ -module Mindee - module Product - module Resume - class ResumeV1Education < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def degree_domain: -> String - def degree_type: -> String - def end_month: -> String - def end_year: -> String - def school: -> String - def start_month: -> String - def start_year: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_educations.rbs b/sig/mindee/product/resume/resume_v1_educations.rbs deleted file mode 100644 index b488f3978..000000000 --- a/sig/mindee/product/resume/resume_v1_educations.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Product - module Resume - class ResumeV1Educations < Array[ResumeV1Education] - def initialize: (Array[untyped], Integer?) -> void - def self.line_items_separator: (String) -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_language.rbs b/sig/mindee/product/resume/resume_v1_language.rbs deleted file mode 100644 index 9b721f5b7..000000000 --- a/sig/mindee/product/resume/resume_v1_language.rbs +++ /dev/null @@ -1,15 +0,0 @@ -module Mindee - module Product - module Resume - class ResumeV1Language < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def language: -> String - def level: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_languages.rbs b/sig/mindee/product/resume/resume_v1_languages.rbs deleted file mode 100644 index ba4ad08f2..000000000 --- a/sig/mindee/product/resume/resume_v1_languages.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Product - module Resume - class ResumeV1Languages < Array[ResumeV1Language] - def initialize: (Array[untyped], Integer?) -> void - def self.line_items_separator: (String) -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_page.rbs b/sig/mindee/product/resume/resume_v1_page.rbs deleted file mode 100644 index b4a568376..000000000 --- a/sig/mindee/product/resume/resume_v1_page.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# lib/mindee/product/resume/resume_v1_page.rb - -module Mindee - module Product - module Resume - class ResumeV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class ResumeV1PagePrediction < ResumeV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_professional_experience.rbs b/sig/mindee/product/resume/resume_v1_professional_experience.rbs deleted file mode 100644 index 234096979..000000000 --- a/sig/mindee/product/resume/resume_v1_professional_experience.rbs +++ /dev/null @@ -1,22 +0,0 @@ -module Mindee - module Product - module Resume - class ResumeV1ProfessionalExperience < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def contract_type: -> String - def department: -> String - def description: -> String - def employer: -> String - def end_month: -> String - def end_year: -> String - def role: -> String - def start_month: -> String - def start_year: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_professional_experiences.rbs b/sig/mindee/product/resume/resume_v1_professional_experiences.rbs deleted file mode 100644 index 2cf552290..000000000 --- a/sig/mindee/product/resume/resume_v1_professional_experiences.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Product - module Resume - class ResumeV1ProfessionalExperiences < Array[ResumeV1ProfessionalExperience] - def initialize: (Array[untyped], Integer?) -> void - def self.line_items_separator: (String) -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_social_networks_url.rbs b/sig/mindee/product/resume/resume_v1_social_networks_url.rbs deleted file mode 100644 index db2204185..000000000 --- a/sig/mindee/product/resume/resume_v1_social_networks_url.rbs +++ /dev/null @@ -1,15 +0,0 @@ -module Mindee - module Product - module Resume - class ResumeV1SocialNetworksUrl < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def name: -> String - def url: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/resume/resume_v1_social_networks_urls.rbs b/sig/mindee/product/resume/resume_v1_social_networks_urls.rbs deleted file mode 100644 index 090e1994a..000000000 --- a/sig/mindee/product/resume/resume_v1_social_networks_urls.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Product - module Resume - class ResumeV1SocialNetworksUrls < Array[ResumeV1SocialNetworksUrl] - def initialize: (Array[untyped], Integer?) -> void - def self.line_items_separator: (String) -> String - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/universal/universal_page.rbs b/sig/mindee/product/universal/universal_page.rbs deleted file mode 100644 index b53ebe251..000000000 --- a/sig/mindee/product/universal/universal_page.rbs +++ /dev/null @@ -1,14 +0,0 @@ -# lib/mindee/product/universal/universal_page.rb -module Mindee - module Product - module Universal - class UniversalPage < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class UniversalPagePrediction < UniversalPrediction - def initialize: (Hash[String | Symbol, untyped], ?nil) -> void - def to_s: -> String - end - end - end -end diff --git a/sig/mindee/product/universal/universal_prediction.rbs b/sig/mindee/product/universal/universal_prediction.rbs deleted file mode 100644 index b3badf94f..000000000 --- a/sig/mindee/product/universal/universal_prediction.rbs +++ /dev/null @@ -1,19 +0,0 @@ -# lib/mindee/product/universal/universal_prediction.rb -module Mindee - module Product - module Universal - class UniversalPrediction < Parsing::Common::Prediction - def fields: -> Hash[String | Symbol, untyped] - def initialize: (untyped?) -> void - def to_s: -> String - def generate_field_string: (String, Parsing::Universal::UniversalListField, Regexp) -> String - def generate_list_field_string: (String, Hash[String | Symbol, untyped], Regexp) -> String - def generate_sub_value_string: (String, Parsing::Universal::UniversalListField, Regexp) -> String - def single_fields: -> Hash[String | Symbol, untyped] - def list_fields: -> Hash[String | Symbol, Parsing::Universal::UniversalListField] - def object_fields: -> Hash[String | Symbol, untyped] - def list_field_names: -> Array[untyped] - end - end - end -end diff --git a/sig/mindee/product/us/bank_check/bank_check_v1.rbs b/sig/mindee/product/us/bank_check/bank_check_v1.rbs deleted file mode 100644 index 6447d243a..000000000 --- a/sig/mindee/product/us/bank_check/bank_check_v1.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/product/../bank_check/bank_check_v1.rb - -module Mindee - module Product - module US - module BankCheck - class BankCheckV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end - end -end diff --git a/sig/mindee/product/us/bank_check/bank_check_v1_document.rbs b/sig/mindee/product/us/bank_check/bank_check_v1_document.rbs deleted file mode 100644 index 34983c309..000000000 --- a/sig/mindee/product/us/bank_check/bank_check_v1_document.rbs +++ /dev/null @@ -1,20 +0,0 @@ -# lib/mindee/product/../bank_check/bank_check_v1_document.rb - -module Mindee - module Product - module US - module BankCheck - class BankCheckV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def account_number: -> (Parsing::Standard::StringField) - def amount: -> (Parsing::Standard::AmountField) - def check_number: -> (Parsing::Standard::StringField) - def date: -> (Parsing::Standard::DateField) - def payees: -> (Array[Parsing::Standard::StringField]) - def routing_number: -> (Parsing::Standard::StringField) - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/us/bank_check/bank_check_v1_page.rbs b/sig/mindee/product/us/bank_check/bank_check_v1_page.rbs deleted file mode 100644 index 624527667..000000000 --- a/sig/mindee/product/us/bank_check/bank_check_v1_page.rbs +++ /dev/null @@ -1,19 +0,0 @@ -# lib/mindee/product/../bank_check/bank_check_v1_page.rb - -module Mindee - module Product - module US - module BankCheck - class BankCheckV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class BankCheckV1PagePrediction < BankCheckV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def check_position: -> Parsing::Standard::PositionField - def signatures_positions: -> Array[Parsing::Standard::PositionField] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/us/healthcare_card/healthcare_card_v1.rbs b/sig/mindee/product/us/healthcare_card/healthcare_card_v1.rbs deleted file mode 100644 index 847b6a612..000000000 --- a/sig/mindee/product/us/healthcare_card/healthcare_card_v1.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/product/../healthcare_card/healthcare_card_v1.rb - -module Mindee - module Product - module US - module HealthcareCard - class HealthcareCardV1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end - end -end diff --git a/sig/mindee/product/us/healthcare_card/healthcare_card_v1_copays.rbs b/sig/mindee/product/us/healthcare_card/healthcare_card_v1_copays.rbs deleted file mode 100644 index 3a4c387bd..000000000 --- a/sig/mindee/product/us/healthcare_card/healthcare_card_v1_copays.rbs +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true - -module Mindee - module Product - module US - module HealthcareCard - class HealthcareCardV1Copays < Array[HealthcareCardV1Copay] - def initialize: (Array[untyped], Integer?) -> void - def self.line_items_separator: (String) -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/us/healthcare_card/healthcare_card_v1_document.rbs b/sig/mindee/product/us/healthcare_card/healthcare_card_v1_document.rbs deleted file mode 100644 index 6f6ec9b8c..000000000 --- a/sig/mindee/product/us/healthcare_card/healthcare_card_v1_document.rbs +++ /dev/null @@ -1,30 +0,0 @@ -# lib/mindee/product/../healthcare_card/healthcare_card_v1_document.rb - -module Mindee - module Product - module US - module HealthcareCard - class HealthcareCardV1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def company_name: -> (Parsing::Standard::StringField) - def copays: -> (Product::US::HealthcareCard::HealthcareCardV1Copays) - def dependents: -> (Array[Parsing::Standard::StringField]) - def enrollment_date: -> (Parsing::Standard::DateField) - def group_number: -> (Parsing::Standard::StringField) - def issuer80840: -> (Parsing::Standard::StringField) - def member_id: -> (Parsing::Standard::StringField) - def member_name: -> (Parsing::Standard::StringField) - def payer_id: -> (Parsing::Standard::StringField) - def plan_name: -> (Parsing::Standard::StringField) - def rx_bin: -> (Parsing::Standard::StringField) - def rx_grp: -> (Parsing::Standard::StringField) - def rx_id: -> (Parsing::Standard::StringField) - def rx_pcn: -> (Parsing::Standard::StringField) - def copays_separator: (String) -> String - def copays_to_s: -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/us/healthcare_card/healthcare_card_v1_page.rbs b/sig/mindee/product/us/healthcare_card/healthcare_card_v1_page.rbs deleted file mode 100644 index cf6b9255f..000000000 --- a/sig/mindee/product/us/healthcare_card/healthcare_card_v1_page.rbs +++ /dev/null @@ -1,17 +0,0 @@ -# lib/mindee/product/../healthcare_card/healthcare_card_v1_page.rb - -module Mindee - module Product - module US - module HealthcareCard - class HealthcareCardV1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class HealthcareCardV1PagePrediction < HealthcareCardV1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/us/us_mail/us_mail_v3.rbs b/sig/mindee/product/us/us_mail/us_mail_v3.rbs deleted file mode 100644 index 67efde76d..000000000 --- a/sig/mindee/product/us/us_mail/us_mail_v3.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/product/../us_mail/us_mail_v3.rb - -module Mindee - module Product - module US - module UsMail - class UsMailV3 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end - end -end diff --git a/sig/mindee/product/us/us_mail/us_mail_v3_document.rbs b/sig/mindee/product/us/us_mail/us_mail_v3_document.rbs deleted file mode 100644 index 20b351207..000000000 --- a/sig/mindee/product/us/us_mail/us_mail_v3_document.rbs +++ /dev/null @@ -1,21 +0,0 @@ -# lib/mindee/product/../us_mail/us_mail_v3_document.rb - -module Mindee - module Product - module US - module UsMail - class UsMailV3Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def is_return_to_sender: -> (Parsing::Standard::BooleanField) - def recipient_addresses: -> (Product::US::UsMail::UsMailV3RecipientAddresses) - def recipient_names: -> (Array[Parsing::Standard::StringField]) - def sender_address: -> (Product::US::UsMail::UsMailV3SenderAddress) - def sender_name: -> (Parsing::Standard::StringField) - def recipient_addresses_separator: (String) -> String - def recipient_addresses_to_s: -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/us/us_mail/us_mail_v3_recipient_address.rbs b/sig/mindee/product/us/us_mail/us_mail_v3_recipient_address.rbs deleted file mode 100644 index b10006886..000000000 --- a/sig/mindee/product/us/us_mail/us_mail_v3_recipient_address.rbs +++ /dev/null @@ -1,23 +0,0 @@ -module Mindee - module Product - module US - module UsMail - class UsMailV3RecipientAddress < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def city: -> String - def complete: -> String - def is_address_change: -> bool - def postal_code: -> String - def private_mailbox_number: -> String - def state: -> String - def street: -> String - def unit: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def table_printable_values: -> Hash[String | Symbol, untyped] - def to_table_line: -> String - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/us/us_mail/us_mail_v3_sender_address.rbs b/sig/mindee/product/us/us_mail/us_mail_v3_sender_address.rbs deleted file mode 100644 index 2928e024e..000000000 --- a/sig/mindee/product/us/us_mail/us_mail_v3_sender_address.rbs +++ /dev/null @@ -1,18 +0,0 @@ -module Mindee - module Product - module US - module UsMail - class UsMailV3SenderAddress < Parsing::Standard::FeatureField - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def city: -> String - def complete: -> String - def postal_code: -> String - def state: -> String - def street: -> String - def printable_values: -> Hash[String | Symbol, untyped] - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/us/w9/w9_v1.rbs b/sig/mindee/product/us/w9/w9_v1.rbs deleted file mode 100644 index a7e8bd007..000000000 --- a/sig/mindee/product/us/w9/w9_v1.rbs +++ /dev/null @@ -1,13 +0,0 @@ -# lib/mindee/product/../w9/w9_v1.rb - -module Mindee - module Product - module US - module W9 - class W9V1 < Parsing::Common::Inference - def initialize: (Hash[String | Symbol, untyped]) -> void - end - end - end - end -end diff --git a/sig/mindee/product/us/w9/w9_v1_document.rbs b/sig/mindee/product/us/w9/w9_v1_document.rbs deleted file mode 100644 index 67fd37879..000000000 --- a/sig/mindee/product/us/w9/w9_v1_document.rbs +++ /dev/null @@ -1,14 +0,0 @@ -# lib/mindee/product/../w9/w9_v1_document.rb - -module Mindee - module Product - module US - module W9 - class W9V1Document < Parsing::Common::Prediction - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/product/us/w9/w9_v1_page.rbs b/sig/mindee/product/us/w9/w9_v1_page.rbs deleted file mode 100644 index 1c49ec761..000000000 --- a/sig/mindee/product/us/w9/w9_v1_page.rbs +++ /dev/null @@ -1,29 +0,0 @@ -# lib/mindee/product/../w9/w9_v1_page.rb - -module Mindee - module Product - module US - module W9 - class W9V1Page < Parsing::Common::Page - def initialize: (Hash[String | Symbol, untyped]) -> void - end - class W9V1PagePrediction < W9V1Document - def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def address: -> Parsing::Standard::StringField - def business_name: -> Parsing::Standard::StringField - def city_state_zip: -> Parsing::Standard::StringField - def ein: -> Parsing::Standard::StringField - def name: -> Parsing::Standard::StringField - def signature_date_position: -> Parsing::Standard::PositionField - def signature_position: -> Parsing::Standard::PositionField - def ssn: -> Parsing::Standard::StringField - def tax_classification: -> Parsing::Standard::StringField - def tax_classification_llc: -> Parsing::Standard::StringField - def tax_classification_other_details: -> Parsing::Standard::StringField - def w9_revision_date: -> Parsing::Standard::StringField - def to_s: -> String - end - end - end - end -end diff --git a/sig/mindee/v1/client.rbs b/sig/mindee/v1/client.rbs new file mode 100644 index 000000000..2896d7594 --- /dev/null +++ b/sig/mindee/v1/client.rbs @@ -0,0 +1,84 @@ +# lib/v1/mindee/client.rb + +module Mindee + module V1 + OTS_OWNER: String + + class ParseOptions + attr_accessor all_words: bool + attr_accessor full_text: bool + attr_accessor close_file: bool + attr_accessor page_options: PageOptions + attr_accessor cropper: bool + attr_accessor rag: bool + attr_accessor workflow_id: String? + attr_accessor initial_delay_sec: Integer | Float + attr_accessor delay_sec: Integer | Float + attr_accessor max_retries: Integer + + def initialize: (params: Hash[String | Symbol, untyped]) -> void + end + + class WorkflowOptions + attr_accessor document_alias: (String?) + attr_accessor priority: (Symbol?) + attr_accessor full_text: bool + attr_accessor rag: bool? + attr_accessor public_url: (String?) + attr_accessor page_options: (PageOptions) + attr_accessor close_file: bool + + def initialize: (params: Hash[String | Symbol, untyped]) -> void + end + + class Client + @api_key: String? + + def initialize: (?api_key: String) -> void + + def logger: () -> Logging + + def parse: (Input::Source::LocalInputSource | Input::Source::URLInputSource, singleton(V1::Parsing::Common::Inference), ?endpoint: (V1::HTTP::Endpoint?), options: ParseOptions | Hash[String | Symbol, untyped]) -> V1::Parsing::Common::ApiResponse + + def parse_sync: (Input::Source::LocalInputSource | Input::Source::URLInputSource, singleton(V1::Parsing::Common::Inference), V1::HTTP::Endpoint, ParseOptions) -> V1::Parsing::Common::ApiResponse + + def enqueue: (Input::Source::LocalInputSource | Input::Source::URLInputSource, singleton(V1::Parsing::Common::Inference), ?endpoint: (V1::HTTP::Endpoint?), options: ParseOptions | Hash[String | Symbol, untyped]) -> V1::Parsing::Common::ApiResponse + + def parse_queued: (String, singleton(V1::Parsing::Common::Inference), ?endpoint: V1::HTTP::Endpoint?) -> V1::Parsing::Common::ApiResponse + + def enqueue_and_parse: (Input::Source::URLInputSource | Input::Source::LocalInputSource, singleton(V1::Parsing::Common::Inference), V1::HTTP::Endpoint, ParseOptions) -> V1::Parsing::Common::ApiResponse + + def execute_workflow: (Input::Source::URLInputSource | Input::Source::LocalInputSource, String, options: (Hash[String | Symbol, untyped] | WorkflowOptions)) -> V1::Parsing::Common::WorkflowResponse + + def load_prediction: (singleton(V1::Parsing::Common::Inference), Input::LocalResponse) -> V1::Parsing::Common::ApiResponse + + def source_from_path: (String, ?repair_pdf: bool) -> Input::Source::PathInputSource + + def source_from_bytes: (String, String, ?repair_pdf: bool) -> Input::Source::BytesInputSource + + def source_from_b64string: (String, String, ?repair_pdf: bool) -> Input::Source::Base64InputSource + + def source_from_file: (File, String, ?repair_pdf: bool) -> Input::Source::FileInputSource + + def source_from_url: (String) -> Input::Source::URLInputSource + + def create_endpoint: (endpoint_name: String, account_name: String, version: String) -> V1::HTTP::Endpoint + + private + + def normalize_parse_options: ((Hash[String | Symbol, untyped] | ParseOptions)) -> ParseOptions + + def process_pdf_if_required: (Input::Source::LocalInputSource, ParseOptions | WorkflowOptions) -> void + + def initialize_endpoint: (singleton(V1::Parsing::Common::Inference), ?endpoint_name: String, ?account_name: String, ?version: String) -> V1::HTTP::Endpoint + + def validate_async_params: (Integer | Float, Integer | Float, Integer) -> void + + def fix_endpoint_name: (singleton(V1::Parsing::Common::Inference), String?) -> String + + def fix_account_name: (String) -> String + + def fix_version: (singleton(V1::Parsing::Common::Inference), String) -> String + end + end +end diff --git a/sig/mindee/v1/extraction/multi_receipts_extractor.rbs b/sig/mindee/v1/extraction/multi_receipts_extractor.rbs new file mode 100644 index 000000000..ca2691837 --- /dev/null +++ b/sig/mindee/v1/extraction/multi_receipts_extractor.rbs @@ -0,0 +1,8 @@ +# lib/mindee/v1/extraction/multi_receipts_extractor.rb +module Mindee + module V1 + module Extraction + def self.extract_receipts: (Input::Source::LocalInputSource, Product::MultiReceiptsDetector::MultiReceiptsDetectorV1) -> Array[Image::ExtractedImage] + end + end +end diff --git a/sig/mindee/v1/http/endpoint.rbs b/sig/mindee/v1/http/endpoint.rbs new file mode 100644 index 000000000..b77755a57 --- /dev/null +++ b/sig/mindee/v1/http/endpoint.rbs @@ -0,0 +1,41 @@ +# lib/mindee/v1/http/endpoint.rb +module Mindee + module V1 + module HTTP + API_KEY_ENV_NAME: String + API_KEY_DEFAULT: String? + BASE_URL_ENV_NAME: String + BASE_URL_DEFAULT: String + REQUEST_TIMEOUT_ENV_NAME: String + TIMEOUT_DEFAULT: Integer + USER_AGENT: String + + class Endpoint + attr_reader api_key: String + attr_reader base_url: String + attr_reader request_timeout: Integer + attr_reader url_root: String + + def logger: () -> Logger + + def initialize: (String, String, String?, ?api_key: String) -> String + + def predict: (Input::Source::LocalInputSource | Input::Source::URLInputSource, ParseOptions) -> [Hash[String | Symbol, untyped], String] + + def predict_async: (Input::Source::LocalInputSource | Input::Source::URLInputSource, ParseOptions) -> [Hash[String | Symbol, untyped], String] + + def parse_async: (String) -> [Hash[String | Symbol, untyped], String] + + def predict_req_post: (Input::Source::LocalInputSource | Input::Source::URLInputSource, ParseOptions) -> Net::HTTPResponse + + def document_queue_req_post: (Input::Source::LocalInputSource | Input::Source::URLInputSource, ParseOptions) -> Net::HTTPResponse + + def document_queue_req_get: (String) -> Net::HTTPResponse + + def check_api_key: -> void + + def configure_ssl: (Net::HTTP) -> void + end + end + end +end diff --git a/sig/mindee/v1/http/workflow_endpoint.rbs b/sig/mindee/v1/http/workflow_endpoint.rbs new file mode 100644 index 000000000..7432bbec0 --- /dev/null +++ b/sig/mindee/v1/http/workflow_endpoint.rbs @@ -0,0 +1,22 @@ +# lib/mindee/v1/http/workflow_endpoint.rb +module Mindee + module V1 + module HTTP + class WorkflowEndpoint + def api_key: -> String + + def request_timeout: -> Integer + + def url: -> String + + def initialize: (untyped, ?api_key: String) -> String + + def execute_workflow: (Input::Source::LocalInputSource | Input::Source::URLInputSource, WorkflowOptions) -> [Hash[String, untyped], String] + + def workflow_execution_req_post: (Input::Source::LocalInputSource | Input::Source::URLInputSource, WorkflowOptions) -> Net::HTTPResponse? + + def check_api_key: -> nil + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/api_request.rbs b/sig/mindee/v1/parsing/common/api_request.rbs new file mode 100644 index 000000000..0b8ca410b --- /dev/null +++ b/sig/mindee/v1/parsing/common/api_request.rbs @@ -0,0 +1,22 @@ +# lib/mindee/v1/parsing/common/api_request.rb +module Mindee + module V1 + module Parsing + module Common + class ApiRequest + def error: -> Hash[String, untyped] + + def ressources: -> Array[String] + + def status: -> [RequestStatus, Symbol] + + def status_code: -> Integer + + def url: -> String + + def initialize: (Hash[String, untyped]) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/api_response.rbs b/sig/mindee/v1/parsing/common/api_response.rbs new file mode 100644 index 000000000..9b93a9d89 --- /dev/null +++ b/sig/mindee/v1/parsing/common/api_response.rbs @@ -0,0 +1,31 @@ +# lib/mindee/v1/parsing/common/api_response.rb +module Mindee + module V1 + module Parsing + module Common + module JobStatus + WAITING: :waiting + PROCESSING: :processing + COMPLETED: :completed + FAILURE: :failed + end + + module RequestStatus + FAILURE: :failure + SUCCESS: :success + end + + class ApiResponse + attr_reader document: Parsing::Common::Document? + attr_reader job: Parsing::Common::Job? + attr_reader api_request: Parsing::Common::ApiRequest + attr_reader raw_http: String + + def logger: () -> Logger + + def initialize: (singleton(Parsing::Common::Inference), Hash[String | Symbol, untyped] | Net::HTTPResponse, String) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/document.rbs b/sig/mindee/v1/parsing/common/document.rbs new file mode 100644 index 000000000..e86285256 --- /dev/null +++ b/sig/mindee/v1/parsing/common/document.rbs @@ -0,0 +1,32 @@ +# lib/mindee/v1/parsing/common/document.rb +module Mindee + module V1 + module Parsing + module Common + class Document + def inference: -> Inference + + def name: -> String + + def id: -> String + + def extras: -> Extras::Extras? + + def ocr: -> OCR::OCR? + + def n_pages: -> Integer + + def self.load_ocr: (Hash[String | Symbol, untyped]) -> Parsing::Common::OCR::OCR? + + def self.extract_extras: (Hash[String | Symbol, untyped]) -> Parsing::Common::Extras::Extras? + + def initialize: (singleton(Parsing::Common::Inference), Hash[String | Symbol, untyped]) -> void + + def to_s: -> String + + def inject_full_text_ocr: (Hash[String | Symbol, untyped]) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/execution.rbs b/sig/mindee/v1/parsing/common/execution.rbs new file mode 100644 index 000000000..b30fa44bc --- /dev/null +++ b/sig/mindee/v1/parsing/common/execution.rbs @@ -0,0 +1,26 @@ +# lib/mindee/v1/parsing/common/execution.rb +module Mindee + module V1 + module Parsing + module Common + class Execution + attr_reader available_at: Time? + attr_reader batch_name: String + attr_reader created_at: Time + attr_reader file: ExecutionFile + attr_reader id: String + attr_reader inference: Inference + attr_reader priority: Symbol? + attr_reader reviewed_at: Time? + attr_reader reviewed_prediction: Prediction? + attr_reader status: Symbol + attr_reader type: String? + attr_reader uploaded_at: Time? + attr_reader workflow_id: String + + def initialize: (singleton(Parsing::Common::Inference), Hash[String | Symbol, untyped]) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/execution_file.rbs b/sig/mindee/v1/parsing/common/execution_file.rbs new file mode 100644 index 000000000..e4530c544 --- /dev/null +++ b/sig/mindee/v1/parsing/common/execution_file.rbs @@ -0,0 +1,16 @@ +# lib/mindee/v1/parsing/common/execution_file.rb +module Mindee + module V1 + module Parsing + module Common + class ExecutionFile + def name: -> String + + def alias: -> String? + + def initialize: (Hash[String | Symbol, untyped]) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/execution_priority.rbs b/sig/mindee/v1/parsing/common/execution_priority.rbs new file mode 100644 index 000000000..2c1c51d67 --- /dev/null +++ b/sig/mindee/v1/parsing/common/execution_priority.rbs @@ -0,0 +1,16 @@ +# lib/mindee/v1/parsing/common/execution_priority.rb +module Mindee + module V1 + module Parsing + module Common + module ExecutionPriority + LOW: :low + MEDIUM: :medium + HIGH: :high + + def self.to_priority: (untyped) -> (:high | :low | :medium)? + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/extras/cropper_extra.rbs b/sig/mindee/v1/parsing/common/extras/cropper_extra.rbs new file mode 100644 index 000000000..72bdaf9be --- /dev/null +++ b/sig/mindee/v1/parsing/common/extras/cropper_extra.rbs @@ -0,0 +1,18 @@ +# lib/mindee/v1/parsing/common/extras/cropper_extra.rb +module Mindee + module V1 + module Parsing + module Common + module Extras + class CropperExtra + attr_reader croppings: Array[Standard::PositionField] + + def initialize: (Hash[String | Symbol, untyped], ?Integer?) -> void + + def to_s: -> String + end + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/extras/extras.rbs b/sig/mindee/v1/parsing/common/extras/extras.rbs new file mode 100644 index 000000000..d8fc17f57 --- /dev/null +++ b/sig/mindee/v1/parsing/common/extras/extras.rbs @@ -0,0 +1,24 @@ +# lib/mindee/v1/parsing/common/extras/extras.rb +module Mindee + module V1 + module Parsing + module Common + module Extras + class Extras + attr_reader cropper: CropperExtra? + attr_reader full_text_ocr: FullTextOCRExtra + attr_reader rag: RAGExtra? + + def initialize: (Hash[String | Symbol, untyped]) -> void + + def to_s: -> String + + def add_artificial_extra: (Hash[String | Symbol, untyped]) -> void + end + + def empty?: -> bool + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/extras/full_text_ocr_extra.rbs b/sig/mindee/v1/parsing/common/extras/full_text_ocr_extra.rbs new file mode 100644 index 000000000..497d3962f --- /dev/null +++ b/sig/mindee/v1/parsing/common/extras/full_text_ocr_extra.rbs @@ -0,0 +1,22 @@ +# lib/mindee/v1/parsing/common/extras/full_text_ocr_extra.rb +module Mindee + module V1 + module Parsing + module Common + module Extras + class FullTextOCRExtra + def contents: -> String? + + def language: -> String? + + def initialize: (Hash[String | Symbol, untyped]) -> nil + + def to_s: -> String + + def <<: (?untyped?) -> untyped + end + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/extras/rag_extra.rbs b/sig/mindee/v1/parsing/common/extras/rag_extra.rbs new file mode 100644 index 000000000..b86991139 --- /dev/null +++ b/sig/mindee/v1/parsing/common/extras/rag_extra.rbs @@ -0,0 +1,19 @@ +# lib/mindee/v1/parsing/common/extras/rag_extra.rb + +module Mindee + module V1 + module Parsing + module Common + module Extras + class RAGExtra + def matching_document_id: -> String? + + def initialize: (untyped) -> nil + + def to_s: -> String + end + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/inference.rbs b/sig/mindee/v1/parsing/common/inference.rbs new file mode 100644 index 000000000..c9255023d --- /dev/null +++ b/sig/mindee/v1/parsing/common/inference.rbs @@ -0,0 +1,31 @@ +# lib/mindee/v1/parsing/common/inference.rb +module Mindee + module V1 + module Parsing + module Common + class Inference + def self.endpoint_name: () -> String? + + def self.endpoint_version: () -> String? + + def self.has_async: () -> bool + + def self.has_sync: () -> bool + + attr_reader endpoint_name: String + attr_reader endpoint_version: String + attr_reader extras: Extras::Extras + attr_reader has_async: bool + attr_reader has_sync: bool + attr_reader is_rotation_applied: bool + attr_reader pages: Array[Page] + attr_reader product: Product + + def initialize: (Hash[String | Symbol, untyped]) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/job.rbs b/sig/mindee/v1/parsing/common/job.rbs new file mode 100644 index 000000000..8b9b8f528 --- /dev/null +++ b/sig/mindee/v1/parsing/common/job.rbs @@ -0,0 +1,24 @@ +# lib/mindee/v1/parsing/common/job.rb +module Mindee + module V1 + module Parsing + module Common + class Job + def id: -> String + + def issued_at: -> Time + + def available_at: -> Time + + def status: () -> (:waiting | :processing | :completed | :failed) + + def millisecs_taken: -> Integer + + def error: -> Hash[String | Symbol, untyped] + + def initialize: (Hash[String | Symbol, untyped]) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/ocr/mvision_v1.rbs b/sig/mindee/v1/parsing/common/ocr/mvision_v1.rbs new file mode 100644 index 000000000..8b2220c10 --- /dev/null +++ b/sig/mindee/v1/parsing/common/ocr/mvision_v1.rbs @@ -0,0 +1,20 @@ +# lib/mindee/v1/parsing/common/ocr/mvision_v1.rb +module Mindee + module V1 + module Parsing + module Common + module OCR + class MVisionV1 + def pages: -> [ ] + + def initialize: (Hash[String | Symbol, untyped]) -> void + + def to_s: -> String + + def reconstruct_vertically: (Array[Geometry::Point], Integer, Float) -> OCRLine + end + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/ocr/ocr.rbs b/sig/mindee/v1/parsing/common/ocr/ocr.rbs new file mode 100644 index 000000000..1c1db9ce6 --- /dev/null +++ b/sig/mindee/v1/parsing/common/ocr/ocr.rbs @@ -0,0 +1,56 @@ +# lib/mindee/v1/parsing/common/ocr/ocr.rb +module Mindee + module V1 + module Parsing + module Common + module OCR + class OCRWord + attr_reader bounding_box: Geometry::Quadrilateral + attr_accessor confidence: Float + attr_reader polygon: Geometry::Polygon + attr_reader text: String + + def initialize: (Hash[String | Symbol, untyped]) -> void + + def to_s: -> String + end + + class OCRLine < Array[OCRWord] + def initialize: (?Array[untyped]?, ?Array[OCRWord]?) -> void + + def sort_on_x: -> OCRLine + + def to_s: -> String + end + + class OCRPage + attr_reader all_words: Array[OCRWord] + attr_reader lines: Array[OCRLine] + + def initialize: (Hash[String | Symbol, untyped]) -> void + + def all_lines: -> Array[OCRLine] + + def to_s: -> String + + def parse_one: (Array[OCRWord], OCRWord?, Array[Integer], Array[OCRLine]) -> Array[OCRLine]? + + def to_lines: -> Array[OCRLine] + + def words_on_same_line?: (OCRWord, OCRWord) -> bool + end + + class OCR + attr_reader mvision_v1: MVisionV1 + + def initialize: (Hash[String | Symbol, untyped]) -> void + + def to_s: -> String + + def reconstruct_vertically: (Array[Geometry::Point], Integer, ?Float) -> OCRLine + end + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/orientation.rbs b/sig/mindee/v1/parsing/common/orientation.rbs new file mode 100644 index 000000000..897085ebe --- /dev/null +++ b/sig/mindee/v1/parsing/common/orientation.rbs @@ -0,0 +1,15 @@ +# lib/mindee/v1/parsing/common/orientation.rb +module Mindee + module V1 + module Parsing + module Common + class Orientation + attr_reader page_id: Integer? + attr_reader value: Integer? + + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/page.rbs b/sig/mindee/v1/parsing/common/page.rbs new file mode 100644 index 000000000..5e533830c --- /dev/null +++ b/sig/mindee/v1/parsing/common/page.rbs @@ -0,0 +1,19 @@ +# lib/mindee/v1/parsing/common/page.rb +module Mindee + module V1 + module Parsing + module Common + class Page + attr_reader extras: Extras::Extras + attr_reader orientation: Common::Orientation + attr_reader page_id: Integer + attr_reader prediction: untyped # Voluntary to allow proper overloads, leave as-is. + + def initialize: (Hash[String | Symbol, untyped]) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/prediction.rbs b/sig/mindee/v1/parsing/common/prediction.rbs new file mode 100644 index 000000000..8c3f69f6a --- /dev/null +++ b/sig/mindee/v1/parsing/common/prediction.rbs @@ -0,0 +1,14 @@ +# lib/mindee/v1/parsing/common/prediction.rb +module Mindee + module V1 + module Parsing + module Common + class Prediction + def to_s: -> String + + def initialize: (untyped?, untyped?) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/product.rbs b/sig/mindee/v1/parsing/common/product.rbs new file mode 100644 index 000000000..32996474b --- /dev/null +++ b/sig/mindee/v1/parsing/common/product.rbs @@ -0,0 +1,16 @@ +# lib/mindee/v1/parsing/common/product.rb +module Mindee + module V1 + module Parsing + module Common + class Product + attr_reader name: String + attr_reader type: String? + attr_reader version: String + + def initialize: (Hash[String | Symbol, untyped]) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/common/workflow_response.rbs b/sig/mindee/v1/parsing/common/workflow_response.rbs new file mode 100644 index 000000000..7698809ad --- /dev/null +++ b/sig/mindee/v1/parsing/common/workflow_response.rbs @@ -0,0 +1,22 @@ +# lib/mindee/v1/parsing/common/workflow_response.rb +module Mindee + module V1 + module Parsing + module Common + class WorkflowResponse + @api_request: ApiRequest + @execution: Execution + @raw_http: String + + def execution: -> Execution + + def api_request: -> ApiRequest + + def raw_http: -> String + + def initialize: (singleton(Parsing::Common::Inference), Hash[String | Symbol, untyped] | Net::HTTPResponse, String) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/abstract_field.rbs b/sig/mindee/v1/parsing/standard/abstract_field.rbs new file mode 100644 index 000000000..3f6f99cb7 --- /dev/null +++ b/sig/mindee/v1/parsing/standard/abstract_field.rbs @@ -0,0 +1,30 @@ +# lib/mindee/v1/parsing/standard/abstract_field.rb +module Mindee + module V1 + module Parsing + module Standard + class AbstractField + def bounding_box: -> Geometry::Polygon? + + def polygon: -> Geometry::Polygon? + + def page_id: -> Integer? + + def confidence: -> Float? + + def confidence=: (Float?) -> Float? + + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def to_s: -> String + + def self.array_confidence: (Array[untyped]) -> Float + + def self.array_sum: (Array[untyped]) -> Float + + def self.float_to_string: (Float, ?Integer) -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/address_field.rbs b/sig/mindee/v1/parsing/standard/address_field.rbs new file mode 100644 index 000000000..87564e2c1 --- /dev/null +++ b/sig/mindee/v1/parsing/standard/address_field.rbs @@ -0,0 +1,28 @@ +# lib/mindee/v1/parsing/standard/address_field.rb +module Mindee + module V1 + module Parsing + module Standard + class AddressField < StringField + def street_number: -> String + + def street_name: -> String + + def po_box: -> String + + def address_complement: -> String + + def city: -> String + + def postal_code: -> String + + def state: -> String + + def country: -> String + + def initialize: (Hash[String | Symbol, untyped], ?Integer?, ?reconstructed: bool) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/amount_field.rbs b/sig/mindee/v1/parsing/standard/amount_field.rbs new file mode 100644 index 000000000..dea6e0c78 --- /dev/null +++ b/sig/mindee/v1/parsing/standard/amount_field.rbs @@ -0,0 +1,16 @@ +# lib/mindee/v1/parsing/standard/amount_field.rb +module Mindee + module V1 + module Parsing + module Standard + class AmountField < BaseField + attr_reader value: Float? + + def initialize: (Hash[String | Symbol, untyped], Integer?, ?reconstructed: bool) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/base_field.rbs b/sig/mindee/v1/parsing/standard/base_field.rbs new file mode 100644 index 000000000..2153b2c2c --- /dev/null +++ b/sig/mindee/v1/parsing/standard/base_field.rbs @@ -0,0 +1,16 @@ +# lib/mindee/v1/parsing/standard/base_field.rb +module Mindee + module V1 + module Parsing + module Standard + class BaseField < Parsing::Standard::AbstractField + def initialize: (Hash[String | Symbol, untyped], Integer?, ?reconstructed: bool) -> void + + def value: -> (String | Float | Integer | bool) + + def reconstructed: -> bool + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/boolean_field.rbs b/sig/mindee/v1/parsing/standard/boolean_field.rbs new file mode 100644 index 000000000..b18d13c68 --- /dev/null +++ b/sig/mindee/v1/parsing/standard/boolean_field.rbs @@ -0,0 +1,16 @@ +# lib/mindee/v1/parsing/standard/boolean_field.rb +module Mindee + module V1 + module Parsing + module Standard + class BooleanField < BaseField + def value: -> bool? + + def initialize: (Hash[String | Symbol, untyped], ?Integer?, ?reconstructed: false) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/classification_field.rbs b/sig/mindee/v1/parsing/standard/classification_field.rbs new file mode 100644 index 000000000..e174e2cf9 --- /dev/null +++ b/sig/mindee/v1/parsing/standard/classification_field.rbs @@ -0,0 +1,12 @@ +# lib/mindee/v1/parsing/standard/classification_field.rb +module Mindee + module V1 + module Parsing + module Standard + class ClassificationField < BaseField + def value: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/company_registration_field.rbs b/sig/mindee/v1/parsing/standard/company_registration_field.rbs new file mode 100644 index 000000000..325af88f5 --- /dev/null +++ b/sig/mindee/v1/parsing/standard/company_registration_field.rbs @@ -0,0 +1,20 @@ +# lib/mindee/v1/parsing/standard/company_registration_field.rb +module Mindee + module V1 + module Parsing + module Standard + class CompanyRegistrationField < BaseField + attr_reader type: String + + def initialize: (Hash[String | Symbol, untyped], Integer?, ?reconstructed: false) -> void + + def to_table_line: -> String + + def to_s: -> String + + def printable_values: -> Hash[Symbol, string] + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/date_field.rbs b/sig/mindee/v1/parsing/standard/date_field.rbs new file mode 100644 index 000000000..d8b050c43 --- /dev/null +++ b/sig/mindee/v1/parsing/standard/date_field.rbs @@ -0,0 +1,20 @@ +# lib/mindee/v1/parsing/standard/date_field.rb +module Mindee + module V1 + module Parsing + module Standard + class DateField < BaseField + def date_object: -> DateTime + + def value: -> String? + + def raw: -> String? + + def is_computed: -> bool + + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/feature_field.rbs b/sig/mindee/v1/parsing/standard/feature_field.rbs new file mode 100644 index 000000000..a43e31f25 --- /dev/null +++ b/sig/mindee/v1/parsing/standard/feature_field.rbs @@ -0,0 +1,12 @@ +# lib/mindee/v1/parsing/standard/feature_field.rb +module Mindee + module V1 + module Parsing + module Standard + class FeatureField < BaseField + def format_for_display: (String | bool?, ?Integer?) -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/locale_field.rbs b/sig/mindee/v1/parsing/standard/locale_field.rbs new file mode 100644 index 000000000..30b231ab8 --- /dev/null +++ b/sig/mindee/v1/parsing/standard/locale_field.rbs @@ -0,0 +1,24 @@ +# lib/mindee/v1/parsing/standard/locale_field.rb +module Mindee + module V1 + module Parsing + module Standard + class LocaleField + def confidence: -> Float? + + def language: -> String? + + def country: -> String? + + def currency: -> String? + + def value: -> String? + + def initialize: (Hash[String | Symbol, untyped], ?Integer?) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/payment_details_field.rbs b/sig/mindee/v1/parsing/standard/payment_details_field.rbs new file mode 100644 index 000000000..2631acc8e --- /dev/null +++ b/sig/mindee/v1/parsing/standard/payment_details_field.rbs @@ -0,0 +1,19 @@ +# lib/mindee/v1/parsing/standard/payment_details_field.rb +module Mindee + module V1 + module Parsing + module Standard + class PaymentDetailsField < BaseField + attr_reader account_number: String? + attr_reader iban: String? + attr_reader routing_number: String? + attr_reader swift: String? + + def initialize: (Hash[String | Symbol, untyped], Integer?, ?reconstructed: bool) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/position_field.rbs b/sig/mindee/v1/parsing/standard/position_field.rbs new file mode 100644 index 000000000..9c64db75f --- /dev/null +++ b/sig/mindee/v1/parsing/standard/position_field.rbs @@ -0,0 +1,26 @@ +# lib/mindee/v1/parsing/standard/position_field.rb +module Mindee + module V1 + module Parsing + module Standard + class PositionField + def polygon: -> Geometry::Polygon + + def value: -> Geometry::Polygon + + def quadrangle: -> Geometry::Quadrilateral + + def rectangle: -> Geometry::Quadrilateral + + def bounding_box: -> Geometry::Quadrilateral + + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def to_s: -> String + + def to_quadrilateral: (Hash[String | Symbol, Array[untyped]], String) -> Geometry::Quadrilateral? + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/string_field.rbs b/sig/mindee/v1/parsing/standard/string_field.rbs new file mode 100644 index 000000000..b3817c3b2 --- /dev/null +++ b/sig/mindee/v1/parsing/standard/string_field.rbs @@ -0,0 +1,16 @@ +# lib/mindee/v1/parsing/standard/string_field.rb +module Mindee + module V1 + module Parsing + module Standard + class StringField < BaseField + def value: -> String + + def raw_value: -> String + + def initialize: (Hash[String | Symbol, untyped], ?Integer?, ?reconstructed: bool) -> void + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/standard/tax_field.rbs b/sig/mindee/v1/parsing/standard/tax_field.rbs new file mode 100644 index 000000000..f3219fcbb --- /dev/null +++ b/sig/mindee/v1/parsing/standard/tax_field.rbs @@ -0,0 +1,33 @@ +# lib/mindee/v1/parsing/standard/tax_field.rb +module Mindee + module V1 + module Parsing + module Standard + class TaxField < BaseField + attr_reader base: Float + attr_reader code: String + attr_reader rate: Float + attr_reader value: Float? + + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def print_float: (Float) -> String + + def to_s: -> String + + def printable_values: -> Hash[Symbol, String] + + def to_table_line: -> String + end + + class Taxes < Array[TaxField] + def initialize: (Array[untyped], Integer?) -> void + + def line_separator: (String) -> String + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/universal/universal_list_field.rbs b/sig/mindee/v1/parsing/universal/universal_list_field.rbs new file mode 100644 index 000000000..bff4c488f --- /dev/null +++ b/sig/mindee/v1/parsing/universal/universal_list_field.rbs @@ -0,0 +1,21 @@ +# lib/mindee/v1/parsing/universal/universal_list_field.rb +module Mindee + module V1 + module Parsing + module Universal + class UniversalListField + attr_reader page_id: Integer + attr_reader values: Array[UniversalObjectField | Standard::StringField] + + def initialize: (Array[Hash[String | Symbol, untyped]], ?Integer?) -> void + + def contents_list: -> Array[String] + + def contents_string: (?String) -> String + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/parsing/universal/universal_object_field.rbs b/sig/mindee/v1/parsing/universal/universal_object_field.rbs new file mode 100644 index 000000000..ed01a5fb6 --- /dev/null +++ b/sig/mindee/v1/parsing/universal/universal_object_field.rbs @@ -0,0 +1,38 @@ +# lib/mindee/v1/parsing/universal/universal_object_field.rb +module Mindee + module V1 + module Parsing + module Universal + class UniversalObjectField + attr_reader all_values: Hash[String | Symbol, String | Standard::PositionField?] + attr_reader confidence: Float + attr_reader page_id: Integer + attr_reader raw_value: String + + def initialize: (Hash[String | Symbol, untyped], ?Integer?) -> void + + def str_level: (?Integer) -> String + + def method_missing: (Symbol, *untyped, untyped) + -> (String + | Integer + | Float + | bool + | Standard::PositionField + | Hash[String | Symbol, untyped] + ?) + + def respond_to_missing?: (Symbol, ?bool) -> bool + + def to_s: -> String + + def handle_position_field: (String | Symbol, Hash[String | Symbol, untyped] | Integer | String | Float | bool?, Integer?) -> void + + def handle_default_field: (String | Symbol, Hash[String | Symbol, untyped] | Integer | String | Float | bool?) -> void + end + + def self.universal_object?: (Hash[String | Symbol, untyped]) -> bool + end + end + end +end diff --git a/sig/mindee/product/barcode_reader/barcode_reader_v1.rbs b/sig/mindee/v1/product/barcode_reader/barcode_reader_v1.rbs similarity index 65% rename from sig/mindee/product/barcode_reader/barcode_reader_v1.rbs rename to sig/mindee/v1/product/barcode_reader/barcode_reader_v1.rbs index f6c25f5fa..a17f2f1a9 100644 --- a/sig/mindee/product/barcode_reader/barcode_reader_v1.rbs +++ b/sig/mindee/v1/product/barcode_reader/barcode_reader_v1.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/barcode_reader/barcode_reader_v1.rb +# lib/mindee/v1/product/barcode_reader/barcode_reader_v1.rb module Mindee - module Product + module V1 + module Product module BarcodeReader class BarcodeReaderV1 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void end + end end end end diff --git a/sig/mindee/product/barcode_reader/barcode_reader_v1_document.rbs b/sig/mindee/v1/product/barcode_reader/barcode_reader_v1_document.rbs similarity index 76% rename from sig/mindee/product/barcode_reader/barcode_reader_v1_document.rbs rename to sig/mindee/v1/product/barcode_reader/barcode_reader_v1_document.rbs index 1cf918b53..2ffcc0a26 100644 --- a/sig/mindee/product/barcode_reader/barcode_reader_v1_document.rbs +++ b/sig/mindee/v1/product/barcode_reader/barcode_reader_v1_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/barcode_reader/barcode_reader_v1_document.rb +# lib/mindee/v1/product/barcode_reader/barcode_reader_v1_document.rb module Mindee - module Product + module V1 + module Product module BarcodeReader class BarcodeReaderV1Document < Parsing::Common::Prediction def initialize: (Hash[String | Symbol, untyped], Integer?) -> void @@ -9,6 +10,7 @@ module Mindee def codes_2d: -> (Array[Parsing::Standard::StringField]) def to_s: -> String end + end end end end diff --git a/sig/mindee/product/barcode_reader/barcode_reader_v1_page.rbs b/sig/mindee/v1/product/barcode_reader/barcode_reader_v1_page.rbs similarity index 77% rename from sig/mindee/product/barcode_reader/barcode_reader_v1_page.rbs rename to sig/mindee/v1/product/barcode_reader/barcode_reader_v1_page.rbs index 4236b483e..41834d483 100644 --- a/sig/mindee/product/barcode_reader/barcode_reader_v1_page.rbs +++ b/sig/mindee/v1/product/barcode_reader/barcode_reader_v1_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/barcode_reader/barcode_reader_v1_page.rb +# lib/mindee/v1/product/barcode_reader/barcode_reader_v1_page.rb module Mindee - module Product + module V1 + module Product module BarcodeReader class BarcodeReaderV1Page < Parsing::Common::Page def initialize: (Hash[String | Symbol, untyped]) -> void @@ -10,6 +11,7 @@ module Mindee def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String end + end end end end diff --git a/sig/mindee/product/cropper/cropper_v1.rbs b/sig/mindee/v1/product/cropper/cropper_v1.rbs similarity index 67% rename from sig/mindee/product/cropper/cropper_v1.rbs rename to sig/mindee/v1/product/cropper/cropper_v1.rbs index e36799d73..7b12fb53e 100644 --- a/sig/mindee/product/cropper/cropper_v1.rbs +++ b/sig/mindee/v1/product/cropper/cropper_v1.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/cropper/cropper_v1.rb +# lib/mindee/v1/product/cropper/cropper_v1.rb module Mindee - module Product + module V1 + module Product module Cropper class CropperV1 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void end + end end end end diff --git a/sig/mindee/product/cropper/cropper_v1_document.rbs b/sig/mindee/v1/product/cropper/cropper_v1_document.rbs similarity index 70% rename from sig/mindee/product/cropper/cropper_v1_document.rbs rename to sig/mindee/v1/product/cropper/cropper_v1_document.rbs index a54ebb097..9cb23fe26 100644 --- a/sig/mindee/product/cropper/cropper_v1_document.rbs +++ b/sig/mindee/v1/product/cropper/cropper_v1_document.rbs @@ -1,12 +1,14 @@ -# lib/mindee/product/cropper/cropper_v1_document.rb +# lib/mindee/v1/product/cropper/cropper_v1_document.rb module Mindee - module Product + module V1 + module Product module Cropper class CropperV1Document < Parsing::Common::Prediction def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String end + end end end end diff --git a/sig/mindee/product/cropper/cropper_v1_page.rbs b/sig/mindee/v1/product/cropper/cropper_v1_page.rbs similarity index 68% rename from sig/mindee/product/cropper/cropper_v1_page.rbs rename to sig/mindee/v1/product/cropper/cropper_v1_page.rbs index b041c97d5..e90ab9e94 100644 --- a/sig/mindee/product/cropper/cropper_v1_page.rbs +++ b/sig/mindee/v1/product/cropper/cropper_v1_page.rbs @@ -1,16 +1,19 @@ -# lib/mindee/product/cropper/cropper_v1_page.rb +# lib/mindee/v1/product/cropper/cropper_v1_page.rb module Mindee - module Product + module V1 + module Product module Cropper class CropperV1Page < Parsing::Common::Page def initialize: (Hash[String | Symbol, untyped]) -> void end class CropperV1PagePrediction < CropperV1Document + attr_reader cropping: Array[Parsing::Standard::PositionField] + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def cropping: -> Array[Parsing::Standard::PositionField] def to_s: -> String end + end end end end diff --git a/sig/mindee/product/financial_document/financial_document_v1.rbs b/sig/mindee/v1/product/financial_document/financial_document_v1.rbs similarity index 64% rename from sig/mindee/product/financial_document/financial_document_v1.rbs rename to sig/mindee/v1/product/financial_document/financial_document_v1.rbs index 1958f2b86..529839afe 100644 --- a/sig/mindee/product/financial_document/financial_document_v1.rbs +++ b/sig/mindee/v1/product/financial_document/financial_document_v1.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/financial_document/financial_document_v1.rb +# lib/mindee/v1/product/financial_document/financial_document_v1.rb module Mindee - module Product + module V1 + module Product module FinancialDocument class FinancialDocumentV1 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void end + end end end end diff --git a/sig/mindee/product/financial_document/financial_document_v1_document.rbs b/sig/mindee/v1/product/financial_document/financial_document_v1_document.rbs similarity index 95% rename from sig/mindee/product/financial_document/financial_document_v1_document.rbs rename to sig/mindee/v1/product/financial_document/financial_document_v1_document.rbs index e16a6bf81..dba618c1f 100644 --- a/sig/mindee/product/financial_document/financial_document_v1_document.rbs +++ b/sig/mindee/v1/product/financial_document/financial_document_v1_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/financial_document/financial_document_v1_document.rb +# lib/mindee/v1/product/financial_document/financial_document_v1_document.rb module Mindee - module Product + module V1 + module Product module FinancialDocument class FinancialDocumentV1Document < Parsing::Common::Prediction def initialize: (Hash[String | Symbol, untyped], Integer?) -> void @@ -42,6 +43,7 @@ module Mindee def line_items_to_s: -> String def to_s: -> String end + end end end end diff --git a/sig/mindee/v1/product/financial_document/financial_document_v1_line_item.rbs b/sig/mindee/v1/product/financial_document/financial_document_v1_line_item.rbs new file mode 100644 index 000000000..9ad61b17a --- /dev/null +++ b/sig/mindee/v1/product/financial_document/financial_document_v1_line_item.rbs @@ -0,0 +1,35 @@ +module Mindee + module V1 + module Product + module FinancialDocument + class FinancialDocumentV1LineItem < Parsing::Standard::FeatureField + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def description: -> String + + def product_code: -> String + + def quantity: -> Float + + def tax_amount: -> Float + + def tax_rate: -> Float + + def total_amount: -> Float + + def unit_measure: -> String + + def unit_price: -> Float + + def printable_values: -> Hash[Symbol, String] + + def table_printable_values: -> Hash[String | Symbol, untyped] + + def to_table_line: -> String + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/product/financial_document/financial_document_v1_line_items.rbs b/sig/mindee/v1/product/financial_document/financial_document_v1_line_items.rbs similarity index 88% rename from sig/mindee/product/financial_document/financial_document_v1_line_items.rbs rename to sig/mindee/v1/product/financial_document/financial_document_v1_line_items.rbs index be830ec83..8aea927d2 100644 --- a/sig/mindee/product/financial_document/financial_document_v1_line_items.rbs +++ b/sig/mindee/v1/product/financial_document/financial_document_v1_line_items.rbs @@ -1,13 +1,15 @@ # frozen_string_literal: true module Mindee - module Product + module V1 + module Product module FinancialDocument class FinancialDocumentV1LineItems < Array[FinancialDocumentV1LineItem] def initialize: (Array[untyped], Integer?) -> void def self.line_items_separator: (String) -> String def to_s: -> String end + end end end end diff --git a/sig/mindee/product/financial_document/financial_document_v1_page.rbs b/sig/mindee/v1/product/financial_document/financial_document_v1_page.rbs similarity index 77% rename from sig/mindee/product/financial_document/financial_document_v1_page.rbs rename to sig/mindee/v1/product/financial_document/financial_document_v1_page.rbs index b0cf7072b..282a9933a 100644 --- a/sig/mindee/product/financial_document/financial_document_v1_page.rbs +++ b/sig/mindee/v1/product/financial_document/financial_document_v1_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/financial_document/financial_document_v1_page.rb +# lib/mindee/v1/product/financial_document/financial_document_v1_page.rb module Mindee - module Product + module V1 + module Product module FinancialDocument class FinancialDocumentV1Page < Parsing::Common::Page def initialize: (Hash[String | Symbol, untyped]) -> void @@ -10,6 +11,7 @@ module Mindee def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String end + end end end end diff --git a/sig/mindee/product/fr/bank_account_details/bank_account_details_v1.rbs b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v1.rbs similarity index 68% rename from sig/mindee/product/fr/bank_account_details/bank_account_details_v1.rbs rename to sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v1.rbs index 3dbdd649b..0f8c6b974 100644 --- a/sig/mindee/product/fr/bank_account_details/bank_account_details_v1.rbs +++ b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v1.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/../bank_account_details/bank_account_details_v1.rb +# lib/mindee/v1/product/bank_account_details/bank_account_details_v1.rb module Mindee - module Product + module V1 + module Product module FR module BankAccountDetails class BankAccountDetailsV1 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void + end end end end diff --git a/sig/mindee/product/fr/bank_account_details/bank_account_details_v1_document.rbs b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_document.rbs similarity index 81% rename from sig/mindee/product/fr/bank_account_details/bank_account_details_v1_document.rbs rename to sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_document.rbs index 77cc8662d..c406f444b 100644 --- a/sig/mindee/product/fr/bank_account_details/bank_account_details_v1_document.rbs +++ b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/../bank_account_details/bank_account_details_v1_document.rb +# lib/mindee/v1/product/bank_account_details/bank_account_details_v1_document.rb module Mindee - module Product + module V1 + module Product module FR module BankAccountDetails class BankAccountDetailsV1Document < Parsing::Common::Prediction @@ -10,6 +11,7 @@ module Mindee def iban: -> (Parsing::Standard::StringField) def swift: -> (Parsing::Standard::StringField) def to_s: -> String + end end end end diff --git a/sig/mindee/product/fr/bank_account_details/bank_account_details_v1_page.rbs b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_page.rbs similarity index 80% rename from sig/mindee/product/fr/bank_account_details/bank_account_details_v1_page.rbs rename to sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_page.rbs index 9aa88d771..cadfe4779 100644 --- a/sig/mindee/product/fr/bank_account_details/bank_account_details_v1_page.rbs +++ b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v1_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/../bank_account_details/bank_account_details_v1_page.rb +# lib/mindee/v1/product/bank_account_details/bank_account_details_v1_page.rb module Mindee - module Product + module V1 + module Product module FR module BankAccountDetails class BankAccountDetailsV1Page < Parsing::Common::Page @@ -10,6 +11,7 @@ module Mindee class BankAccountDetailsV1PagePrediction < BankAccountDetailsV1Document def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String + end end end end diff --git a/sig/mindee/product/fr/bank_account_details/bank_account_details_v2.rbs b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2.rbs similarity index 68% rename from sig/mindee/product/fr/bank_account_details/bank_account_details_v2.rbs rename to sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2.rbs index 4104f8cac..7c65ce892 100644 --- a/sig/mindee/product/fr/bank_account_details/bank_account_details_v2.rbs +++ b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/../bank_account_details/bank_account_details_v2.rb +# lib/mindee/v1/product/bank_account_details/bank_account_details_v2.rb module Mindee - module Product + module V1 + module Product module FR module BankAccountDetails class BankAccountDetailsV2 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void + end end end end diff --git a/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_bban.rbs b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_bban.rbs new file mode 100644 index 000000000..64d17ae09 --- /dev/null +++ b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_bban.rbs @@ -0,0 +1,25 @@ +module Mindee + module V1 + module Product + module FR + module BankAccountDetails + class BankAccountDetailsV2Bban < Parsing::Standard::FeatureField + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def bban_bank_code: -> String + + def bban_branch_code: -> String + + def bban_key: -> String + + def bban_number: -> String + + def printable_values: -> Hash[Symbol, String] + + def to_s: -> String + end + end + end + end + end +end diff --git a/sig/mindee/product/fr/bank_account_details/bank_account_details_v2_document.rbs b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_document.rbs similarity index 83% rename from sig/mindee/product/fr/bank_account_details/bank_account_details_v2_document.rbs rename to sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_document.rbs index 11925a9d4..74d3d1aa8 100644 --- a/sig/mindee/product/fr/bank_account_details/bank_account_details_v2_document.rbs +++ b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/../bank_account_details/bank_account_details_v2_document.rb +# lib/mindee/v1/product/bank_account_details/bank_account_details_v2_document.rb module Mindee - module Product + module V1 + module Product module FR module BankAccountDetails class BankAccountDetailsV2Document < Parsing::Common::Prediction @@ -11,6 +12,7 @@ module Mindee def iban: -> (Parsing::Standard::StringField) def swift_code: -> (Parsing::Standard::StringField) def to_s: -> String + end end end end diff --git a/sig/mindee/product/fr/bank_account_details/bank_account_details_v2_page.rbs b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_page.rbs similarity index 80% rename from sig/mindee/product/fr/bank_account_details/bank_account_details_v2_page.rbs rename to sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_page.rbs index 3b5813802..f288d4730 100644 --- a/sig/mindee/product/fr/bank_account_details/bank_account_details_v2_page.rbs +++ b/sig/mindee/v1/product/fr/bank_account_details/bank_account_details_v2_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/../bank_account_details/bank_account_details_v2_page.rb +# lib/mindee/v1/product/bank_account_details/bank_account_details_v2_page.rb module Mindee - module Product + module V1 + module Product module FR module BankAccountDetails class BankAccountDetailsV2Page < Parsing::Common::Page @@ -10,6 +11,7 @@ module Mindee class BankAccountDetailsV2PagePrediction < BankAccountDetailsV2Document def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String + end end end end diff --git a/sig/mindee/product/fr/bank_statement/bank_statement_v2.rbs b/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2.rbs similarity index 67% rename from sig/mindee/product/fr/bank_statement/bank_statement_v2.rbs rename to sig/mindee/v1/product/fr/bank_statement/bank_statement_v2.rbs index 9efba9b4f..81ced6e01 100644 --- a/sig/mindee/product/fr/bank_statement/bank_statement_v2.rbs +++ b/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/../bank_statement/bank_statement_v2.rb +# lib/mindee/v1/product/bank_statement/bank_statement_v2.rb module Mindee - module Product + module V1 + module Product module FR module BankStatement class BankStatementV2 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void + end end end end diff --git a/sig/mindee/product/fr/bank_statement/bank_statement_v2_document.rbs b/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_document.rbs similarity index 92% rename from sig/mindee/product/fr/bank_statement/bank_statement_v2_document.rbs rename to sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_document.rbs index 22dbadc3a..4caa38519 100644 --- a/sig/mindee/product/fr/bank_statement/bank_statement_v2_document.rbs +++ b/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/../bank_statement/bank_statement_v2_document.rb +# lib/mindee/v1/product/bank_statement/bank_statement_v2_document.rb module Mindee - module Product + module V1 + module Product module FR module BankStatement class BankStatementV2Document < Parsing::Common::Prediction @@ -22,6 +23,7 @@ module Mindee def transactions_separator: (String) -> String def transactions_to_s: -> String def to_s: -> String + end end end end diff --git a/sig/mindee/product/fr/bank_statement/bank_statement_v2_page.rbs b/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_page.rbs similarity index 79% rename from sig/mindee/product/fr/bank_statement/bank_statement_v2_page.rbs rename to sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_page.rbs index 3da539654..941b7eeaa 100644 --- a/sig/mindee/product/fr/bank_statement/bank_statement_v2_page.rbs +++ b/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/../bank_statement/bank_statement_v2_page.rb +# lib/mindee/v1/product/bank_statement/bank_statement_v2_page.rb module Mindee - module Product + module V1 + module Product module FR module BankStatement class BankStatementV2Page < Parsing::Common::Page @@ -10,6 +11,7 @@ module Mindee class BankStatementV2PagePrediction < BankStatementV2Document def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String + end end end end diff --git a/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_transaction.rbs b/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_transaction.rbs new file mode 100644 index 000000000..3097a8b25 --- /dev/null +++ b/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_transaction.rbs @@ -0,0 +1,27 @@ +module Mindee + module V1 + module Product + module FR + module BankStatement + class BankStatementV2Transaction < Parsing::Standard::FeatureField + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def amount: -> Float + + def date: -> String + + def description: -> String + + def printable_values: -> Hash[Symbol, String] + + def table_printable_values: -> Hash[String | Symbol, untyped] + + def to_table_line: -> String + + def to_s: -> String + end + end + end + end + end +end diff --git a/sig/mindee/product/fr/bank_statement/bank_statement_v2_transactions.rbs b/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_transactions.rbs similarity index 88% rename from sig/mindee/product/fr/bank_statement/bank_statement_v2_transactions.rbs rename to sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_transactions.rbs index b9fd35f41..0f27a52ff 100644 --- a/sig/mindee/product/fr/bank_statement/bank_statement_v2_transactions.rbs +++ b/sig/mindee/v1/product/fr/bank_statement/bank_statement_v2_transactions.rbs @@ -1,13 +1,15 @@ # frozen_string_literal: true module Mindee - module Product + module V1 + module Product module FR module BankStatement class BankStatementV2Transactions < Array[BankStatementV2Transaction] def initialize: (Array[untyped], Integer?) -> void def self.line_items_separator: (String) -> String def to_s: -> String + end end end end diff --git a/sig/mindee/v1/product/fr/id_card/id_card_v1.rbs b/sig/mindee/v1/product/fr/id_card/id_card_v1.rbs new file mode 100644 index 000000000..9f4de18d0 --- /dev/null +++ b/sig/mindee/v1/product/fr/id_card/id_card_v1.rbs @@ -0,0 +1,15 @@ +# lib/mindee/v1/product/id_card/id_card_v1.rb + +module Mindee + module V1 + module Product + module FR + module IdCard + class IdCardV1 < Parsing::Common::Inference + def initialize: (Hash[String | Symbol, untyped]) -> void + end + end + end + end + end +end diff --git a/sig/mindee/product/fr/id_card/id_card_v1_document.rbs b/sig/mindee/v1/product/fr/id_card/id_card_v1_document.rbs similarity index 89% rename from sig/mindee/product/fr/id_card/id_card_v1_document.rbs rename to sig/mindee/v1/product/fr/id_card/id_card_v1_document.rbs index 08759aac8..4fd206feb 100644 --- a/sig/mindee/product/fr/id_card/id_card_v1_document.rbs +++ b/sig/mindee/v1/product/fr/id_card/id_card_v1_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/../id_card/id_card_v1_document.rb +# lib/mindee/v1/product/id_card/id_card_v1_document.rb module Mindee - module Product + module V1 + module Product module FR module IdCard class IdCardV1Document < Parsing::Common::Prediction @@ -17,6 +18,7 @@ module Mindee def mrz2: -> (Parsing::Standard::StringField) def surname: -> (Parsing::Standard::StringField) def to_s: -> String + end end end end diff --git a/sig/mindee/product/fr/id_card/id_card_v1_page.rbs b/sig/mindee/v1/product/fr/id_card/id_card_v1_page.rbs similarity index 82% rename from sig/mindee/product/fr/id_card/id_card_v1_page.rbs rename to sig/mindee/v1/product/fr/id_card/id_card_v1_page.rbs index 9cf966626..601ddba1d 100644 --- a/sig/mindee/product/fr/id_card/id_card_v1_page.rbs +++ b/sig/mindee/v1/product/fr/id_card/id_card_v1_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/../id_card/id_card_v1_page.rb +# lib/mindee/v1/product/id_card/id_card_v1_page.rb module Mindee - module Product + module V1 + module Product module FR module IdCard class IdCardV1Page < Parsing::Common::Page @@ -11,6 +12,7 @@ module Mindee def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def document_side: -> Parsing::Standard::ClassificationField def to_s: -> String + end end end end diff --git a/sig/mindee/product/fr/id_card/id_card_v2.rbs b/sig/mindee/v1/product/fr/id_card/id_card_v2.rbs similarity index 69% rename from sig/mindee/product/fr/id_card/id_card_v2.rbs rename to sig/mindee/v1/product/fr/id_card/id_card_v2.rbs index b64e89040..9f29ff1f5 100644 --- a/sig/mindee/product/fr/id_card/id_card_v2.rbs +++ b/sig/mindee/v1/product/fr/id_card/id_card_v2.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/../id_card/id_card_v2.rb +# lib/mindee/v1/product/id_card/id_card_v2.rb module Mindee - module Product + module V1 + module Product module FR module IdCard class IdCardV2 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void + end end end end diff --git a/sig/mindee/product/fr/id_card/id_card_v2_document.rbs b/sig/mindee/v1/product/fr/id_card/id_card_v2_document.rbs similarity index 92% rename from sig/mindee/product/fr/id_card/id_card_v2_document.rbs rename to sig/mindee/v1/product/fr/id_card/id_card_v2_document.rbs index 6b6a3312f..a4e60a23d 100644 --- a/sig/mindee/product/fr/id_card/id_card_v2_document.rbs +++ b/sig/mindee/v1/product/fr/id_card/id_card_v2_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/../id_card/id_card_v2_document.rb +# lib/mindee/v1/product/id_card/id_card_v2_document.rb module Mindee - module Product + module V1 + module Product module FR module IdCard class IdCardV2Document < Parsing::Common::Prediction @@ -22,6 +23,7 @@ module Mindee def nationality: -> (Parsing::Standard::StringField) def surname: -> (Parsing::Standard::StringField) def to_s: -> String + end end end end diff --git a/sig/mindee/product/fr/id_card/id_card_v2_page.rbs b/sig/mindee/v1/product/fr/id_card/id_card_v2_page.rbs similarity index 84% rename from sig/mindee/product/fr/id_card/id_card_v2_page.rbs rename to sig/mindee/v1/product/fr/id_card/id_card_v2_page.rbs index f9bd4c9b4..3e9d32b40 100644 --- a/sig/mindee/product/fr/id_card/id_card_v2_page.rbs +++ b/sig/mindee/v1/product/fr/id_card/id_card_v2_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/../id_card/id_card_v2_page.rb +# lib/mindee/v1/product/id_card/id_card_v2_page.rb module Mindee - module Product + module V1 + module Product module FR module IdCard class IdCardV2Page < Parsing::Common::Page @@ -12,6 +13,7 @@ module Mindee def document_side: -> Parsing::Standard::ClassificationField def document_type: -> Parsing::Standard::ClassificationField def to_s: -> String + end end end end diff --git a/sig/mindee/product/international_id/international_id_v2.rbs b/sig/mindee/v1/product/international_id/international_id_v2.rbs similarity index 64% rename from sig/mindee/product/international_id/international_id_v2.rbs rename to sig/mindee/v1/product/international_id/international_id_v2.rbs index 2d3209608..4f14dffb9 100644 --- a/sig/mindee/product/international_id/international_id_v2.rbs +++ b/sig/mindee/v1/product/international_id/international_id_v2.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/international_id/international_id_v2.rb +# lib/mindee/v1/product/international_id/international_id_v2.rb module Mindee - module Product + module V1 + module Product module InternationalId class InternationalIdV2 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void end + end end end end diff --git a/sig/mindee/product/international_id/international_id_v2_document.rbs b/sig/mindee/v1/product/international_id/international_id_v2_document.rbs similarity index 91% rename from sig/mindee/product/international_id/international_id_v2_document.rbs rename to sig/mindee/v1/product/international_id/international_id_v2_document.rbs index 89605400a..93e986076 100644 --- a/sig/mindee/product/international_id/international_id_v2_document.rbs +++ b/sig/mindee/v1/product/international_id/international_id_v2_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/international_id/international_id_v2_document.rb +# lib/mindee/v1/product/international_id/international_id_v2_document.rb module Mindee - module Product + module V1 + module Product module InternationalId class InternationalIdV2Document < Parsing::Common::Prediction def initialize: (Hash[String | Symbol, untyped], Integer?) -> void @@ -24,6 +25,7 @@ module Mindee def surnames: -> (Array[Parsing::Standard::StringField]) def to_s: -> String end + end end end end diff --git a/sig/mindee/product/international_id/international_id_v2_page.rbs b/sig/mindee/v1/product/international_id/international_id_v2_page.rbs similarity index 77% rename from sig/mindee/product/international_id/international_id_v2_page.rbs rename to sig/mindee/v1/product/international_id/international_id_v2_page.rbs index aff9c96ec..853ab31c9 100644 --- a/sig/mindee/product/international_id/international_id_v2_page.rbs +++ b/sig/mindee/v1/product/international_id/international_id_v2_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/international_id/international_id_v2_page.rb +# lib/mindee/v1/product/international_id/international_id_v2_page.rb module Mindee - module Product + module V1 + module Product module InternationalId class InternationalIdV2Page < Parsing::Common::Page def initialize: (Hash[String | Symbol, untyped]) -> void @@ -10,6 +11,7 @@ module Mindee def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String end + end end end end diff --git a/sig/mindee/product/invoice/invoice_v4.rbs b/sig/mindee/v1/product/invoice/invoice_v4.rbs similarity index 67% rename from sig/mindee/product/invoice/invoice_v4.rbs rename to sig/mindee/v1/product/invoice/invoice_v4.rbs index dce951753..5a19f24c1 100644 --- a/sig/mindee/product/invoice/invoice_v4.rbs +++ b/sig/mindee/v1/product/invoice/invoice_v4.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/invoice/invoice_v4.rb +# lib/mindee/v1/product/invoice/invoice_v4.rb module Mindee - module Product + module V1 + module Product module Invoice class InvoiceV4 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void end + end end end end diff --git a/sig/mindee/product/invoice/invoice_v4_document.rbs b/sig/mindee/v1/product/invoice/invoice_v4_document.rbs similarity index 95% rename from sig/mindee/product/invoice/invoice_v4_document.rbs rename to sig/mindee/v1/product/invoice/invoice_v4_document.rbs index c1ac95247..58210c46f 100644 --- a/sig/mindee/product/invoice/invoice_v4_document.rbs +++ b/sig/mindee/v1/product/invoice/invoice_v4_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/invoice/invoice_v4_document.rb +# lib/mindee/v1/product/invoice/invoice_v4_document.rb module Mindee - module Product + module V1 + module Product module Invoice class InvoiceV4Document < Parsing::Common::Prediction def initialize: (Hash[String | Symbol, untyped], Integer?) -> void @@ -38,6 +39,7 @@ module Mindee def line_items_to_s: -> String def to_s: -> String end + end end end end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_usage.rbs b/sig/mindee/v1/product/invoice/invoice_v4_line_item.rbs similarity index 50% rename from sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_usage.rbs rename to sig/mindee/v1/product/invoice/invoice_v4_line_item.rbs index f2f2f412d..4962dc0c9 100644 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_usage.rbs +++ b/sig/mindee/v1/product/invoice/invoice_v4_line_item.rbs @@ -1,20 +1,32 @@ module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1EnergyUsage < Parsing::Standard::FeatureField + module V1 + module Product + module Invoice + class InvoiceV4LineItem < Parsing::Standard::FeatureField def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def consumption: -> Float + def description: -> String - def end_date: -> String - def start_date: -> String + + def product_code: -> String + + def quantity: -> Float + + def tax_amount: -> Float + def tax_rate: -> Float - def total: -> Float - def unit: -> String + + def total_amount: -> Float + + def unit_measure: -> String + def unit_price: -> Float - def printable_values: -> Hash[String | Symbol, untyped] + + def printable_values: -> Hash[Symbol, String] + def table_printable_values: -> Hash[String | Symbol, untyped] + def to_table_line: -> String + def to_s: -> String end end diff --git a/sig/mindee/product/invoice/invoice_v4_line_items.rbs b/sig/mindee/v1/product/invoice/invoice_v4_line_items.rbs similarity index 87% rename from sig/mindee/product/invoice/invoice_v4_line_items.rbs rename to sig/mindee/v1/product/invoice/invoice_v4_line_items.rbs index 916900683..b821e91a0 100644 --- a/sig/mindee/product/invoice/invoice_v4_line_items.rbs +++ b/sig/mindee/v1/product/invoice/invoice_v4_line_items.rbs @@ -1,13 +1,15 @@ # frozen_string_literal: true module Mindee - module Product + module V1 + module Product module Invoice class InvoiceV4LineItems < Array[InvoiceV4LineItem] def initialize: (Array[untyped], Integer?) -> void def self.line_items_separator: (String) -> String def to_s: -> String end + end end end end diff --git a/sig/mindee/product/invoice/invoice_v4_page.rbs b/sig/mindee/v1/product/invoice/invoice_v4_page.rbs similarity index 78% rename from sig/mindee/product/invoice/invoice_v4_page.rbs rename to sig/mindee/v1/product/invoice/invoice_v4_page.rbs index 041228d4b..3a3f0fb93 100644 --- a/sig/mindee/product/invoice/invoice_v4_page.rbs +++ b/sig/mindee/v1/product/invoice/invoice_v4_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/invoice/invoice_v4_page.rb +# lib/mindee/v1/product/invoice/invoice_v4_page.rb module Mindee - module Product + module V1 + module Product module Invoice class InvoiceV4Page < Parsing::Common::Page def initialize: (Hash[String | Symbol, untyped]) -> void @@ -10,6 +11,7 @@ module Mindee def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String end + end end end end diff --git a/sig/mindee/product/invoice_splitter/invoice_splitter_v1.rbs b/sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1.rbs similarity index 64% rename from sig/mindee/product/invoice_splitter/invoice_splitter_v1.rbs rename to sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1.rbs index e34fb52e6..2d50c2e60 100644 --- a/sig/mindee/product/invoice_splitter/invoice_splitter_v1.rbs +++ b/sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/invoice_splitter/invoice_splitter_v1.rb +# lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1.rb module Mindee - module Product + module V1 + module Product module InvoiceSplitter class InvoiceSplitterV1 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void end + end end end end diff --git a/sig/mindee/product/invoice_splitter/invoice_splitter_v1_document.rbs b/sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_document.rbs similarity index 79% rename from sig/mindee/product/invoice_splitter/invoice_splitter_v1_document.rbs rename to sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_document.rbs index 890486052..3de0203b4 100644 --- a/sig/mindee/product/invoice_splitter/invoice_splitter_v1_document.rbs +++ b/sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/invoice_splitter/invoice_splitter_v1_document.rb +# lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_document.rb module Mindee - module Product + module V1 + module Product module InvoiceSplitter class InvoiceSplitterV1Document < Parsing::Common::Prediction def initialize: (Hash[String | Symbol, untyped], Integer?) -> void @@ -10,6 +11,7 @@ module Mindee def invoice_page_groups_to_s: -> String def to_s: -> String end + end end end end diff --git a/sig/mindee/product/us/healthcare_card/healthcare_card_v1_copay.rbs b/sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rbs similarity index 50% rename from sig/mindee/product/us/healthcare_card/healthcare_card_v1_copay.rbs rename to sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rbs index a90161305..b1929140a 100644 --- a/sig/mindee/product/us/healthcare_card/healthcare_card_v1_copay.rbs +++ b/sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_group.rbs @@ -1,14 +1,18 @@ module Mindee - module Product - module US - module HealthcareCard - class HealthcareCardV1Copay < Parsing::Standard::FeatureField + module V1 + module Product + module InvoiceSplitter + class InvoiceSplitterV1InvoicePageGroup < Parsing::Standard::FeatureField def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def service_fees: -> Float - def service_name: -> String - def printable_values: -> Hash[String | Symbol, untyped] + + def page_indexes: -> Array[Integer] + + def printable_values: -> Hash[Symbol, String] + def table_printable_values: -> Hash[String | Symbol, untyped] + def to_table_line: -> String + def to_s: -> String end end diff --git a/sig/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rbs b/sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rbs similarity index 89% rename from sig/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rbs rename to sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rbs index 188b8867b..90a0d0701 100644 --- a/sig/mindee/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rbs +++ b/sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_invoice_page_groups.rbs @@ -1,13 +1,15 @@ # frozen_string_literal: true module Mindee - module Product + module V1 + module Product module InvoiceSplitter class InvoiceSplitterV1InvoicePageGroups < Array[InvoiceSplitterV1InvoicePageGroup] def initialize: (Array[untyped], Integer?) -> void def self.line_items_separator: (String) -> String def to_s: -> String end + end end end end diff --git a/sig/mindee/product/invoice_splitter/invoice_splitter_v1_page.rbs b/sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_page.rbs similarity index 77% rename from sig/mindee/product/invoice_splitter/invoice_splitter_v1_page.rbs rename to sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_page.rbs index 2ed881454..c9e553d3b 100644 --- a/sig/mindee/product/invoice_splitter/invoice_splitter_v1_page.rbs +++ b/sig/mindee/v1/product/invoice_splitter/invoice_splitter_v1_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/invoice_splitter/invoice_splitter_v1_page.rb +# lib/mindee/v1/product/invoice_splitter/invoice_splitter_v1_page.rb module Mindee - module Product + module V1 + module Product module InvoiceSplitter class InvoiceSplitterV1Page < Parsing::Common::Page def initialize: (Hash[String | Symbol, untyped]) -> void @@ -10,6 +11,7 @@ module Mindee def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String end + end end end end diff --git a/sig/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1.rbs b/sig/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1.rbs new file mode 100644 index 000000000..f6688fc08 --- /dev/null +++ b/sig/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1.rbs @@ -0,0 +1,14 @@ +# lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1.rb + +module Mindee + module V1 + module Product + module MultiReceiptsDetector + class MultiReceiptsDetectorV1 < Parsing::Common::Inference + attr_reader prediction: MultiReceiptsDetectorV1Document + def initialize: (Hash[String | Symbol, untyped]) -> void + end + end + end + end +end diff --git a/sig/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_document.rbs b/sig/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_document.rbs similarity index 55% rename from sig/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_document.rbs rename to sig/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_document.rbs index eafb6b58a..5a7689873 100644 --- a/sig/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_document.rbs +++ b/sig/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_document.rbs @@ -1,13 +1,15 @@ -# lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_document.rb +# lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_document.rb module Mindee - module Product + module V1 + module Product module MultiReceiptsDetector class MultiReceiptsDetectorV1Document < Parsing::Common::Prediction + attr_reader receipts:(Array[Parsing::Standard::PositionField]) def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def receipts: -> (Array[Parsing::Standard::PositionField]) def to_s: -> String end + end end end end diff --git a/sig/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_page.rbs b/sig/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_page.rbs similarity index 76% rename from sig/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_page.rbs rename to sig/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_page.rbs index 949e77e52..a131abdd6 100644 --- a/sig/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_page.rbs +++ b/sig/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/multi_receipts_detector/multi_receipts_detector_v1_page.rb +# lib/mindee/v1/product/multi_receipts_detector/multi_receipts_detector_v1_page.rb module Mindee - module Product + module V1 + module Product module MultiReceiptsDetector class MultiReceiptsDetectorV1Page < Parsing::Common::Page def initialize: (Hash[String | Symbol, untyped]) -> void @@ -10,6 +11,7 @@ module Mindee def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String end + end end end end diff --git a/sig/mindee/product/passport/passport_v1.rbs b/sig/mindee/v1/product/passport/passport_v1.rbs similarity index 66% rename from sig/mindee/product/passport/passport_v1.rbs rename to sig/mindee/v1/product/passport/passport_v1.rbs index e4c84f49a..ff32afc06 100644 --- a/sig/mindee/product/passport/passport_v1.rbs +++ b/sig/mindee/v1/product/passport/passport_v1.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/passport/passport_v1.rb +# lib/mindee/v1/product/passport/passport_v1.rb module Mindee - module Product + module V1 + module Product module Passport class PassportV1 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void end + end end end end diff --git a/sig/mindee/product/passport/passport_v1_document.rbs b/sig/mindee/v1/product/passport/passport_v1_document.rbs similarity index 89% rename from sig/mindee/product/passport/passport_v1_document.rbs rename to sig/mindee/v1/product/passport/passport_v1_document.rbs index 1f2c6dd18..db6e078f6 100644 --- a/sig/mindee/product/passport/passport_v1_document.rbs +++ b/sig/mindee/v1/product/passport/passport_v1_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/passport/passport_v1_document.rb +# lib/mindee/v1/product/passport/passport_v1_document.rb module Mindee - module Product + module V1 + module Product module Passport class PassportV1Document < Parsing::Common::Prediction def initialize: (Hash[String | Symbol, untyped], Integer?) -> void @@ -18,6 +19,7 @@ module Mindee def surname: -> (Parsing::Standard::StringField) def to_s: -> String end + end end end end diff --git a/sig/mindee/product/passport/passport_v1_page.rbs b/sig/mindee/v1/product/passport/passport_v1_page.rbs similarity index 78% rename from sig/mindee/product/passport/passport_v1_page.rbs rename to sig/mindee/v1/product/passport/passport_v1_page.rbs index 33d9a2fc8..73d581c55 100644 --- a/sig/mindee/product/passport/passport_v1_page.rbs +++ b/sig/mindee/v1/product/passport/passport_v1_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/passport/passport_v1_page.rb +# lib/mindee/v1/product/passport/passport_v1_page.rb module Mindee - module Product + module V1 + module Product module Passport class PassportV1Page < Parsing::Common::Page def initialize: (Hash[String | Symbol, untyped]) -> void @@ -10,6 +11,7 @@ module Mindee def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String end + end end end end diff --git a/sig/mindee/product/receipt/receipt_v5.rbs b/sig/mindee/v1/product/receipt/receipt_v5.rbs similarity index 67% rename from sig/mindee/product/receipt/receipt_v5.rbs rename to sig/mindee/v1/product/receipt/receipt_v5.rbs index 025be2f62..2f4a6e7b4 100644 --- a/sig/mindee/product/receipt/receipt_v5.rbs +++ b/sig/mindee/v1/product/receipt/receipt_v5.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/receipt/receipt_v5.rb +# lib/mindee/v1/product/receipt/receipt_v5.rb module Mindee - module Product + module V1 + module Product module Receipt class ReceiptV5 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void end + end end end end diff --git a/sig/mindee/product/receipt/receipt_v5_document.rbs b/sig/mindee/v1/product/receipt/receipt_v5_document.rbs similarity index 93% rename from sig/mindee/product/receipt/receipt_v5_document.rbs rename to sig/mindee/v1/product/receipt/receipt_v5_document.rbs index ffe778796..6c3026034 100644 --- a/sig/mindee/product/receipt/receipt_v5_document.rbs +++ b/sig/mindee/v1/product/receipt/receipt_v5_document.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/receipt/receipt_v5_document.rb +# lib/mindee/v1/product/receipt/receipt_v5_document.rb module Mindee - module Product + module V1 + module Product module Receipt class ReceiptV5Document < Parsing::Common::Prediction def initialize: (Hash[String | Symbol, untyped], Integer?) -> void @@ -26,6 +27,7 @@ module Mindee def line_items_to_s: -> String def to_s: -> String end + end end end end diff --git a/sig/mindee/product/fr/bank_statement/bank_statement_v2_transaction.rbs b/sig/mindee/v1/product/receipt/receipt_v5_line_item.rbs similarity index 51% rename from sig/mindee/product/fr/bank_statement/bank_statement_v2_transaction.rbs rename to sig/mindee/v1/product/receipt/receipt_v5_line_item.rbs index aef64ec1f..5cb4816e2 100644 --- a/sig/mindee/product/fr/bank_statement/bank_statement_v2_transaction.rbs +++ b/sig/mindee/v1/product/receipt/receipt_v5_line_item.rbs @@ -1,15 +1,24 @@ module Mindee - module Product - module FR - module BankStatement - class BankStatementV2Transaction < Parsing::Standard::FeatureField + module V1 + module Product + module Receipt + class ReceiptV5LineItem < Parsing::Standard::FeatureField def initialize: (Hash[String | Symbol, untyped], Integer?) -> void - def amount: -> Float - def date: -> String + def description: -> String - def printable_values: -> Hash[String | Symbol, untyped] + + def quantity: -> Float + + def total_amount: -> Float + + def unit_price: -> Float + + def printable_values: -> Hash[Symbol, String] + def table_printable_values: -> Hash[String | Symbol, untyped] + def to_table_line: -> String + def to_s: -> String end end diff --git a/sig/mindee/product/receipt/receipt_v5_line_items.rbs b/sig/mindee/v1/product/receipt/receipt_v5_line_items.rbs similarity index 87% rename from sig/mindee/product/receipt/receipt_v5_line_items.rbs rename to sig/mindee/v1/product/receipt/receipt_v5_line_items.rbs index 13a5484d8..081efcc55 100644 --- a/sig/mindee/product/receipt/receipt_v5_line_items.rbs +++ b/sig/mindee/v1/product/receipt/receipt_v5_line_items.rbs @@ -1,13 +1,15 @@ # frozen_string_literal: true module Mindee - module Product + module V1 + module Product module Receipt class ReceiptV5LineItems < Array[ReceiptV5LineItem] def initialize: (Array[untyped], Integer?) -> void def self.line_items_separator: (String) -> String def to_s: -> String end + end end end end diff --git a/sig/mindee/product/receipt/receipt_v5_page.rbs b/sig/mindee/v1/product/receipt/receipt_v5_page.rbs similarity index 78% rename from sig/mindee/product/receipt/receipt_v5_page.rbs rename to sig/mindee/v1/product/receipt/receipt_v5_page.rbs index 92afc1c08..bd988a53e 100644 --- a/sig/mindee/product/receipt/receipt_v5_page.rbs +++ b/sig/mindee/v1/product/receipt/receipt_v5_page.rbs @@ -1,7 +1,8 @@ -# lib/mindee/product/receipt/receipt_v5_page.rb +# lib/mindee/v1/product/receipt/receipt_v5_page.rb module Mindee - module Product + module V1 + module Product module Receipt class ReceiptV5Page < Parsing::Common::Page def initialize: (Hash[String | Symbol, untyped]) -> void @@ -10,6 +11,7 @@ module Mindee def initialize: (Hash[String | Symbol, untyped], Integer?) -> void def to_s: -> String end + end end end end diff --git a/sig/mindee/product/resume/resume_v1.rbs b/sig/mindee/v1/product/resume/resume_v1.rbs similarity index 67% rename from sig/mindee/product/resume/resume_v1.rbs rename to sig/mindee/v1/product/resume/resume_v1.rbs index be7ab1f4a..369cf6e21 100644 --- a/sig/mindee/product/resume/resume_v1.rbs +++ b/sig/mindee/v1/product/resume/resume_v1.rbs @@ -1,11 +1,13 @@ -# lib/mindee/product/resume/resume_v1.rb +# lib/mindee/v1/product/resume/resume_v1.rb module Mindee - module Product + module V1 + module Product module Resume class ResumeV1 < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void end + end end end end diff --git a/sig/mindee/v1/product/resume/resume_v1_certificate.rbs b/sig/mindee/v1/product/resume/resume_v1_certificate.rbs new file mode 100644 index 000000000..98b30446c --- /dev/null +++ b/sig/mindee/v1/product/resume/resume_v1_certificate.rbs @@ -0,0 +1,27 @@ +module Mindee + module V1 + module Product + module Resume + class ResumeV1Certificate < Parsing::Standard::FeatureField + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def grade: -> String + + def name: -> String + + def provider: -> String + + def year: -> String + + def printable_values: -> Hash[Symbol, String] + + def table_printable_values: -> Hash[String | Symbol, untyped] + + def to_table_line: -> String + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_paid_time_offs.rbs b/sig/mindee/v1/product/resume/resume_v1_certificates.rbs similarity index 66% rename from sig/mindee/product/fr/payslip/payslip_v3_paid_time_offs.rbs rename to sig/mindee/v1/product/resume/resume_v1_certificates.rbs index 0327fcae7..45abc7e41 100644 --- a/sig/mindee/product/fr/payslip/payslip_v3_paid_time_offs.rbs +++ b/sig/mindee/v1/product/resume/resume_v1_certificates.rbs @@ -1,12 +1,14 @@ # frozen_string_literal: true module Mindee - module Product - module FR - module Payslip - class PayslipV3PaidTimeOffs < Array[PayslipV3PaidTimeOff] + module V1 + module Product + module Resume + class ResumeV1Certificates < Array[ResumeV1Certificate] def initialize: (Array[untyped], Integer?) -> void + def self.line_items_separator: (String) -> String + def to_s: -> String end end diff --git a/sig/mindee/v1/product/resume/resume_v1_document.rbs b/sig/mindee/v1/product/resume/resume_v1_document.rbs new file mode 100644 index 000000000..6e95f93da --- /dev/null +++ b/sig/mindee/v1/product/resume/resume_v1_document.rbs @@ -0,0 +1,69 @@ +# lib/mindee/v1/product/resume/resume_v1_document.rb + +module Mindee + module V1 + module Product + module Resume + class ResumeV1Document < Parsing::Common::Prediction + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def address: -> (Parsing::Standard::StringField) + + def certificates: -> (Product::Resume::ResumeV1Certificates) + + def document_language: -> (Parsing::Standard::StringField) + + def document_type: -> (Parsing::Standard::ClassificationField) + + def education: -> (Product::Resume::ResumeV1Educations) + + def email_address: -> (Parsing::Standard::StringField) + + def given_names: -> (Array[Parsing::Standard::StringField]) + + def hard_skills: -> (Array[Parsing::Standard::StringField]) + + def job_applied: -> (Parsing::Standard::StringField) + + def languages: -> (Product::Resume::ResumeV1Languages) + + def nationality: -> (Parsing::Standard::StringField) + + def phone_number: -> (Parsing::Standard::StringField) + + def profession: -> (Parsing::Standard::StringField) + + def professional_experiences: -> (Product::Resume::ResumeV1ProfessionalExperiences) + + def social_networks_urls: -> (Product::Resume::ResumeV1SocialNetworksUrls) + + def soft_skills: -> (Array[Parsing::Standard::StringField]) + + def surnames: -> (Array[Parsing::Standard::StringField]) + + def social_networks_urls_separator: (String) -> String + + def social_networks_urls_to_s: -> String + + def languages_separator: (String) -> String + + def languages_to_s: -> String + + def education_separator: (String) -> String + + def education_to_s: -> String + + def professional_experiences_separator: (String) -> String + + def professional_experiences_to_s: -> String + + def certificates_separator: (String) -> String + + def certificates_to_s: -> String + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/product/resume/resume_v1_education.rbs b/sig/mindee/v1/product/resume/resume_v1_education.rbs new file mode 100644 index 000000000..c533ebd04 --- /dev/null +++ b/sig/mindee/v1/product/resume/resume_v1_education.rbs @@ -0,0 +1,33 @@ +module Mindee + module V1 + module Product + module Resume + class ResumeV1Education < Parsing::Standard::FeatureField + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def degree_domain: -> String + + def degree_type: -> String + + def end_month: -> String + + def end_year: -> String + + def school: -> String + + def start_month: -> String + + def start_year: -> String + + def printable_values: -> Hash[Symbol, String] + + def table_printable_values: -> Hash[String | Symbol, untyped] + + def to_table_line: -> String + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/product/fr/payslip/payslip_v3_salary_details.rbs b/sig/mindee/v1/product/resume/resume_v1_educations.rbs similarity index 66% rename from sig/mindee/product/fr/payslip/payslip_v3_salary_details.rbs rename to sig/mindee/v1/product/resume/resume_v1_educations.rbs index f3c6ce889..3d3459211 100644 --- a/sig/mindee/product/fr/payslip/payslip_v3_salary_details.rbs +++ b/sig/mindee/v1/product/resume/resume_v1_educations.rbs @@ -1,12 +1,14 @@ # frozen_string_literal: true module Mindee - module Product - module FR - module Payslip - class PayslipV3SalaryDetails < Array[PayslipV3SalaryDetail] + module V1 + module Product + module Resume + class ResumeV1Educations < Array[ResumeV1Education] def initialize: (Array[untyped], Integer?) -> void + def self.line_items_separator: (String) -> String + def to_s: -> String end end diff --git a/sig/mindee/v1/product/resume/resume_v1_language.rbs b/sig/mindee/v1/product/resume/resume_v1_language.rbs new file mode 100644 index 000000000..224d6359c --- /dev/null +++ b/sig/mindee/v1/product/resume/resume_v1_language.rbs @@ -0,0 +1,23 @@ +module Mindee + module V1 + module Product + module Resume + class ResumeV1Language < Parsing::Standard::FeatureField + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def language: -> String + + def level: -> String + + def printable_values: -> Hash[Symbol, String] + + def table_printable_values: -> Hash[String | Symbol, untyped] + + def to_table_line: -> String + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/product/us/us_mail/us_mail_v3_recipient_addresses.rbs b/sig/mindee/v1/product/resume/resume_v1_languages.rbs similarity index 65% rename from sig/mindee/product/us/us_mail/us_mail_v3_recipient_addresses.rbs rename to sig/mindee/v1/product/resume/resume_v1_languages.rbs index a18e339a4..e73b94ac2 100644 --- a/sig/mindee/product/us/us_mail/us_mail_v3_recipient_addresses.rbs +++ b/sig/mindee/v1/product/resume/resume_v1_languages.rbs @@ -1,12 +1,14 @@ # frozen_string_literal: true module Mindee - module Product - module US - module UsMail - class UsMailV3RecipientAddresses < Array[UsMailV3RecipientAddress] + module V1 + module Product + module Resume + class ResumeV1Languages < Array[ResumeV1Language] def initialize: (Array[untyped], Integer?) -> void + def self.line_items_separator: (String) -> String + def to_s: -> String end end diff --git a/sig/mindee/product/us/us_mail/us_mail_v3_page.rbs b/sig/mindee/v1/product/resume/resume_v1_page.rbs similarity index 53% rename from sig/mindee/product/us/us_mail/us_mail_v3_page.rbs rename to sig/mindee/v1/product/resume/resume_v1_page.rbs index 279eaa147..a30271498 100644 --- a/sig/mindee/product/us/us_mail/us_mail_v3_page.rbs +++ b/sig/mindee/v1/product/resume/resume_v1_page.rbs @@ -1,14 +1,16 @@ -# lib/mindee/product/../us_mail/us_mail_v3_page.rb +# lib/mindee/v1/product/resume/resume_v1_page.rb module Mindee - module Product - module US - module UsMail - class UsMailV3Page < Parsing::Common::Page + module V1 + module Product + module Resume + class ResumeV1Page < Parsing::Common::Page def initialize: (Hash[String | Symbol, untyped]) -> void end - class UsMailV3PagePrediction < UsMailV3Document + + class ResumeV1PagePrediction < ResumeV1Document def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + def to_s: -> String end end diff --git a/sig/mindee/v1/product/resume/resume_v1_professional_experience.rbs b/sig/mindee/v1/product/resume/resume_v1_professional_experience.rbs new file mode 100644 index 000000000..61910b5cf --- /dev/null +++ b/sig/mindee/v1/product/resume/resume_v1_professional_experience.rbs @@ -0,0 +1,37 @@ +module Mindee + module V1 + module Product + module Resume + class ResumeV1ProfessionalExperience < Parsing::Standard::FeatureField + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def contract_type: -> String + + def department: -> String + + def description: -> String + + def employer: -> String + + def end_month: -> String + + def end_year: -> String + + def role: -> String + + def start_month: -> String + + def start_year: -> String + + def printable_values: -> Hash[Symbol, String] + + def table_printable_values: -> Hash[String | Symbol, untyped] + + def to_table_line: -> String + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_subscriptions.rbs b/sig/mindee/v1/product/resume/resume_v1_professional_experiences.rbs similarity index 62% rename from sig/mindee/product/fr/energy_bill/energy_bill_v1_subscriptions.rbs rename to sig/mindee/v1/product/resume/resume_v1_professional_experiences.rbs index 054ddb118..3a4cac88d 100644 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_subscriptions.rbs +++ b/sig/mindee/v1/product/resume/resume_v1_professional_experiences.rbs @@ -1,12 +1,14 @@ # frozen_string_literal: true module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1Subscriptions < Array[EnergyBillV1Subscription] + module V1 + module Product + module Resume + class ResumeV1ProfessionalExperiences < Array[ResumeV1ProfessionalExperience] def initialize: (Array[untyped], Integer?) -> void + def self.line_items_separator: (String) -> String + def to_s: -> String end end diff --git a/sig/mindee/v1/product/resume/resume_v1_social_networks_url.rbs b/sig/mindee/v1/product/resume/resume_v1_social_networks_url.rbs new file mode 100644 index 000000000..c0889b5e0 --- /dev/null +++ b/sig/mindee/v1/product/resume/resume_v1_social_networks_url.rbs @@ -0,0 +1,23 @@ +module Mindee + module V1 + module Product + module Resume + class ResumeV1SocialNetworksUrl < Parsing::Standard::FeatureField + def initialize: (Hash[String | Symbol, untyped], Integer?) -> void + + def name: -> String + + def url: -> String + + def printable_values: -> Hash[Symbol, String] + + def table_printable_values: -> Hash[String | Symbol, untyped] + + def to_table_line: -> String + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_usages.rbs b/sig/mindee/v1/product/resume/resume_v1_social_networks_urls.rbs similarity index 64% rename from sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_usages.rbs rename to sig/mindee/v1/product/resume/resume_v1_social_networks_urls.rbs index 0a6a44602..8758c95a3 100644 --- a/sig/mindee/product/fr/energy_bill/energy_bill_v1_energy_usages.rbs +++ b/sig/mindee/v1/product/resume/resume_v1_social_networks_urls.rbs @@ -1,12 +1,14 @@ # frozen_string_literal: true module Mindee - module Product - module FR - module EnergyBill - class EnergyBillV1EnergyUsages < Array[EnergyBillV1EnergyUsage] + module V1 + module Product + module Resume + class ResumeV1SocialNetworksUrls < Array[ResumeV1SocialNetworksUrl] def initialize: (Array[untyped], Integer?) -> void + def self.line_items_separator: (String) -> String + def to_s: -> String end end diff --git a/sig/mindee/product/universal/universal.rbs b/sig/mindee/v1/product/universal/universal.rbs similarity index 78% rename from sig/mindee/product/universal/universal.rbs rename to sig/mindee/v1/product/universal/universal.rbs index 4371feccb..debc5eb2d 100644 --- a/sig/mindee/product/universal/universal.rbs +++ b/sig/mindee/v1/product/universal/universal.rbs @@ -1,6 +1,7 @@ -# lib/mindee/product/universal/universal.rb +# lib/mindee/v1/product/universal/universal.rb module Mindee - module Product + module V1 + module Product module Universal class Universal < Parsing::Common::Inference def initialize: (Hash[String | Symbol, untyped]) -> void @@ -9,6 +10,7 @@ module Mindee def has_async: -> bool def has_sync: -> bool end + end end end end diff --git a/sig/mindee/product/universal/universal_document.rbs b/sig/mindee/v1/product/universal/universal_document.rbs similarity index 65% rename from sig/mindee/product/universal/universal_document.rbs rename to sig/mindee/v1/product/universal/universal_document.rbs index a8a1d70fe..c3abb68d5 100644 --- a/sig/mindee/product/universal/universal_document.rbs +++ b/sig/mindee/v1/product/universal/universal_document.rbs @@ -1,10 +1,12 @@ -# lib/mindee/product/universal/universal_document.rb +# lib/mindee/v1/product/universal/universal_document.rb module Mindee - module Product + module V1 + module Product module Universal class UniversalDocument < Parsing::Common::Document def initialize: (Hash[String | Symbol, untyped]) -> void end + end end end end diff --git a/sig/mindee/v1/product/universal/universal_page.rbs b/sig/mindee/v1/product/universal/universal_page.rbs new file mode 100644 index 000000000..7527da7f5 --- /dev/null +++ b/sig/mindee/v1/product/universal/universal_page.rbs @@ -0,0 +1,18 @@ +# lib/mindee/v1/product/universal/universal_page.rb +module Mindee + module V1 + module Product + module Universal + class UniversalPage < Parsing::Common::Page + def initialize: (Hash[String | Symbol, untyped]) -> void + end + + class UniversalPagePrediction < UniversalPrediction + def initialize: (Hash[String | Symbol, untyped], ?nil) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v1/product/universal/universal_prediction.rbs b/sig/mindee/v1/product/universal/universal_prediction.rbs new file mode 100644 index 000000000..2ab3c7fe5 --- /dev/null +++ b/sig/mindee/v1/product/universal/universal_prediction.rbs @@ -0,0 +1,30 @@ +# lib/mindee/v1/product/universal/universal_prediction.rb +module Mindee + module V1 + module Product + module Universal + class UniversalPrediction < Parsing::Common::Prediction + def fields: -> Hash[String | Symbol, untyped] + + def initialize: (untyped?) -> void + + def to_s: -> String + + def generate_field_string: (String, Parsing::Universal::UniversalListField, Regexp) -> String + + def generate_list_field_string: (String, Hash[String | Symbol, untyped], Regexp) -> String + + def generate_sub_value_string: (String, Parsing::Universal::UniversalListField, Regexp) -> String + + def single_fields: -> Hash[String | Symbol, untyped] + + def list_fields: -> Hash[String | Symbol, Parsing::Universal::UniversalListField] + + def object_fields: -> Hash[String | Symbol, untyped] + + def list_field_names: -> Array[untyped] + end + end + end + end +end diff --git a/sig/mindee/v2/client.rbs b/sig/mindee/v2/client.rbs new file mode 100644 index 000000000..143e185fc --- /dev/null +++ b/sig/mindee/v2/client.rbs @@ -0,0 +1,29 @@ +# lib/mindee/v2/client.rb + +OTS_OWNER: String + +module Mindee + module V2 + class Client + private attr_reader mindee_api: V2::HTTP::MindeeApiV2 + + def logger: () -> Logger + + def initialize: (?api_key: String) -> void + + def get_result: [T] (HTTP::_ProductClass[T] product, String resource) -> T + + def get_job: (String job_id) -> V2::Parsing::JobResponse + + def enqueue: [T] (HTTP::_ProductClass[T] product, Input::Source::LocalInputSource | Input::Source::URLInputSource, Hash[String | Symbol, untyped] | Input::BaseParameters params) -> V2::Parsing::JobResponse + + def enqueue_and_get_result: [T] (HTTP::_ProductClass[T] product, Input::Source::LocalInputSource | Input::Source::URLInputSource, Hash[String | Symbol, untyped] | Input::BaseParameters params) -> T + + def search_models: (String?, String?) -> Mindee::V2::Parsing::Search::SearchResponse + + def validate_async_params: (Integer | Float, Integer | Float, Integer) -> void + + def normalize_parameters: (singleton(Input::BaseParameters) param_class, Hash[String | Symbol, untyped] | Input::BaseParameters params) -> Input::BaseParameters + end + end +end diff --git a/sig/mindee/v2/file_operation/crop.rbs b/sig/mindee/v2/file_operation/crop.rbs new file mode 100644 index 000000000..f10349df0 --- /dev/null +++ b/sig/mindee/v2/file_operation/crop.rbs @@ -0,0 +1,10 @@ +module Mindee + module V2 + module FileOperation + module Crop + def self.extract_single_crop: (Input::Source::LocalInputSource, Parsing::Field::FieldLocation) -> Image::ExtractedImage + def self.extract_crops: (Input::Source::LocalInputSource, Array[Product::Crop::CropItem]) -> CropFiles + end + end + end +end diff --git a/sig/mindee/v2/file_operation/crop_files.rbs b/sig/mindee/v2/file_operation/crop_files.rbs new file mode 100644 index 000000000..7994d94c9 --- /dev/null +++ b/sig/mindee/v2/file_operation/crop_files.rbs @@ -0,0 +1,9 @@ +module Mindee + module V2 + module FileOperation + class CropFiles < Array[Image::ExtractedImage] + def save_all_to_disk: (String | Pathname, ?prefix: String, ?file_format: String?) -> void + end + end + end +end diff --git a/sig/mindee/v2/file_operation/split.rbs b/sig/mindee/v2/file_operation/split.rbs new file mode 100644 index 000000000..5424c987d --- /dev/null +++ b/sig/mindee/v2/file_operation/split.rbs @@ -0,0 +1,11 @@ +module Mindee + module V2 + module FileOperation + module Split + def self.extract_single_split: (Input::Source::LocalInputSource, Array[Integer]) -> PDF::ExtractedPDF + + def self.extract_splits: (Input::Source::LocalInputSource, Array[Array[Integer]]) -> SplitFiles + end + end + end +end diff --git a/sig/mindee/v2/file_operation/split_files.rbs b/sig/mindee/v2/file_operation/split_files.rbs new file mode 100644 index 000000000..38a864575 --- /dev/null +++ b/sig/mindee/v2/file_operation/split_files.rbs @@ -0,0 +1,9 @@ +module Mindee + module V2 + module FileOperation + class SplitFiles < Array[PDF::ExtractedPDF] + def save_all_to_disk: (String | Pathname, ?prefix: String?) -> void + end + end + end +end diff --git a/sig/mindee/v2/http/api_v2_settings.rbs b/sig/mindee/v2/http/api_v2_settings.rbs new file mode 100644 index 000000000..e55580ae5 --- /dev/null +++ b/sig/mindee/v2/http/api_v2_settings.rbs @@ -0,0 +1,27 @@ +# lib/mindee/v2/http/api_v2_settings.rb +module Mindee + module V2 + module HTTP + class ApiV2Settings + MINDEE_V2_API_KEY_ENV_NAME: String + MINDEE_V2_API_KEY_DEFAULT: String? + MINDEE_V2_BASE_URL_ENV_NAME: String + MINDEE_V2_BASE_URL_DEFAULT: String + MINDEE_V2_REQUEST_TIMEOUT_ENV_NAME: String + MINDEE_V2_TIMEOUT_DEFAULT: Integer + USER_AGENT: String + + def logger: () -> Logger + + attr_reader api_key: String? + attr_reader base_url: String + attr_reader request_timeout: Integer + attr_reader user_agent: String + + def initialize: (?api_key: String?) -> void + + def check_api_key: -> void + end + end + end +end diff --git a/sig/mindee/v2/http/mindee_api_v2.rbs b/sig/mindee/v2/http/mindee_api_v2.rbs new file mode 100644 index 000000000..9cbbfe719 --- /dev/null +++ b/sig/mindee/v2/http/mindee_api_v2.rbs @@ -0,0 +1,52 @@ +# lib/mindee/v2/http/mindee_api_v2.rbs +module Mindee + module V2 + module HTTP + interface _ResponseFactory[T] + def new: (Hash[String | Symbol, untyped]) -> T + end + + interface _ProductClass[T] + def slug: () -> String + + def response_type: () -> _ResponseFactory[T] + + def params_type: () -> singleton(Input::BaseParameters) + end + + class MindeeApiV2 + attr_reader settings: ApiV2Settings + + def initialize: (?api_key: String?) -> void + + def req_get_result: [T] (_ProductClass[T] product, String resource) -> T + + def req_post_enqueue: (Input::Source::LocalInputSource | Input::Source::URLInputSource, Input::BaseParameters) -> V2::Parsing::JobResponse + + def req_get_job: (String) -> V2::Parsing::JobResponse + + def process_response: (Net::HTTPResponse?) -> Hash[String | Symbol, untyped] + + def poll: (String) -> Net::HTTPResponse + + def result_req_get: [T] (String, _ProductClass[T] product) -> Net::HTTPResponse + + def enqueue: (Input::Source::LocalInputSource | Input::Source::URLInputSource, Input::BaseParameters) -> Net::HTTPResponse? + + def search_models: (String?, String?) -> Mindee::V2::Parsing::Search::SearchResponse + + private + + def enqueue_form_options: (Array[Array[untyped]], V2::Product::Extraction::Params::ExtractionParameters) -> Array[Array[untyped]] + + def req_get_job_url: (String) -> V2::Parsing::JobResponse + + def req_get_result_url: [T] (_ResponseFactory[T] result_class, String url) -> T + + def req_get_search_models: (String?, String?) -> Net::HTTPResponse + + def uri?: (String) -> bool + end + end + end +end diff --git a/sig/mindee/v2/parsing/base_inference.rbs b/sig/mindee/v2/parsing/base_inference.rbs index 4f6b03968..b9ddd9e25 100644 --- a/sig/mindee/v2/parsing/base_inference.rbs +++ b/sig/mindee/v2/parsing/base_inference.rbs @@ -4,10 +4,10 @@ module Mindee module V2 module Parsing class BaseInference - attr_reader job: Mindee::Parsing::V2::InferenceJob - attr_reader file: Mindee::Parsing::V2::InferenceFile + attr_reader job: Mindee::V2::Parsing::InferenceJob + attr_reader file: Mindee::V2::Parsing::InferenceFile attr_reader id: String - attr_reader model: Mindee::Parsing::V2::InferenceModel + attr_reader model: Mindee::V2::Parsing::InferenceModel def initialize: (Hash[String | Symbol, untyped]) -> void diff --git a/sig/mindee/v2/parsing/base_response.rbs b/sig/mindee/v2/parsing/base_response.rbs index 8d1c7814c..803afaf20 100644 --- a/sig/mindee/v2/parsing/base_response.rbs +++ b/sig/mindee/v2/parsing/base_response.rbs @@ -3,7 +3,7 @@ module Mindee module V2 module Parsing - class BaseResponse[T] < Mindee::Parsing::V2::CommonResponse + class BaseResponse[T] < Mindee::V2::Parsing::CommonResponse attr_reader inference: T end end diff --git a/sig/mindee/v2/parsing/common_response.rbs b/sig/mindee/v2/parsing/common_response.rbs new file mode 100644 index 000000000..abf94f0b5 --- /dev/null +++ b/sig/mindee/v2/parsing/common_response.rbs @@ -0,0 +1,12 @@ +# lib/mindee/v2/parsing/common_response.rb +module Mindee + module V2 + module Parsing + class CommonResponse + attr_reader raw_http: String + + def initialize: (Hash[String | Symbol, untyped]) -> void + end + end + end +end diff --git a/sig/mindee/v2/parsing/error_item.rbs b/sig/mindee/v2/parsing/error_item.rbs new file mode 100644 index 000000000..46bf17432 --- /dev/null +++ b/sig/mindee/v2/parsing/error_item.rbs @@ -0,0 +1,13 @@ +# lib/mindee/v2/parsing/error_item.rb +module Mindee + module V2 + module Parsing + class ErrorItem + attr_reader pointer: String + attr_reader detail: String | nil + + def initialize: (Hash[String | Symbol, untyped]) -> void + end + end + end +end diff --git a/sig/mindee/parsing/v2/error_response.rbs b/sig/mindee/v2/parsing/error_response.rbs similarity index 84% rename from sig/mindee/parsing/v2/error_response.rbs rename to sig/mindee/v2/parsing/error_response.rbs index 7c0fdf55a..9fb9fd0e7 100644 --- a/sig/mindee/parsing/v2/error_response.rbs +++ b/sig/mindee/v2/parsing/error_response.rbs @@ -1,13 +1,14 @@ -# lib/mindee/parsing/v2/error_response.rb +# lib/mindee/v2/parsing/error_response.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing class ErrorResponse attr_reader detail: String attr_reader status: Integer attr_reader code: String attr_reader title: String attr_reader errors: Array[ErrorItem] + def initialize: (Hash[String | Symbol, untyped]) -> void def as_hash: -> Hash[Symbol, String | Integer] diff --git a/sig/mindee/parsing/v2/field/base_field.rbs b/sig/mindee/v2/parsing/field/base_field.rbs similarity index 85% rename from sig/mindee/parsing/v2/field/base_field.rbs rename to sig/mindee/v2/parsing/field/base_field.rbs index 5c401ab1a..b05002072 100644 --- a/sig/mindee/parsing/v2/field/base_field.rbs +++ b/sig/mindee/v2/parsing/field/base_field.rbs @@ -1,7 +1,7 @@ -# lib/mindee/parsing/v2/field/base_field.rb +# lib/mindee/v2/parsing/field/base_field.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field class BaseField attr_reader indent_level: Integer diff --git a/sig/mindee/parsing/v2/field/field_confidence.rbs b/sig/mindee/v2/parsing/field/field_confidence.rbs similarity index 91% rename from sig/mindee/parsing/v2/field/field_confidence.rbs rename to sig/mindee/v2/parsing/field/field_confidence.rbs index 77ca6b682..e1c72817a 100644 --- a/sig/mindee/parsing/v2/field/field_confidence.rbs +++ b/sig/mindee/v2/parsing/field/field_confidence.rbs @@ -1,7 +1,7 @@ -# lib/mindee/parsing/v2/field/field_confidence.rb +# lib/mindee/v2/parsing/field/field_confidence.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field class FieldConfidence attr_reader value: String diff --git a/sig/mindee/parsing/v2/field/field_location.rbs b/sig/mindee/v2/parsing/field/field_location.rbs similarity index 78% rename from sig/mindee/parsing/v2/field/field_location.rbs rename to sig/mindee/v2/parsing/field/field_location.rbs index 0c400ee08..d8cb365cc 100644 --- a/sig/mindee/parsing/v2/field/field_location.rbs +++ b/sig/mindee/v2/parsing/field/field_location.rbs @@ -1,7 +1,7 @@ -# lib/mindee/parsing/v2/field/field_location.rb +# lib/mindee/v2/parsing/field/field_location.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field class FieldLocation attr_reader page: Integer diff --git a/sig/mindee/parsing/v2/field/inference_fields.rbs b/sig/mindee/v2/parsing/field/inference_fields.rbs similarity index 87% rename from sig/mindee/parsing/v2/field/inference_fields.rbs rename to sig/mindee/v2/parsing/field/inference_fields.rbs index 203f06aaa..4c29c6123 100644 --- a/sig/mindee/parsing/v2/field/inference_fields.rbs +++ b/sig/mindee/v2/parsing/field/inference_fields.rbs @@ -1,7 +1,7 @@ -# lib/mindee/parsing/v2/field/inference_fields.rb +# lib/mindee/v2/parsing/field/inference_fields.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field class InferenceFields < Hash[String, ListField | ObjectField | SimpleField?] attr_reader indent_level: Integer diff --git a/sig/mindee/parsing/v2/field/list_field.rbs b/sig/mindee/v2/parsing/field/list_field.rbs similarity index 89% rename from sig/mindee/parsing/v2/field/list_field.rbs rename to sig/mindee/v2/parsing/field/list_field.rbs index 1f0295dab..ff17adc83 100644 --- a/sig/mindee/parsing/v2/field/list_field.rbs +++ b/sig/mindee/v2/parsing/field/list_field.rbs @@ -1,7 +1,7 @@ -# lib/mindee/parsing/v2/field/list_field.rb +# lib/mindee/v2/parsing/field/list_field.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field class ListField < BaseField include Enumerable[BaseField] diff --git a/sig/mindee/parsing/v2/field/object_field.rbs b/sig/mindee/v2/parsing/field/object_field.rbs similarity index 91% rename from sig/mindee/parsing/v2/field/object_field.rbs rename to sig/mindee/v2/parsing/field/object_field.rbs index 149dd23cd..1aa3557aa 100644 --- a/sig/mindee/parsing/v2/field/object_field.rbs +++ b/sig/mindee/v2/parsing/field/object_field.rbs @@ -1,7 +1,7 @@ -# lib/mindee/parsing/v2/field/object_field.rb +# lib/mindee/v2/parsing/field/object_field.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field # A field containing a nested set of inference fields. class ObjectField < BaseField diff --git a/sig/mindee/parsing/v2/field/simple_field.rbs b/sig/mindee/v2/parsing/field/simple_field.rbs similarity index 81% rename from sig/mindee/parsing/v2/field/simple_field.rbs rename to sig/mindee/v2/parsing/field/simple_field.rbs index facf0b121..b0a35b29e 100644 --- a/sig/mindee/parsing/v2/field/simple_field.rbs +++ b/sig/mindee/v2/parsing/field/simple_field.rbs @@ -1,7 +1,7 @@ -# lib/mindee/parsing/v2/field/simple_field.rb +# lib/mindee/v2/parsing/field/simple_field.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing module Field class SimpleField < BaseField attr_reader value: String | Integer | Float | bool | nil diff --git a/sig/mindee/parsing/v2/inference_active_options.rbs b/sig/mindee/v2/parsing/inference_active_options.rbs similarity index 83% rename from sig/mindee/parsing/v2/inference_active_options.rbs rename to sig/mindee/v2/parsing/inference_active_options.rbs index f0cc0296e..0a4ff0591 100644 --- a/sig/mindee/parsing/v2/inference_active_options.rbs +++ b/sig/mindee/v2/parsing/inference_active_options.rbs @@ -1,12 +1,14 @@ module Mindee - module Parsing - module V2 + module V2 + module Parsing class DataSchemaActiveOption attr_reader replace: bool - def initialize: (Hash[Symbol |string, untyped]) -> void + def initialize: (Hash[Symbol | string, untyped]) -> void + def to_s: () -> String end + class InferenceActiveOptions attr_reader confidence: bool attr_reader polygon: bool @@ -16,6 +18,7 @@ module Mindee attr_reader data_schema: DataSchemaActiveOption def initialize: (Hash[String | Symbol, untyped]) -> void + def to_s: () -> String end end diff --git a/sig/mindee/parsing/v2/inference_file.rbs b/sig/mindee/v2/parsing/inference_file.rbs similarity index 80% rename from sig/mindee/parsing/v2/inference_file.rbs rename to sig/mindee/v2/parsing/inference_file.rbs index 43e313115..310392d59 100644 --- a/sig/mindee/parsing/v2/inference_file.rbs +++ b/sig/mindee/v2/parsing/inference_file.rbs @@ -1,13 +1,15 @@ -# lib/mindee/parsing/v2/inference_file.rb +# lib/mindee/v2/parsing/inference_file.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing class InferenceFile attr_reader name: String attr_reader file_alias: String? attr_reader page_count: Integer attr_reader mime_type: String + def initialize: (Hash[String | Symbol, untyped]) -> void + def to_s: -> String end end diff --git a/sig/mindee/parsing/v2/inference_job.rbs b/sig/mindee/v2/parsing/inference_job.rbs similarity index 85% rename from sig/mindee/parsing/v2/inference_job.rbs rename to sig/mindee/v2/parsing/inference_job.rbs index 029576818..ab58a7381 100644 --- a/sig/mindee/parsing/v2/inference_job.rbs +++ b/sig/mindee/v2/parsing/inference_job.rbs @@ -1,10 +1,11 @@ module Mindee - module Parsing - module V2 + module V2 + module Parsing class InferenceJob attr_reader id: String def initialize: (Hash[String | Symbol, untyped]) -> void + def to_s: -> String end end diff --git a/sig/mindee/parsing/v2/inference_model.rbs b/sig/mindee/v2/parsing/inference_model.rbs similarity index 68% rename from sig/mindee/parsing/v2/inference_model.rbs rename to sig/mindee/v2/parsing/inference_model.rbs index 07a9be237..aab50b775 100644 --- a/sig/mindee/parsing/v2/inference_model.rbs +++ b/sig/mindee/v2/parsing/inference_model.rbs @@ -1,9 +1,10 @@ -# lib/mindee/parsing/v2/inference_model.rb +# lib/mindee/v2/parsing/inference_model.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing class InferenceModel attr_reader id: String + def initialize: (Hash[String | Symbol, untyped]) -> void end end diff --git a/sig/mindee/parsing/v2/job.rbs b/sig/mindee/v2/parsing/job.rbs similarity index 90% rename from sig/mindee/parsing/v2/job.rbs rename to sig/mindee/v2/parsing/job.rbs index 1b60d013f..9e8656885 100644 --- a/sig/mindee/parsing/v2/job.rbs +++ b/sig/mindee/v2/parsing/job.rbs @@ -1,7 +1,7 @@ -# lib/mindee/parsing/v2/job.rb +# lib/mindee/v2/parsing/job.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing class Job attr_reader alias: String attr_reader created_at: Time @@ -16,6 +16,7 @@ module Mindee attr_reader webhooks: Array[JobWebhook] def initialize: (Hash[String | Symbol, untyped]) -> void + def to_s: -> String end end diff --git a/sig/mindee/parsing/v2/job_response.rbs b/sig/mindee/v2/parsing/job_response.rbs similarity index 73% rename from sig/mindee/parsing/v2/job_response.rbs rename to sig/mindee/v2/parsing/job_response.rbs index 1ecf8683a..eceb631b3 100644 --- a/sig/mindee/parsing/v2/job_response.rbs +++ b/sig/mindee/v2/parsing/job_response.rbs @@ -1,10 +1,12 @@ -# lib/mindee/parsing/v2/job_response.rb +# lib/mindee/v2/parsing/job_response.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing class JobResponse < CommonResponse attr_reader job: Job + def initialize: (Hash[String | Symbol, untyped]) -> void + def to_s: -> String end end diff --git a/sig/mindee/parsing/v2/job_webhook.rbs b/sig/mindee/v2/parsing/job_webhook.rbs similarity index 83% rename from sig/mindee/parsing/v2/job_webhook.rbs rename to sig/mindee/v2/parsing/job_webhook.rbs index 5d9ea9201..9ccb02f8c 100644 --- a/sig/mindee/parsing/v2/job_webhook.rbs +++ b/sig/mindee/v2/parsing/job_webhook.rbs @@ -1,7 +1,7 @@ -# lib/mindee/parsing/v2/job_webhook.rb +# lib/mindee/v2/parsing/job_webhook.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing class JobWebhook attr_reader created_at: DateTime? attr_reader error: ErrorResponse? @@ -9,7 +9,9 @@ module Mindee attr_reader status: String def initialize: (Hash[String | Symbol, untyped]) -> void + def to_s: -> String + def parse_date: (String?) -> DateTime? end end diff --git a/sig/mindee/parsing/v2/rag_metadata.rbs b/sig/mindee/v2/parsing/rag_metadata.rbs similarity index 72% rename from sig/mindee/parsing/v2/rag_metadata.rbs rename to sig/mindee/v2/parsing/rag_metadata.rbs index 2995de66e..bbb6c70ca 100644 --- a/sig/mindee/parsing/v2/rag_metadata.rbs +++ b/sig/mindee/v2/parsing/rag_metadata.rbs @@ -1,8 +1,8 @@ -# lib/mindee/parsing/v2/rag_metadata.rb +# lib/mindee/v2/parsing/rag_metadata.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing class RAGMetadata attr_accessor retrieved_document_id: string | nil diff --git a/sig/mindee/parsing/v2/raw_text.rbs b/sig/mindee/v2/parsing/raw_text.rbs similarity index 72% rename from sig/mindee/parsing/v2/raw_text.rbs rename to sig/mindee/v2/parsing/raw_text.rbs index b5959005c..a8e0a9f73 100644 --- a/sig/mindee/parsing/v2/raw_text.rbs +++ b/sig/mindee/v2/parsing/raw_text.rbs @@ -1,7 +1,7 @@ -# lib/mindee/parsing/v2/raw_text.rb +# lib/mindee/v2/parsing/raw_text.rb module Mindee - module Parsing - module V2 + module V2 + module Parsing class RawText attr_reader pages: Array[RawTextPage] diff --git a/sig/mindee/parsing/v2/raw_text_page.rbs b/sig/mindee/v2/parsing/raw_text_page.rbs similarity index 84% rename from sig/mindee/parsing/v2/raw_text_page.rbs rename to sig/mindee/v2/parsing/raw_text_page.rbs index 536d2c484..ce87f51c9 100644 --- a/sig/mindee/parsing/v2/raw_text_page.rbs +++ b/sig/mindee/v2/parsing/raw_text_page.rbs @@ -1,6 +1,6 @@ module Mindee - module Parsing - module V2 + module V2 + module Parsing class RawTextPage attr_reader content: String diff --git a/sig/mindee/v2/parsing/search/pagination_metadata.rbs b/sig/mindee/v2/parsing/search/pagination_metadata.rbs new file mode 100644 index 000000000..5c43bb624 --- /dev/null +++ b/sig/mindee/v2/parsing/search/pagination_metadata.rbs @@ -0,0 +1,20 @@ +# lib/mindee/v2/parsing/search/pagination_metadata.rbs + +module Mindee + module V2 + module Parsing + module Search + class PaginationMetadata + attr_reader page: Integer + attr_reader per_page: Integer + attr_reader total_items: Integer + attr_reader total_pages: Integer + + def initialize: (Hash[String|Symbol, untyped]) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v2/parsing/search/search_model.rbs b/sig/mindee/v2/parsing/search/search_model.rbs new file mode 100644 index 000000000..e0c02de63 --- /dev/null +++ b/sig/mindee/v2/parsing/search/search_model.rbs @@ -0,0 +1,19 @@ +# lib/mindee/v2/parsing/search/search_model.rb + +module Mindee + module V2 + module Parsing + module Search + class SearchModel + attr_reader id: String + attr_reader model_type: String + attr_reader name: String + + def initialize: (Hash[String|Symbol, untyped]) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v2/parsing/search/search_response.rbs b/sig/mindee/v2/parsing/search/search_response.rbs new file mode 100644 index 000000000..14c0bfdae --- /dev/null +++ b/sig/mindee/v2/parsing/search/search_response.rbs @@ -0,0 +1,17 @@ +# lib/mindee/v2/search/search_response.rb +module Mindee + module V2 + module Parsing + module Search + class SearchResponse + attr_reader models: Array[SearchResponse] + attr_reader pagination_metadata: PaginationMetadata + + def initialize: (Hash[String|Symbol, untyped]) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v2/parsing/search_models.rbs b/sig/mindee/v2/parsing/search_models.rbs new file mode 100644 index 000000000..ba9d391e4 --- /dev/null +++ b/sig/mindee/v2/parsing/search_models.rbs @@ -0,0 +1,14 @@ +# lib/mindee/v2/parsing/search/search_models.rb +module Mindee + module V2 + module Parsing + module Search + class SearchModels < Array[SearchModel] + def initialize: (Array[untyped]) -> void + + def to_s: -> String + end + end + end + end +end diff --git a/sig/mindee/v2/product/classification/classification_response.rbs b/sig/mindee/v2/product/classification/classification_response.rbs index ee34fbc12..6e43050cd 100644 --- a/sig/mindee/v2/product/classification/classification_response.rbs +++ b/sig/mindee/v2/product/classification/classification_response.rbs @@ -4,7 +4,7 @@ module Mindee module V2 module Product module Classification - class ClassificationResponse + class ClassificationResponse < Parsing::BaseResponse[ClassificationInference] self.@slug: String self.@_params_type: singleton(Params::ClassificationParameters) diff --git a/sig/mindee/v2/product/crop/crop_item.rbs b/sig/mindee/v2/product/crop/crop_item.rbs index 1e3e79986..b87efc6d4 100644 --- a/sig/mindee/v2/product/crop/crop_item.rbs +++ b/sig/mindee/v2/product/crop/crop_item.rbs @@ -4,9 +4,12 @@ module Mindee module Crop class CropItem attr_reader object_type: String - attr_reader location: Mindee::Parsing::V2::Field::FieldLocation + attr_reader location: Mindee::V2::Parsing::Field::FieldLocation def initialize: (Hash[String | Symbol, untyped]) -> void + + def extract_from_file: (Input::Source::LocalInputSource) -> Image::ExtractedImage + def to_s: -> String end end diff --git a/sig/mindee/v2/product/crop/crop_response.rbs b/sig/mindee/v2/product/crop/crop_response.rbs index 4b0c638f7..7ebadb1a1 100644 --- a/sig/mindee/v2/product/crop/crop_response.rbs +++ b/sig/mindee/v2/product/crop/crop_response.rbs @@ -4,7 +4,7 @@ module Mindee module V2 module Product module Crop - class CropResponse + class CropResponse < Parsing::BaseResponse[CropInference] self.@slug: String self.@_params_type: singleton(Params::CropParameters) @@ -13,6 +13,8 @@ module Mindee def _params_type: -> singleton(Params::CropParameters) + def extract_from_file: (Input::Source::LocalInputSource) -> FileOperation::CropFiles + def to_s: -> String def self._params_type: () -> singleton(Params::CropParameters) def self.slug: () -> String diff --git a/sig/mindee/v2/product/extraction/extraction.rbs b/sig/mindee/v2/product/extraction/extraction.rbs index c747c7b8d..197a5f7e5 100644 --- a/sig/mindee/v2/product/extraction/extraction.rbs +++ b/sig/mindee/v2/product/extraction/extraction.rbs @@ -1,3 +1,5 @@ +# lib/mindee/v2/product/extraction/extraction.rb + module Mindee module V2 module Product @@ -5,6 +7,7 @@ module Mindee class Extraction self.@params_type: singleton(Mindee::V2::Product::Extraction::Params::ExtractionParameters) self.@response_type: singleton(Mindee::V2::Product::Extraction::ExtractionResponse) + self.@slug: String end end end diff --git a/sig/mindee/v2/product/extraction/extraction_inference.rbs b/sig/mindee/v2/product/extraction/extraction_inference.rbs index ffefa44bf..2facf4f77 100644 --- a/sig/mindee/v2/product/extraction/extraction_inference.rbs +++ b/sig/mindee/v2/product/extraction/extraction_inference.rbs @@ -3,6 +3,11 @@ module Mindee module Product module Extraction class ExtractionInference + attr_reader self.params_type: singleton(Params::ExtractionParameters) + attr_reader self.response_type: singleton(ExtractionResponse) + attr_reader self.slug: String + + attr_reader active_options: Mindee::V2::Parsing::InferenceActiveOptions attr_reader result: ExtractionResult def initialize: (Hash[String | Symbol, untyped]) -> void diff --git a/sig/mindee/v2/product/extraction/extraction_response.rbs b/sig/mindee/v2/product/extraction/extraction_response.rbs index 000d7f822..0b5cec064 100644 --- a/sig/mindee/v2/product/extraction/extraction_response.rbs +++ b/sig/mindee/v2/product/extraction/extraction_response.rbs @@ -1,16 +1,22 @@ +# lib/mindee/v2/product/extraction/extraction_response.rb + module Mindee module V2 module Product module Extraction - class ExtractionResponse + class ExtractionResponse < Parsing::BaseResponse[ExtractionInference] self.@_params_type: singleton(Params::ExtractionParameters) - attr_reader inference: Mindee::V2::Product::Extraction::ExtractionInference + self.@slug: String + + attr_reader inference: ExtractionInference def initialize: (Hash[String | Symbol, untyped]) -> void def _params_type: -> singleton(Params::ExtractionParameters) def self._params_type: () -> singleton(Params::ExtractionParameters) + + def to_s: -> String end end end diff --git a/sig/mindee/v2/product/extraction/extraction_result.rbs b/sig/mindee/v2/product/extraction/extraction_result.rbs index 975d364c1..c8e0ea00d 100644 --- a/sig/mindee/v2/product/extraction/extraction_result.rbs +++ b/sig/mindee/v2/product/extraction/extraction_result.rbs @@ -1,8 +1,16 @@ +# lib/mindee/v2/product/extraction/extraction_result.rb + module Mindee module V2 module Product module Extraction - class ExtractionResult < Mindee::Parsing::V2::InferenceResult + class ExtractionResult + attr_reader fields: Parsing::Field::InferenceFields + attr_reader raw_text: Parsing::RawText? + attr_reader rag: Parsing::RAGMetadata? + + def initialize: (Hash[String | Symbol, untyped]) -> void + def to_s: -> String end end end diff --git a/sig/mindee/v2/product/extraction/params/data_schema.rbs b/sig/mindee/v2/product/extraction/params/data_schema.rbs new file mode 100644 index 000000000..7511ad128 --- /dev/null +++ b/sig/mindee/v2/product/extraction/params/data_schema.rbs @@ -0,0 +1,21 @@ +# lib/mindee/v2/product/extraction/params/data_schema.rb + +module Mindee + module V2 + module Product + module Extraction + module Params + class DataSchema + attr_reader replace: DataSchemaReplace + + def initialize: (Hash[String | Symbol, untyped] | String | DataSchema) -> void + + def to_hash: () -> Hash[Symbol, untyped] + + def to_s: -> String + end + end + end + end + end +end diff --git a/sig/mindee/v2/product/extraction/params/data_schema_field.rbs b/sig/mindee/v2/product/extraction/params/data_schema_field.rbs new file mode 100644 index 000000000..95a363285 --- /dev/null +++ b/sig/mindee/v2/product/extraction/params/data_schema_field.rbs @@ -0,0 +1,29 @@ +# lib/mindee/v2/product/extraction/params/data_schema_field.rb + +module Mindee + module V2 + module Product + module Extraction + module Params + class DataSchemaField + attr_reader title: String + attr_reader name: String + attr_reader is_array: bool + attr_reader type: String + attr_reader classification_values: String | nil + attr_reader unique_values: bool | nil + attr_reader description: String | nil + attr_reader guidelines: String | nil + attr_reader nested_fields: Array[Hash[String | Symbol, untyped]] | nil + + def initialize: (Hash[Symbol, untyped]) -> void + + def to_hash: () -> Hash[Symbol, untyped] + + def to_string: () -> String + end + end + end + end + end +end diff --git a/sig/mindee/v2/product/extraction/params/data_schema_replace.rbs b/sig/mindee/v2/product/extraction/params/data_schema_replace.rbs new file mode 100644 index 000000000..9dae8dc7d --- /dev/null +++ b/sig/mindee/v2/product/extraction/params/data_schema_replace.rbs @@ -0,0 +1,21 @@ +# lib/mindee/v2/product/extraction/params/data_schema_replace.rb + +module Mindee + module V2 + module Product + module Extraction + module Params + class DataSchemaReplace + attr_reader fields: Array[DataSchemaField] + + def initialize: (Hash[Symbol, untyped]) -> void + + def to_hash: () -> Hash[Symbol, untyped] + + def to_string: () -> String + end + end + end + end + end +end diff --git a/sig/mindee/v2/product/extraction/params/extraction_parameters.rbs b/sig/mindee/v2/product/extraction/params/extraction_parameters.rbs index f93bcdaec..79eb23878 100644 --- a/sig/mindee/v2/product/extraction/params/extraction_parameters.rbs +++ b/sig/mindee/v2/product/extraction/params/extraction_parameters.rbs @@ -3,7 +3,33 @@ module Mindee module Product module Extraction module Params - class ExtractionParameters < Input::InferenceParameters + class ExtractionParameters < Input::BaseParameters + + def self.slug: -> String + + attr_reader confidence: bool? + attr_reader polygon: bool? + attr_reader rag: bool? + attr_reader raw_text: bool? + attr_reader text_context: String? + attr_reader data_schema: V2::Product::Extraction::Params::DataSchema? + + def initialize: ( + String, + ?rag: bool?, + ?raw_text: bool?, + ?polygon: bool?, + ?confidence: bool?, + ?file_alias: String?, + ?text_context: String?, + ?webhook_ids: Array[String]?, + ?polling_options: Hash[Symbol | String, untyped] | Input::PollingOptions?, + ?close_file: bool?, + ?data_schema: V2::Product::Extraction::Params::DataSchema|String|Hash[Symbol | String, untyped]? + ) -> void + + def self.from_hash: (params: Hash[String | Symbol, untyped]) -> ExtractionParameters + def append_form_data: (Array[Array[untyped]]) -> Array[Array[untyped]] end end end diff --git a/sig/mindee/v2/product/ocr/ocr.rbs b/sig/mindee/v2/product/ocr/ocr.rbs index 9bbc96d01..2abff6d91 100644 --- a/sig/mindee/v2/product/ocr/ocr.rbs +++ b/sig/mindee/v2/product/ocr/ocr.rbs @@ -1,8 +1,8 @@ module Mindee module V2 module Product - module Ocr - class Ocr < BaseProduct + module OCR + class OCR < BaseProduct end end end diff --git a/sig/mindee/v2/product/ocr/ocr_inference.rbs b/sig/mindee/v2/product/ocr/ocr_inference.rbs index 029aa6fbb..af2891535 100644 --- a/sig/mindee/v2/product/ocr/ocr_inference.rbs +++ b/sig/mindee/v2/product/ocr/ocr_inference.rbs @@ -1,9 +1,9 @@ module Mindee module V2 module Product - module Ocr - class OcrInference - attr_reader result: OcrResult + module OCR + class OCRInference + attr_reader result: OCRResult def initialize: (Hash[String | Symbol, untyped]) -> void def to_s: -> String diff --git a/sig/mindee/v2/product/ocr/ocr_page.rbs b/sig/mindee/v2/product/ocr/ocr_page.rbs index 11cd96011..d94029752 100644 --- a/sig/mindee/v2/product/ocr/ocr_page.rbs +++ b/sig/mindee/v2/product/ocr/ocr_page.rbs @@ -1,9 +1,9 @@ module Mindee module V2 module Product - module Ocr - class OcrPage - attr_reader words: Array[OcrWord] + module OCR + class OCRPage + attr_reader words: Array[OCRWord] attr_reader content: String def initialize: (Hash[String | Symbol, untyped]) -> void diff --git a/sig/mindee/v2/product/ocr/ocr_response.rbs b/sig/mindee/v2/product/ocr/ocr_response.rbs index 609aef0e2..8f713b5b2 100644 --- a/sig/mindee/v2/product/ocr/ocr_response.rbs +++ b/sig/mindee/v2/product/ocr/ocr_response.rbs @@ -3,18 +3,18 @@ module Mindee module V2 module Product - module Ocr - class OcrResponse + module OCR + class OCRResponse < Parsing::BaseResponse[OCRInference] self.@slug: String - self.@_params_type: singleton(Params::OcrParameters) + self.@_params_type: singleton(Params::OCRParameters) - attr_reader inference: Mindee::V2::Product::Ocr::OcrInference + attr_reader inference: Mindee::V2::Product::OCR::OCRInference def initialize: (Hash[String | Symbol, untyped]) -> void - def _params_type: -> singleton(Params::OcrParameters) + def _params_type: -> singleton(Params::OCRParameters) def to_s: -> String - def self._params_type: () -> singleton(Params::OcrParameters) + def self._params_type: () -> singleton(Params::OCRParameters) def self.slug: () -> String end end diff --git a/sig/mindee/v2/product/ocr/ocr_result.rbs b/sig/mindee/v2/product/ocr/ocr_result.rbs index c35b0d73f..dc7fcc42a 100644 --- a/sig/mindee/v2/product/ocr/ocr_result.rbs +++ b/sig/mindee/v2/product/ocr/ocr_result.rbs @@ -1,9 +1,9 @@ module Mindee module V2 module Product - module Ocr - class OcrResult - attr_reader pages: Array[Mindee::V2::Product::Ocr::OcrPage] + module OCR + class OCRResult + attr_reader pages: Array[Mindee::V2::Product::OCR::OCRPage] def initialize: (Hash[String | Symbol, untyped]) -> void def to_s: -> String diff --git a/sig/mindee/v2/product/ocr/ocr_word.rbs b/sig/mindee/v2/product/ocr/ocr_word.rbs index 2d9967fb6..0fba61dc2 100644 --- a/sig/mindee/v2/product/ocr/ocr_word.rbs +++ b/sig/mindee/v2/product/ocr/ocr_word.rbs @@ -1,8 +1,8 @@ module Mindee module V2 module Product - module Ocr - class OcrWord + module OCR + class OCRWord attr_reader content: String attr_reader polygon: Geometry::Polygon diff --git a/sig/mindee/v2/product/ocr/params/ocr_parameters/ocr_parameters.rbs b/sig/mindee/v2/product/ocr/params/ocr_parameters/ocr_parameters.rbs index 731720822..a2df6f1ad 100644 --- a/sig/mindee/v2/product/ocr/params/ocr_parameters/ocr_parameters.rbs +++ b/sig/mindee/v2/product/ocr/params/ocr_parameters/ocr_parameters.rbs @@ -1,12 +1,12 @@ module Mindee module V2 module Product - module Ocr + module OCR module Params - class OcrParameters + class OCRParameters def self.slug: -> String - def self.from_hash: (params: Hash[String | Symbol, untyped]) -> OcrParameters + def self.from_hash: (params: Hash[String | Symbol, untyped]) -> OCRParameters def initialize: ( String, diff --git a/sig/mindee/v2/product/split/split_range.rbs b/sig/mindee/v2/product/split/split_range.rbs index 14a390efc..7ec193c55 100644 --- a/sig/mindee/v2/product/split/split_range.rbs +++ b/sig/mindee/v2/product/split/split_range.rbs @@ -3,10 +3,13 @@ module Mindee module Product module Split class SplitRange - attr_reader page_range: Array[int] + attr_reader page_range: Array[Integer] attr_reader document_type: String def initialize: (Hash[String | Symbol, untyped]) -> void + + def extract_from_file: (Input::Source::LocalInputSource) -> PDF::ExtractedPDF + def to_s: -> String end end diff --git a/sig/mindee/v2/product/split/split_response.rbs b/sig/mindee/v2/product/split/split_response.rbs index 9068eeb57..bd04c9696 100644 --- a/sig/mindee/v2/product/split/split_response.rbs +++ b/sig/mindee/v2/product/split/split_response.rbs @@ -4,7 +4,7 @@ module Mindee module V2 module Product module Split - class SplitResponse + class SplitResponse < Parsing::BaseResponse[SplitInference] self.@slug: String self.@_params_type: singleton(Params::SplitParameters) @@ -13,6 +13,8 @@ module Mindee def _params_type: -> singleton(Params::SplitParameters) + def extract_from_file: (Mindee::Input::Source::LocalInputSource) -> FileOperation::SplitFiles + def to_s: -> String def self._params_type: () -> singleton(Params::SplitParameters) def self.slug: () -> String diff --git a/spec/bin/cli_integration.rb b/spec/bin/cli_integration.rb new file mode 100644 index 000000000..ede5c4af6 --- /dev/null +++ b/spec/bin/cli_integration.rb @@ -0,0 +1,91 @@ +# frozen_string_literal: true + +require 'open3' +require 'rbconfig' +require_relative '../data' + +describe 'Mindee CLI V2', :integration, :v2, order: :defined do + let(:findoc_model_id) { ENV.fetch('MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID') } + let(:classification_model_id) { ENV.fetch('MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID') } + let(:crop_model_id) { ENV.fetch('MINDEE_V2_SE_TESTS_CROP_MODEL_ID') } + let(:ocr_model_id) { ENV.fetch('MINDEE_V2_SE_TESTS_OCR_MODEL_ID') } + let(:split_model_id) { ENV.fetch('MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID') } + let(:blank_pdf_url) { ENV.fetch('MINDEE_V2_SE_TESTS_BLANK_PDF_URL') } + let(:test_file) { File.join(FILE_TYPES_DIR, 'pdf', 'blank_1.pdf') } + let(:cli_path) { File.expand_path('../../bin/mindee.rb', __dir__) } + + def run_cli(*args) + Open3.capture3(RbConfig.ruby, cli_path, *args) + end + + context 'search-models command' do + ['classification', 'crop', 'extraction', 'ocr', 'split'].each do |model_type| + it "returns model list for type #{model_type}" do + stdout, stderr, status = run_cli('v2', 'search-models', '-t', model_type) + expect(status.success?).to eq(true), stderr + expect(stdout.strip).not_to be_empty + end + end + + it 'returns no models for non-existent name' do + stdout, stderr, status = run_cli('v2', 'search-models', '-n', 'supercalifragilisticexpialidocious') + expect(status.success?).to eq(true), stderr + expect(stdout.strip).to eq('') + end + + it 'returns models for name filter' do + stdout, stderr, status = run_cli('v2', 'search-models', '-n', 'findoc') + expect(status.success?).to eq(true), stderr + expect(stdout.strip).not_to be_empty + end + + it 'returns models for name and model_type filters' do + stdout, stderr, status = run_cli('v2', 'search-models', '-n', 'findoc', '-t', 'extraction') + expect(status.success?).to eq(true), stderr + expect(stdout.strip).not_to be_empty + end + + it 'returns HTTP 422 on invalid model type' do + stdout, stderr, status = run_cli('v2', 'search-models', '-t', 'invalid') + expect(status.success?).to eq(false) + expect("#{stdout}\n#{stderr}").to include('HTTP 422') + end + end + + context 'product commands' do + it 'runs extraction from an URL source' do + stdout, stderr, status = run_cli('v2', 'extraction', '-m', findoc_model_id, blank_pdf_url) + expect(status.success?).to eq(true), stderr + expect(stdout.strip).not_to be_empty + end + + { + 'classification' => -> { classification_model_id }, + 'crop' => -> { crop_model_id }, + 'ocr' => -> { ocr_model_id }, + 'split' => -> { split_model_id }, + }.each do |command, model_id_proc| + it "runs #{command} with default args" do + stdout, stderr, status = run_cli('v2', command, '-m', instance_exec(&model_id_proc), test_file) + expect(status.success?).to eq(true), stderr + expect(stdout.strip).not_to be_empty + end + end + end + + context 'extraction options' do + [ + ['-a', 'toto'], + ['-r'], + ['-c'], + ['-p'], + ['-t', 'toto'], + ].each do |option_args| + it "runs extraction with #{option_args.join(' ')}" do + stdout, stderr, status = run_cli('v2', 'extraction', '-m', findoc_model_id, test_file, *option_args) + expect(status.success?).to eq(true), stderr + expect(stdout.strip).not_to be_empty + end + end + end +end diff --git a/spec/data.rb b/spec/data.rb index 3550b5de0..d12a2abf6 100644 --- a/spec/data.rb +++ b/spec/data.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true ROOT_DATA_DIR = File.join(__dir__, 'data').freeze +OUTPUT_DIR = File.join(ROOT_DATA_DIR, 'output').freeze FILE_TYPES_DIR = File.join(ROOT_DATA_DIR, 'file_types').freeze V1_DATA_DIR = File.join(ROOT_DATA_DIR, 'v1').freeze V2_DATA_DIR = File.join(ROOT_DATA_DIR, 'v2').freeze diff --git a/spec/dependency_spec.rb b/spec/dependency_spec.rb new file mode 100644 index 000000000..6f80cbdd5 --- /dev/null +++ b/spec/dependency_spec.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +require 'mindee' +describe Mindee::Dependency do + before(:each) do + if Mindee::Dependency.instance_variable_defined?(:@all_deps_available) + Mindee::Dependency.remove_instance_variable(:@all_deps_available) + end + end + + describe '.all_deps_available?' do + context 'when evaluating the full mindee gem' do + before do + allow(Mindee::Dependency).to receive(:require).and_return(true) + + Mindee::Dependency.instance_variable_set(:@all_deps_available, Mindee::Dependency.check_all_dependencies) + end + + it 'returns true' do + expect(Mindee::Dependency.all_deps_available?).to be true + end + end + + context 'when evaluating the mindee-lite gem' do + before do + allow(Mindee::Dependency).to receive(:require).and_raise(LoadError) + + Mindee::Dependency.instance_variable_set(:@all_deps_available, Mindee::Dependency.check_all_dependencies) + end + + it 'returns false' do + expect(Mindee::Dependency.all_deps_available?).to be false + end + end + end +end + +describe 'Mindee PDF Module Loading' do + let(:pdf_tools_module_path) { File.expand_path('../lib/mindee/pdf/pdf_tools.rb', __dir__) } + + context 'when initialized in a mindee-lite environment' do + before do + allow(Mindee::Dependency).to receive(:all_deps_available?).and_return(false) + end + + it 'raises a LoadError with the lite exception message' do + expect do + load pdf_tools_module_path + end.to raise_error(LoadError, Mindee::Dependency::MINDEE_DEPENDENCIES_LOAD_ERROR) + end + end + + context 'when initialized in a full mindee environment' do + around do |example| + original_require = Kernel.instance_method(:require) + + Kernel.define_method(:require) do |name| + ['origami', 'mini_magick', 'pdf-reader'].include?(name) || original_require.bind_call(self, name) + end + + begin + example.run + ensure + Kernel.define_method(:require, original_require) # Restore original require + end + end + + before do + allow(Mindee::Dependency).to receive(:all_deps_available?).and_return(true) + end + + it 'loads the module successfully without raising errors' do + expect do + load pdf_tools_module_path + end.not_to raise_error + end + end +end diff --git a/spec/image/extracted_image_spec.rb b/spec/image/extracted_image_spec.rb index 7462ddca1..82ddbda30 100644 --- a/spec/image/extracted_image_spec.rb +++ b/spec/image/extracted_image_spec.rb @@ -3,10 +3,16 @@ require 'mindee' require 'pathname' require 'fileutils' -require 'mini_magick' require_relative '../data' -describe Mindee::Image::ExtractedImage do +describe 'Mindee::Image::ExtractedImage', :all_deps do + require 'mini_magick' if Mindee::Dependency.all_deps_available? + # Workaround for mindee-lite + if Mindee::Dependency.all_deps_available? + let(:described_class) do + Mindee::Image::ExtractedImage + end + end let(:file_path) do File.join(V1_DATA_DIR, 'products', 'invoices', 'default_sample.jpg') end @@ -23,7 +29,7 @@ expect(extracted_image.page_id).to eq(page_id) expect(extracted_image.element_id).to eq(element_id) - expect(extracted_image.internal_file_name).to eq('default_sample_p1_42.jpg') + expect(extracted_image.filename).to eq('default_sample_p1_42.jpg') # NOTE: ruby messes up the formatting of binary strings, I don't think it worth it to correct this behavior, but # the result is that we have to remove them from the comparisons. @@ -47,7 +53,7 @@ extracted_image = described_class.new(input_source, page_id, element_id) - expect(extracted_image.internal_file_name).to eq('default_sample_p1_42.jpg') + expect(extracted_image.filename).to eq('default_sample_p1_42.jpg') end end @@ -68,7 +74,7 @@ expect do extracted_image.write_to_file(invalid_output_path) - end.to raise_error(Mindee::Errors::MindeeImageError, %r{Invalid file format}) + end.to raise_error(Mindee::Error::MindeeImageError, %r{Invalid file format}) end it 'raises an error if the file cannot be saved' do @@ -77,7 +83,7 @@ expect do extracted_image.write_to_file(invalid_output_path) - end.to raise_error(Mindee::Errors::MindeeImageError) + end.to raise_error(Mindee::Error::MindeeImageError) end end @@ -108,7 +114,7 @@ Tempfile.create(['output', '.jpg']) do |tempfile| expect do extracted_image.write_to_file(tempfile.path, 'jpg') - end.to raise_error(Mindee::Errors::MindeeImageError, %r{Could not save file}) + end.to raise_error(Mindee::Error::MindeeImageError, %r{Could not save file}) end end diff --git a/spec/image/image_compressor_spec.rb b/spec/image/image_compressor_spec.rb index 342dff085..dfb4ad554 100644 --- a/spec/image/image_compressor_spec.rb +++ b/spec/image/image_compressor_spec.rb @@ -4,7 +4,7 @@ require_relative '../data' -describe Mindee::Image::ImageCompressor do +describe Mindee::Image::ImageCompressor, :all_deps do describe 'Image Quality Compression' do let(:input_receipt_path) { "#{FILE_TYPES_DIR}/receipt.jpg" } let(:output_dir) { "#{ROOT_DATA_DIR}/output/" } diff --git a/spec/image/image_extractor_spec.rb b/spec/image/image_extractor_spec.rb index 54b55e223..a22030a6d 100644 --- a/spec/image/image_extractor_spec.rb +++ b/spec/image/image_extractor_spec.rb @@ -1,11 +1,12 @@ # frozen_string_literal: true -require 'mindee/product' +require 'mindee/v1/product' require 'mindee/input/sources' require_relative '../data' -describe Mindee::Image do +describe Mindee::Image, :all_deps do include Mindee::Image + let(:barcode_path) do File.join(V1_DATA_DIR, 'products', 'barcode_reader', 'default_sample.jpg') end @@ -17,7 +18,7 @@ context 'an image extractor' do it 'extracts barcode images correctly' do json_data = JSON.parse(File.read(barcode_json_path)) - inference = Mindee::Product::BarcodeReader::BarcodeReaderV1.new(json_data['document']['inference']) + inference = Mindee::V1::Product::BarcodeReader::BarcodeReaderV1.new(json_data['document']['inference']) barcodes1 = inference.prediction.codes_1d.map(&:polygon) barcodes2 = inference.prediction.codes_2d.map(&:polygon) input_source = Mindee::Input::Source::PathInputSource.new(barcode_path) diff --git a/spec/image/image_utils_spec.rb b/spec/image/image_utils_spec.rb index 0579770b8..1f2f94a0a 100644 --- a/spec/image/image_utils_spec.rb +++ b/spec/image/image_utils_spec.rb @@ -1,11 +1,11 @@ # frozen_string_literal: true # spec/image_utils_spec.rb -require 'mini_magick' require 'stringio' require 'mindee' -describe Mindee::Image::ImageUtils do +describe 'Mindee::Image::ImageUtils', :all_deps do + require 'mini_magick' if Mindee::Dependency.all_deps_available? let(:sample_image_path) { "#{FILE_TYPES_DIR}/receipt.jpg" } let(:sample_image) { MiniMagick::Image.open(sample_image_path) } @@ -24,7 +24,7 @@ it 'Should raise an error for invalid input types' do expect do Mindee::Image::ImageUtils.to_image(123) - end.to raise_error(Mindee::Errors::MindeeImageError, %r{Expected an I/O object or a MiniMagick::Image}) + end.to raise_error(Mindee::Error::MindeeImageError, %r{Expected an I/O object or a MiniMagick::Image}) end it 'Should convert MiniMagick image to StringIO' do @@ -51,7 +51,7 @@ it 'Should raise an error if the original image is nil' do expect do Mindee::Image::ImageUtils.calculate_new_dimensions(nil) - end.to raise_error(Mindee::Errors::MindeeImageError, %r{Provided image could not be processed for resizing}) + end.to raise_error(Mindee::Error::MindeeImageError, %r{Provided image could not be processed for resizing}) end it 'Should return dimensions from media box if provided' do diff --git a/spec/input/sources/sources_spec.rb b/spec/input/sources/sources_spec.rb index 0611c0651..caf006972 100644 --- a/spec/input/sources/sources_spec.rb +++ b/spec/input/sources/sources_spec.rb @@ -2,8 +2,8 @@ require 'mindee' require 'mindee/input/sources' -require 'mindee/errors' -require 'pdf-reader' +require 'mindee/error' +require 'pdf-reader' if Mindee::Dependency.all_deps_available? require_relative '../../data' @@ -15,7 +15,7 @@ ) expect(input_source.file_mimetype).to eq('image/jpeg') expect(input_source.filename).to eq('receipt.jpg') - expect(input_source.page_count).to eq(1) + expect(input_source.page_count).to eq(1) if Mindee::Dependency.all_deps_available? expect(input_source.pdf?).to eq(false) input_source = Mindee::Input::Source::PathInputSource.new( @@ -23,7 +23,7 @@ ) expect(input_source.file_mimetype).to eq('image/jpeg') expect(input_source.filename).to eq('receipt.jpga') - expect(input_source.page_count).to eq(1) + expect(input_source.page_count).to eq(1) if Mindee::Dependency.all_deps_available? expect(input_source.pdf?).to eq(false) end @@ -33,7 +33,7 @@ ) expect(input_source.file_mimetype).to eq('image/tiff') expect(input_source.filename).to eq('receipt.tif') - expect(input_source.page_count).to eq(1) + expect(input_source.page_count).to eq(1) if Mindee::Dependency.all_deps_available? expect(input_source.pdf?).to eq(false) input_source = Mindee::Input::Source::PathInputSource.new( @@ -41,11 +41,11 @@ ) expect(input_source.file_mimetype).to eq('image/tiff') expect(input_source.filename).to eq('receipt.tiff') - expect(input_source.page_count).to eq(1) + expect(input_source.page_count).to eq(1) if Mindee::Dependency.all_deps_available? expect(input_source.pdf?).to eq(false) end - it 'should load a HEIC from a path' do + it 'should load a HEIC from a path', :all_deps do input_source = Mindee::Input::Source::PathInputSource.new( File.join(FILE_TYPES_DIR, 'receipt.heic') ) @@ -56,7 +56,7 @@ end end - context 'A PDF input file' do + context 'A PDF input file', :all_deps do it 'should load a multi-page PDF from a path' do input_source = Mindee::Input::Source::PathInputSource.new( File.join(V1_DATA_DIR, 'products/invoices/invoice.pdf') @@ -85,7 +85,7 @@ end context 'A broken fixable PDF' do - mindee_client = Mindee::Client.new(api_key: 'invalid-api-key') + mindee_client = Mindee::V1::Client.new(api_key: 'invalid-api-key') it 'Should not raise a mime error' do expect do mindee_client.source_from_path( @@ -96,18 +96,18 @@ end context 'A broken unfixable PDF' do - mindee_client = Mindee::Client.new(api_key: 'invalid-api-key') + mindee_client = Mindee::V1::Client.new(api_key: 'invalid-api-key') it 'Should raise an error' do expect do mindee_client.source_from_path( "#{FILE_TYPES_DIR}/pdf/broken_unfixable.pdf", repair_pdf: true ) - end.to raise_error Mindee::Errors::MindeePDFError + end.to raise_error Mindee::Error::MindeePDFError end end context 'A broken fixable invoice PDF' do - mindee_client = Mindee::Client.new(api_key: 'invalid-api-key') + mindee_client = Mindee::V1::Client.new(api_key: 'invalid-api-key') it 'Should send correct results' do source_doc_original = mindee_client.source_from_path("#{V1_DATA_DIR}/products/invoices/invoice.pdf") expect do diff --git a/spec/input/sources/url_input_source_spec.rb b/spec/input/sources/url_input_source_spec.rb index d2f1cb487..87407af02 100644 --- a/spec/input/sources/url_input_source_spec.rb +++ b/spec/input/sources/url_input_source_spec.rb @@ -19,7 +19,7 @@ context 'with invalid URL' do it 'raises an error for invalid URLs' do - expect { described_class.new(invalid_url) }.to raise_error(Mindee::Errors::MindeeInputError) + expect { described_class.new(invalid_url) }.to raise_error(Mindee::Error::MindeeInputError) end end end @@ -60,7 +60,7 @@ it 'raises an error' do expect do url_input_source.as_local_input_source - end.to raise_error(Mindee::Errors::MindeeAPIError, %r{Failed to download file}) + end.to raise_error(Mindee::Error::MindeeAPIError, %r{Failed to download file}) end end end @@ -105,7 +105,7 @@ it 'raises an error' do expect do url_input_source.write_to_file('/tmp') - end.to raise_error(Mindee::Errors::MindeeAPIError, %r{Failed to download file}) + end.to raise_error(Mindee::Error::MindeeAPIError, %r{Failed to download file}) end end end diff --git a/spec/openssl_crl_workaround.rb b/spec/openssl_crl_workaround.rb index 1f10c085a..f4dff34d9 100644 --- a/spec/openssl_crl_workaround.rb +++ b/spec/openssl_crl_workaround.rb @@ -3,7 +3,7 @@ require 'openssl' # Workaround for errors in SSL certificates validations on macOS. -params = OpenSSL::SSL::SSLContext::DEFAULT_PARAMS +params = OpenSSL::SSL::SSLContext::DEFAULT_PARAMS.dup params[:verify_mode] = OpenSSL::SSL::VERIFY_PEER diff --git a/spec/pdf/extracted_pdf_spec.rb b/spec/pdf/extracted_pdf_spec.rb index 06a8ca4a4..97d2122c1 100644 --- a/spec/pdf/extracted_pdf_spec.rb +++ b/spec/pdf/extracted_pdf_spec.rb @@ -2,7 +2,13 @@ require 'mindee' -describe Mindee::PDF::PDFExtractor::ExtractedPDF do +describe 'Mindee::PDF::ExtractedPDF', :all_deps do + # Workaround for mindee-lite + if Mindee::Dependency.all_deps_available? + let(:described_class) do + Mindee::PDF::ExtractedPDF + end + end let(:output_dir) { File.join(V1_DATA_DIR, 'output') } let(:valid_pdf_path) { "#{V1_PRODUCT_DATA_DIR}/invoices/invoice.pdf" } let(:invalid_pdf_path) { "#{FILE_TYPES_DIR}/receipt.txt" } @@ -12,65 +18,76 @@ allow(File).to receive(:directory?).and_return(false) allow(File).to receive(:exist?).and_return(true) allow(File).to receive(:extname).and_return('.pdf') - allow(File).to receive(:write) + allow(File).to receive(:binwrite) end describe '#initialize' do it 'initializes with valid pdf bytes and filename' do - pdf_stream = File.open(valid_pdf_path, 'r') - extracted_pdf = described_class.new(pdf_stream, 'invoice.pdf') - - expect(extracted_pdf.pdf_bytes).to eq(pdf_stream) - expect(extracted_pdf.filename).to eq('invoice.pdf') + File.open(valid_pdf_path, 'r') do |pdf_stream| + extracted_pdf = described_class.new(pdf_stream, 'invoice.pdf') + expect(extracted_pdf.pdf_bytes).to be_a(StringIO) + pdf_stream.rewind + extracted_pdf.pdf_bytes.rewind + expect(extracted_pdf.pdf_bytes.read).to eq(pdf_stream.read) + + expect(extracted_pdf.filename).to eq('invoice.pdf') + end end end describe '#page_count' do it 'raises an error for invalid PDF content' do - jpg_stream = File.open(invalid_pdf_path, 'r') - pdf_wrapper = described_class.new(jpg_stream, 'dummy.pdf') + File.open(invalid_pdf_path, 'r') do |jpg_stream| + pdf_wrapper = described_class.new(jpg_stream, 'dummy.pdf') - expect do - pdf_wrapper.page_count - end.to raise_error Mindee::Errors::MindeePDFError, %r{Could not retrieve page count} + expect do + pdf_wrapper.page_count + end.to raise_error Mindee::Error::MindeePDFError, %r{Could not retrieve page count} + end end it 'returns the correct page count for a valid PDF' do - pdf_stream = File.open(valid_pdf_path, 'r') - allow(Mindee::PDF::PDFProcessor).to receive(:open_pdf).and_return(double(pages: [1, 2, 3])) - pdf_wrapper = described_class.new(pdf_stream, 'invoice.pdf') + File.open(valid_pdf_path, 'r') do |pdf_stream| + allow(Mindee::PDF::PDFProcessor).to receive(:open_pdf).and_return(double(pages: [1, 2, 3])) + pdf_wrapper = described_class.new(pdf_stream, 'invoice.pdf') - expect(pdf_wrapper.page_count).to eq(3) + expect(pdf_wrapper.page_count).to eq(3) + end end end describe '#write_to_file' do it 'writes the PDF bytes to a specified file path' do - pdf_stream = File.open(valid_pdf_path, 'r') - pdf_wrapper = described_class.new(pdf_stream, 'invoice.pdf') - - expect { pdf_wrapper.write_to_file(output_path) }.not_to raise_error - expect(File).to have_received(:write).with(output_path, pdf_stream) + File.open(valid_pdf_path, 'r') do |pdf_stream| + expected_pdf_content = pdf_stream.read + pdf_stream.rewind + pdf_wrapper = described_class.new(pdf_stream, 'invoice.pdf') + + expect { pdf_wrapper.write_to_file(output_path) }.not_to raise_error + expect(File).to have_received(:binwrite).with(output_path, expected_pdf_content) + end end it 'raises an error if the output path is a directory' do allow(File).to receive(:directory?).and_return(true) - pdf_stream = File.open(valid_pdf_path, 'r') - pdf_wrapper = described_class.new(pdf_stream, 'invoice.pdf') + File.open(valid_pdf_path, 'r') do |pdf_stream| + pdf_wrapper = described_class.new(pdf_stream, 'invoice.pdf') - expect do - pdf_wrapper.write_to_file(output_path) - end.to raise_error Mindee::Errors::MindeePDFError, %r{Provided path is not a file} + expect do + pdf_wrapper.write_to_file(output_path) + end.to raise_error Mindee::Error::MindeePDFError, %r{Provided path is not a file} + end end it 'raises an error if the save path is invalid' do allow(File).to receive(:exist?).and_return(false) - pdf_stream = File.open(valid_pdf_path, 'r') - pdf_wrapper = described_class.new(pdf_stream, 'invoice.pdf') + File.open(valid_pdf_path, 'r') do |pdf_stream| + pdf_wrapper = described_class.new(pdf_stream, 'invoice.pdf') - expect do - pdf_wrapper.write_to_file(output_path) - end.to raise_error Mindee::Errors::MindeePDFError, %r{Invalid save path provided} + expect do + pdf_wrapper.write_to_file(output_path) + end.to raise_error Mindee::Error::MindeePDFError, %r{Invalid save path provided} + end end end diff --git a/spec/pdf/pdf_compressor_spec.rb b/spec/pdf/pdf_compressor_spec.rb index 13f6ab588..4136c5a6d 100644 --- a/spec/pdf/pdf_compressor_spec.rb +++ b/spec/pdf/pdf_compressor_spec.rb @@ -4,7 +4,7 @@ require_relative '../data' -describe Mindee::PDF::PDFCompressor do +describe 'Mindee::PDF::PDFCompressor', :all_deps do describe 'The PDF text detection method' do it 'should detect text pdf in a PDF file.' do text_input = Mindee::Input::Source::PathInputSource.new("#{FILE_TYPES_DIR}/pdf/multipage.pdf") @@ -20,6 +20,7 @@ it 'should not detect text pdf in an image file.' do image_input = Mindee::Input::Source::PathInputSource.new("#{FILE_TYPES_DIR}/receipt.jpg") + expect(Origami::PDF).not_to receive(:read) expect(Mindee::PDF::PDFTools.source_text?(image_input.io_stream)).to be(false) end end @@ -44,16 +45,17 @@ 50 => "#{ROOT_DATA_DIR}/output/compressed_direct_50.pdf", 10 => "#{ROOT_DATA_DIR}/output/compressed_direct_10.pdf", } - pdf = File.open(input_file_path) - output_file_paths.each_pair do |key, value| - compressed_pdf = Mindee::PDF::PDFCompressor.compress_pdf(pdf, quality: key) - compressed_pdf.rewind - File.write(value, compressed_pdf.read) + File.open(input_file_path) do |pdf| + output_file_paths.each_pair do |key, value| + compressed_pdf = Mindee::PDF::PDFCompressor.compress_pdf(pdf, quality: key) + compressed_pdf.rewind + File.write(value, compressed_pdf.read) + end + expect(File.size(input_file_path)).to be > File.size(output_file_paths[85]) + expect(File.size(output_file_paths[75])).to be < File.size(output_file_paths[85]) + expect(File.size(output_file_paths[50])).to be < File.size(output_file_paths[75]) + expect(File.size(output_file_paths[10])).to be < File.size(output_file_paths[50]) end - expect(File.size(input_file_path)).to be > File.size(output_file_paths[85]) - expect(File.size(output_file_paths[75])).to be < File.size(output_file_paths[85]) - expect(File.size(output_file_paths[50])).to be < File.size(output_file_paths[75]) - expect(File.size(output_file_paths[10])).to be < File.size(output_file_paths[50]) end after(:each) do diff --git a/spec/pdf/pdf_extractor_spec.rb b/spec/pdf/pdf_extractor_spec.rb index f640e8eae..cdae8a235 100644 --- a/spec/pdf/pdf_extractor_spec.rb +++ b/spec/pdf/pdf_extractor_spec.rb @@ -2,15 +2,15 @@ require 'mindee' -describe 'Invoice extraction' do +describe 'Invoice extraction', :all_deps do let(:invoice_default_sample_path) { File.join(V1_PRODUCT_DATA_DIR, 'invoices', 'default_sample.jpg') } let(:invoice_splitter_5p_path) { File.join(V1_PRODUCT_DATA_DIR, 'invoice_splitter', 'invoice_5p.pdf') } let(:loaded_prediction_path) { File.join(V1_PRODUCT_DATA_DIR, 'invoice_splitter', 'response_v1', 'complete.json') } let(:loaded_prediction) do - dummy_client = Mindee::Client.new(api_key: 'dummy_key') + dummy_client = Mindee::V1::Client.new(api_key: 'dummy_key') input_response = Mindee::Input::LocalResponse.new(loaded_prediction_path) - response = dummy_client.load_prediction(Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, input_response) + response = dummy_client.load_prediction(Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, input_response) response.document.inference.prediction end @@ -18,13 +18,13 @@ jpg_input = Mindee::Input::Source::PathInputSource.new(invoice_default_sample_path) expect(jpg_input.pdf?).to eq(false) - extractor = Mindee::PDF::PDFExtractor::PDFExtractor.new(jpg_input) + extractor = Mindee::PDF::PDFExtractor.new(jpg_input) expect(extractor.page_count).to eq(1) end it 'should extract invoices from a PDF (no strict mode)' do pdf_input = Mindee::Input::Source::PathInputSource.new(invoice_splitter_5p_path) - extractor = Mindee::PDF::PDFExtractor::PDFExtractor.new(pdf_input) + extractor = Mindee::PDF::PDFExtractor.new(pdf_input) expect(extractor.page_count).to eq(5) @@ -43,7 +43,7 @@ it 'should extract invoices from a PDF (strict mode)' do pdf_input = Mindee::Input::Source::PathInputSource.new(invoice_splitter_5p_path) - extractor = Mindee::PDF::PDFExtractor::PDFExtractor.new(pdf_input) + extractor = Mindee::PDF::PDFExtractor.new(pdf_input) expect(extractor.page_count).to eq(5) expect(loaded_prediction.invoice_page_groups.length).to eq(3) diff --git a/spec/pdf/pdf_processor_spec.rb b/spec/pdf/pdf_processor_spec.rb index e4e2f8f23..f07dc0c56 100644 --- a/spec/pdf/pdf_processor_spec.rb +++ b/spec/pdf/pdf_processor_spec.rb @@ -4,7 +4,7 @@ require_relative '../data' -describe Mindee::PDF do +describe 'Mindee::PDF', :all_deps do def open_pdf(io_stream) pdf_parser = Origami::PDF::LinearParser.new({}) io_stream.seek(0) @@ -15,29 +15,31 @@ def open_pdf(io_stream) filepath = File.join(FILE_TYPES_DIR, 'pdf/blank.pdf').freeze it 'Should grab the first page' do - io_stream = File.open(filepath, 'rb') - io_stream.seek(0) - options = Mindee::PageOptions.new(params: { - page_indexes: [0], - operation: :KEEP_ONLY, - on_min_pages: 0, - }) - new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) - new_pdf = open_pdf(new_stream) - expect(new_pdf.pages.size).to eq(1) + File.open(filepath, 'rb') do |io_stream| + io_stream.seek(0) + options = Mindee::PageOptions.new(params: { + page_indexes: [0], + operation: :KEEP_ONLY, + on_min_pages: 0, + }) + new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) + new_pdf = open_pdf(new_stream) + expect(new_pdf.pages.size).to eq(1) + end end it 'Should grab the last page' do - io_stream = File.open(filepath, 'rb') - io_stream.seek(0) - options = Mindee::PageOptions.new(params: { - page_indexes: [-1], - operation: :KEEP_ONLY, - on_min_pages: 0, - }) - new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) - new_pdf = open_pdf(new_stream) - expect(new_pdf.pages.size).to eq(1) + File.open(filepath, 'rb') do |io_stream| + io_stream.seek(0) + options = Mindee::PageOptions.new(params: { + page_indexes: [-1], + operation: :KEEP_ONLY, + on_min_pages: 0, + }) + new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) + new_pdf = open_pdf(new_stream) + expect(new_pdf.pages.size).to eq(1) + end end end @@ -45,81 +47,87 @@ def open_pdf(io_stream) filepath = File.join(FILE_TYPES_DIR, 'pdf/multipage.pdf').freeze it 'Should grab the first page' do - io_stream = File.open(filepath, 'rb') - io_stream.seek(0) - options = Mindee::PageOptions.new(params: { - page_indexes: [0], - operation: :KEEP_ONLY, - on_min_pages: 0, - }) - new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) - new_pdf = open_pdf(new_stream) - expect(new_pdf.pages.size).to eq(1) + File.open(filepath, 'rb') do |io_stream| + io_stream.seek(0) + options = Mindee::PageOptions.new(params: { + page_indexes: [0], + operation: :KEEP_ONLY, + on_min_pages: 0, + }) + new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) + new_pdf = open_pdf(new_stream) + expect(new_pdf.pages.size).to eq(1) + end end it 'Should grab the last page' do - io_stream = File.open(filepath, 'rb') - io_stream.seek(0) - options = Mindee::PageOptions.new(params: { - page_indexes: [-1], - operation: :KEEP_ONLY, - on_min_pages: 0, - }) - new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) - new_pdf = open_pdf(new_stream) - expect(new_pdf.pages.size).to eq(1) + File.open(filepath, 'rb') do |io_stream| + io_stream.seek(0) + options = Mindee::PageOptions.new(params: { + page_indexes: [-1], + operation: :KEEP_ONLY, + on_min_pages: 0, + }) + new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) + new_pdf = open_pdf(new_stream) + expect(new_pdf.pages.size).to eq(1) + end end it 'Should grab the first 2, and the last page' do - io_stream = File.open(filepath, 'rb') - io_stream.seek(0) - options = Mindee::PageOptions.new(params: { - page_indexes: [0, 1, -1], - operation: :KEEP_ONLY, - on_min_pages: 0, - }) - new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) - new_pdf = open_pdf(new_stream) - expect(new_pdf.pages.size).to eq(3) + File.open(filepath, 'rb') do |io_stream| + io_stream.seek(0) + options = Mindee::PageOptions.new(params: { + page_indexes: [0, 1, -1], + operation: :KEEP_ONLY, + on_min_pages: 0, + }) + new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) + new_pdf = open_pdf(new_stream) + expect(new_pdf.pages.size).to eq(3) + end end it 'Should grab the first 5 pages' do - io_stream = File.open(filepath, 'rb') - io_stream.seek(0) - options = Mindee::PageOptions.new(params: { - page_indexes: [0, 1, 2, 3, 4], - operation: :KEEP_ONLY, - on_min_pages: 0, - }) - new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) - new_pdf = open_pdf(new_stream) - expect(new_pdf.pages.size).to eq(5) + File.open(filepath, 'rb') do |io_stream| + io_stream.seek(0) + options = Mindee::PageOptions.new(params: { + page_indexes: [0, 1, 2, 3, 4], + operation: :KEEP_ONLY, + on_min_pages: 0, + }) + new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) + new_pdf = open_pdf(new_stream) + expect(new_pdf.pages.size).to eq(5) + end end it 'Should remove the first 3 pages' do - io_stream = File.open(filepath, 'rb') - io_stream.seek(0) - options = Mindee::PageOptions.new(params: { - page_indexes: [0, 1, 2], - operation: :REMOVE, - on_min_pages: 0, - }) - new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) - new_pdf = open_pdf(new_stream) - expect(new_pdf.pages.size).to eq(9) + File.open(filepath, 'rb') do |io_stream| + io_stream.seek(0) + options = Mindee::PageOptions.new(params: { + page_indexes: [0, 1, 2], + operation: :REMOVE, + on_min_pages: 0, + }) + new_stream = Mindee::PDF::PDFProcessor.parse(io_stream, options) + new_pdf = open_pdf(new_stream) + expect(new_pdf.pages.size).to eq(9) + end end it 'Should fail on invalid operation' do - io_stream = File.open(filepath, 'rb') - io_stream.seek(0) - options = Mindee::PageOptions.new(params: { - page_indexes: [1], - operation: :broken, - on_min_pages: 0, - }) - expect do - Mindee::PDF::PDFProcessor.parse(io_stream, options) - end.to raise_error ArgumentError + File.open(filepath, 'rb') do |io_stream| + io_stream.seek(0) + options = Mindee::PageOptions.new(params: { + page_indexes: [1], + operation: :broken, + on_min_pages: 0, + }) + expect do + Mindee::PDF::PDFProcessor.parse(io_stream, options) + end.to raise_error ArgumentError + end end end end diff --git a/spec/test_code_samples_v2.sh b/spec/test_code_samples_v2.sh deleted file mode 100755 index 16a6e30c7..000000000 --- a/spec/test_code_samples_v2.sh +++ /dev/null @@ -1,45 +0,0 @@ -#! /bin/sh -set -e - -OUTPUT_FILE='./_test_v2.rb' - -for f in $(find ./docs/code_samples -maxdepth 1 -name "v2_*.txt" | sort -h) -do - echo - echo "###############################################" - echo "${f}" - echo "###############################################" - echo - - cat "${f}" > $OUTPUT_FILE - sed -i "s/MY_API_KEY/${MINDEE_V2_API_KEY}/" $OUTPUT_FILE - sed -i "s/MY_WEBHOOK_ID/${MINDEE_V2_SE_TESTS_FAILURE_WEBHOOK_ID}/" $OUTPUT_FILE - sed -i 's/\/path\/to\/the\/file.ext/.\/spec\/data\/file_types\/pdf\/blank_1.pdf/' $OUTPUT_FILE - - if echo "${f}" | grep -q "v2_extraction.*.txt" - then - sed -i "s/MY_MODEL_ID/${MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID}/" $OUTPUT_FILE - fi - - if echo "${f}" | grep -q "v2_classification.txt" - then - sed -i "s/MY_MODEL_ID/${MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID}/" $OUTPUT_FILE - fi - - if echo "${f}" | grep -q "v2_crop.txt" - then - sed -i "s/MY_MODEL_ID/${MINDEE_V2_SE_TESTS_CROP_MODEL_ID}/" $OUTPUT_FILE - fi - - if echo "${f}" | grep -q "v2_ocr.txt" - then - sed -i "s/MY_MODEL_ID/${MINDEE_V2_SE_TESTS_OCR_MODEL_ID}/" $OUTPUT_FILE - fi - - if echo "${f}" | grep -q "v2_split.txt" - then - sed -i "s/MY_MODEL_ID/${MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID}/" $OUTPUT_FILE - fi - - bundle exec ruby $OUTPUT_FILE -done diff --git a/spec/test_v1_cli.sh b/spec/test_v1_cli.sh new file mode 100755 index 000000000..166d9e7d7 --- /dev/null +++ b/spec/test_v1_cli.sh @@ -0,0 +1,56 @@ +#!/bin/sh +set -e + +# Initialize rbenv +export PATH="$HOME/.rbenv/bin:$PATH" +eval "$($HOME/.rbenv/bin/rbenv init -)" + +TEST_FILE=$1 +RID=$2 + +if [ -z "$TEST_FILE" ]; then + echo "Error: no sample file provided" + exit 1 +fi + +if [ -z "$RID" ]; then + OS_NAME="$(uname -s)" + case "$OS_NAME" in + Linux*) RID="linux-x64" ;; + Darwin*) RID="osx-x64" ;; + CYGWIN*|MINGW*|MSYS*) RID="win-x64" ;; + *) + echo "" + echo "Error: Could not determine default Runtime Identifier (RID) for OS type '$OS_NAME'." + echo "Please provide one manually. Available: 'linux-x64', 'osx-x64', 'win-x64'" + exit 1 + ;; + esac + echo "Warning: Runtime Identifier (RID) not provided, defaulting to $RID" +fi + +WD="$(basename "$PWD")" +if [ "$WD" = "spec" ]; then + CLI_PATH="../bin/mindee.rb" +else + CLI_PATH="./bin/mindee.rb" +fi + +if [ "$RID" = "win-x64" ]; then + CLI_PATH="${CLI_PATH}.exe" +fi + +PRODUCTS="financial-document receipt invoice invoice-splitter" +PRODUCTS_SIZE=4 +i=1 + +for product in $PRODUCTS +do + echo "--- Test $product with Summary Output ($i/$PRODUCTS_SIZE) ---" + SUMMARY_OUTPUT=$(ruby "$CLI_PATH" v1 "$product" "$TEST_FILE") + echo "$SUMMARY_OUTPUT" + echo "" + echo "" + sleep 0.5 + i=$((i + 1)) +done diff --git a/spec/test_code_samples_v1.sh b/spec/test_v1_code_samples.sh similarity index 100% rename from spec/test_code_samples_v1.sh rename to spec/test_v1_code_samples.sh diff --git a/spec/test_v2_cli.sh b/spec/test_v2_cli.sh new file mode 100755 index 000000000..89c4b406e --- /dev/null +++ b/spec/test_v2_cli.sh @@ -0,0 +1,54 @@ +#!/bin/sh +set -e + +TEST_FILE=$1 +RID=$2 + +export PATH="$HOME/.rbenv/bin:$PATH" +eval "$($HOME/.rbenv/bin/rbenv init -)" + +if [ -z "$TEST_FILE" ]; then + echo "Error: no sample file provided" + exit 1 +fi + +if [ -z "$RID" ]; then + OS_NAME="$(uname -s)" + case "$OS_NAME" in + Linux*) RID="linux-x64" ;; + Darwin*) RID="osx-x64" ;; + CYGWIN*|MINGW*|MSYS*) RID="win-x64" ;; + *) + echo "" + echo "Error: Could not determine default Runtime Identifier (RID) for OS type '$OS_NAME'." + echo "Please provide one manually. Available: 'linux-x64', 'osx-x64', 'win-x64'" + exit 1 + ;; + esac + echo "Warning: Runtime Identifier (RID) not provided, defaulting to $RID" +fi + +WD="$(basename "$PWD")" +if [ "$WD" = "spec" ]; then + CLI_PATH="../bin/mindee.rb" +else + CLI_PATH="./bin/mindee.rb" +fi + +echo "--- Test model list retrieval (all models)" +MODELS=$("$CLI_PATH" v2 search-models) +if [ -z "$MODELS" ]; then + echo "Error: no models found" + exit 1 +else + echo "Models retrieval OK" +fi + +echo "--- Test extraction with no additional args" +SUMMARY_OUTPUT=$("$CLI_PATH" v2 extraction -m "$MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID" "$TEST_FILE") +if [ -z "$SUMMARY_OUTPUT" ]; then + echo "Error: no extraction output" + exit 1 +else + echo "Extraction retrieval OK" +fi diff --git a/spec/test_v2_code_samples.sh b/spec/test_v2_code_samples.sh new file mode 100755 index 000000000..4a2917023 --- /dev/null +++ b/spec/test_v2_code_samples.sh @@ -0,0 +1,45 @@ +#! /bin/sh +set -e + +OUTPUT_FILE='./_test_v2.rb' + +for f in $(find ./docs/code_samples -maxdepth 1 -name "v2_*.txt" | sort -h) +do + echo + echo "###############################################" + echo "${f}" + echo "###############################################" + echo + + cat "${f}" > $OUTPUT_FILE + sed -i "s/MY_API_KEY/${MINDEE_V2_API_KEY}/" $OUTPUT_FILE + sed -i 's/\/path\/to\/the\/file.ext/.\/spec\/data\/file_types\/pdf\/blank_1.pdf/' $OUTPUT_FILE + + if echo "${f}" | grep -q "v2_extraction" + then + sed -i "s/MY_MODEL_ID/${MINDEE_V2_FINDOC_MODEL_ID}/" $OUTPUT_FILE + sed -i "s/MY_WEBHOOK_ID/${MINDEE_V2_FAILURE_WEBHOOK_ID}/" $OUTPUT_FILE + fi + + if echo "${f}" | grep -q "v2_classification" + then + sed -i "s/MY_MODEL_ID/${MINDEE_V2_CLASSIFICATION_MODEL_ID}/" $OUTPUT_FILE + fi + + if echo "${f}" | grep -q "v2_crop" + then + sed -i "s/MY_MODEL_ID/${MINDEE_V2_CROP_MODEL_ID}/" $OUTPUT_FILE + fi + + if echo "${f}" | grep -q "v2_ocr" + then + sed -i "s/MY_MODEL_ID/${MINDEE_V2_OCR_MODEL_ID}/" $OUTPUT_FILE + fi + + if echo "${f}" | grep -q "v2_split" + then + sed -i "s/MY_MODEL_ID/${MINDEE_V2_SPLIT_MODEL_ID}/" $OUTPUT_FILE + fi + + bundle exec ruby $OUTPUT_FILE +done diff --git a/spec/v1/api_response_spec.rb b/spec/v1/api_response_spec.rb index ef744bb60..f0208e15d 100644 --- a/spec/v1/api_response_spec.rb +++ b/spec/v1/api_response_spec.rb @@ -4,16 +4,17 @@ require 'mindee' require_relative '../data' -describe Mindee::Parsing::Common::ApiResponse do +describe Mindee::V1::Parsing::Common::ApiResponse do context 'An Invoice document' do it 'should be properly created from an ApiResponse' do response = load_json(V1_PRODUCT_DATA_DIR, 'invoices/response_v4/complete.json') + raw_response = JSON.generate(response) rst_response = read_file(V1_PRODUCT_DATA_DIR, 'invoices/response_v4/summary_full.rst') - parsed_response = Mindee::Parsing::Common::ApiResponse.new(Mindee::Product::Invoice::InvoiceV4, - response, response.to_s) - expect(parsed_response.document.inference).to be_a Mindee::Product::Invoice::InvoiceV4 - expect(parsed_response.document.inference.prediction).to be_a Mindee::Product::Invoice::InvoiceV4Document - expect(parsed_response.raw_http).to eq(response.to_s) + parsed_response = Mindee::V1::Parsing::Common::ApiResponse.new(Mindee::V1::Product::Invoice::InvoiceV4, + response, raw_response) + expect(parsed_response.document.inference).to be_a Mindee::V1::Product::Invoice::InvoiceV4 + expect(parsed_response.document.inference.prediction).to be_a Mindee::V1::Product::Invoice::InvoiceV4Document + expect(parsed_response.raw_http).to eq(raw_response) expect(parsed_response.document.n_pages).to eq(1) expect(parsed_response.document.inference.pages.length).to eq(1) expect(parsed_response.document.to_s).to eq(rst_response.to_s) diff --git a/spec/v1/async_rseponse_spec.rb b/spec/v1/async_rseponse_spec.rb index 9a264a57f..207fcf737 100644 --- a/spec/v1/async_rseponse_spec.rb +++ b/spec/v1/async_rseponse_spec.rb @@ -5,22 +5,24 @@ require_relative '../data' require_relative '../http/mock_http_response' -describe Mindee::Parsing::Common::ApiResponse do +describe Mindee::V1::Parsing::Common::ApiResponse do context 'An async request' do it 'should be able to be sent' do response = load_json(V1_ASYNC_DIR, 'post_success.json') fake_response = MockHTTPResponse.new('1.0', response['api_request']['status_code'].to_s, 'OK', JSON.generate(response)) expect(Mindee::HTTP::ResponseValidation.valid_async_response?(fake_response)).to eq(true) - parsed_response = Mindee::Parsing::Common::ApiResponse.new(Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, - response, response.to_json) + parsed_response = Mindee::V1::Parsing::Common::ApiResponse.new( + Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, + response, fake_response.body + ) - expect(parsed_response.job.status).to eq(Mindee::Parsing::Common::JobStatus::WAITING) + expect(parsed_response.job.status).to eq(Mindee::V1::Parsing::Common::JobStatus::WAITING) expect(parsed_response.job.id).to eq('76c90710-3a1b-4b91-8a39-31a6543e347c') expect(parsed_response.job.status).to_not respond_to(:available_at) expect(parsed_response.job.status).to_not respond_to(:millisecs_taken) expect(parsed_response.api_request.error).to eq({}) - expect(parsed_response.raw_http).to eq(response.to_json) + expect(parsed_response.raw_http).to eq(fake_response.body) end it 'should not be able to be sent on incompatible endpoints' do @@ -28,8 +30,10 @@ fake_response = MockHTTPResponse.new('1.0', response['api_request']['status_code'].to_s, 'NOT OK', JSON.generate(response)) expect(Mindee::HTTP::ResponseValidation.valid_async_response?(fake_response)).to eq(false) - parsed_response = Mindee::Parsing::Common::ApiResponse.new(Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, - response, response.to_json) + parsed_response = Mindee::V1::Parsing::Common::ApiResponse.new( + Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, + response, fake_response.body + ) expect(parsed_response.job).to be(nil) end @@ -38,15 +42,17 @@ fake_response = MockHTTPResponse.new('1.0', response['api_request']['status_code'].to_s, 'OK', JSON.generate(response)) expect(Mindee::HTTP::ResponseValidation.valid_async_response?(fake_response)).to eq(true) - parsed_response = Mindee::Parsing::Common::ApiResponse.new(Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, - response, response.to_json) + parsed_response = Mindee::V1::Parsing::Common::ApiResponse.new( + Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, + response, fake_response.body + ) expect(parsed_response.job.issued_at.strftime('%Y-%m-%dT%H:%M:%S.%6N')).to eq('2023-03-16T12:33:49.602947') - expect(parsed_response.job.status).to eq(Mindee::Parsing::Common::JobStatus::PROCESSING) + expect(parsed_response.job.status).to eq(Mindee::V1::Parsing::Common::JobStatus::PROCESSING) expect(parsed_response.job.id).to eq('76c90710-3a1b-4b91-8a39-31a6543e347c') expect(parsed_response.job.status).to_not respond_to(:available_at) expect(parsed_response.job.status).to_not respond_to(:millisecs_taken) expect(parsed_response.api_request.error['code']).to eq(nil) - expect(parsed_response.raw_http).to eq(response.to_json) + expect(parsed_response.raw_http).to eq(fake_response.body) end it 'should be able to poll a completed queue' do @@ -54,16 +60,18 @@ fake_response = MockHTTPResponse.new('1.0', response['api_request']['status_code'].to_s, 'OK', JSON.generate(response)) expect(Mindee::HTTP::ResponseValidation.valid_async_response?(fake_response)).to eq(true) - parsed_response = Mindee::Parsing::Common::ApiResponse.new(Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, - response, response.to_json) + parsed_response = Mindee::V1::Parsing::Common::ApiResponse.new( + Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, + response, fake_response.body + ) expect(parsed_response.job.issued_at.strftime('%Y-%m-%dT%H:%M:%S.%6N')).to eq('2023-03-21T13:52:56.326107') - expect(parsed_response.job.status).to eq(Mindee::Parsing::Common::JobStatus::COMPLETED) + expect(parsed_response.job.status).to eq(Mindee::V1::Parsing::Common::JobStatus::COMPLETED) expect(parsed_response.job.id).to eq('b6caf9e8-9bcc-4412-bcb7-f5b416678f0d') expect(parsed_response.job.available_at.strftime('%Y-%m-%dT%H:%M:%S.%6N')).to eq('2023-03-21T13:53:00.990339') expect(parsed_response.job.millisecs_taken).to eq(4664) expect(parsed_response.document).to_not be(nil) expect(parsed_response.api_request.error['code']).to eq(nil) - expect(parsed_response.raw_http).to eq(response.to_json) + expect(parsed_response.raw_http).to eq(fake_response.body) end it 'should retrieve a failed job' do @@ -71,14 +79,16 @@ fake_response = MockHTTPResponse.new('1.0', response['api_request']['status_code'].to_s, 'NOT OK', JSON.generate(response)) expect(Mindee::HTTP::ResponseValidation.valid_async_response?(fake_response)).to eq(false) - parsed_response = Mindee::Parsing::Common::ApiResponse.new(Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, - response, response.to_json) + parsed_response = Mindee::V1::Parsing::Common::ApiResponse.new( + Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, + response, fake_response.body + ) expect(parsed_response.job.issued_at.strftime('%Y-%m-%dT%H:%M:%S.%6N')).to eq('2024-02-20T10:31:06.878599') expect(parsed_response.job.available_at.strftime('%Y-%m-%dT%H:%M:%S.%6N')).to eq('2024-02-20T10:31:06.878599') - expect(parsed_response.api_request.status).to eq(Mindee::Parsing::Common::RequestStatus::SUCCESS) + expect(parsed_response.api_request.status).to eq(Mindee::V1::Parsing::Common::RequestStatus::SUCCESS) expect(parsed_response.api_request.status_code).to eq(200) expect(parsed_response.job.error['code']).to eq('ServerError') - expect(parsed_response.job.status).to eq(Mindee::Parsing::Common::JobStatus::FAILURE) + expect(parsed_response.job.status).to eq(Mindee::V1::Parsing::Common::JobStatus::FAILURE) end end end diff --git a/spec/v1/client_spec.rb b/spec/v1/client_spec.rb index 3b6e0caf0..8d11519c0 100644 --- a/spec/v1/client_spec.rb +++ b/spec/v1/client_spec.rb @@ -4,9 +4,9 @@ require_relative '../data' -describe Mindee::Client do +describe Mindee::V1::Client do context 'A client' do - mindee_client = Mindee::Client.new(api_key: 'invalid-api-key') + mindee_client = Mindee::V1::Client.new(api_key: 'invalid-api-key') it 'should open PDF files from a path' do input_source = mindee_client.source_from_path("#{V1_DATA_DIR}/products/invoices/invoice.pdf") @@ -16,9 +16,10 @@ end it 'should open PDF files from a file handle' do - file = File.open("#{V1_DATA_DIR}/products/invoices/invoice_10p.pdf", 'rb') - input_source = mindee_client.source_from_file(file, 'invoice_10p.pdf') - expect(input_source).to respond_to(:read_contents) + File.open("#{V1_DATA_DIR}/products/invoices/invoice_10p.pdf", 'rb') do |file| + input_source = mindee_client.source_from_file(file, 'invoice_10p.pdf') + expect(input_source).to respond_to(:read_contents) + end end it 'should open PDF files from raw bytes' do @@ -41,9 +42,10 @@ end it 'should open JPG files from a file handle' do - file = File.open("#{FILE_TYPES_DIR}/receipt.jpg", 'rb') - input_source = mindee_client.source_from_file(file, 'receipt.jpg') - expect(input_source).to respond_to(:read_contents) + File.open("#{FILE_TYPES_DIR}/receipt.jpg", 'rb') do |file| + input_source = mindee_client.source_from_file(file, 'receipt.jpg') + expect(input_source).to respond_to(:read_contents) + end end it 'should open JPG files from raw bytes' do @@ -60,15 +62,15 @@ it 'should load a local response' do local_resp = Mindee::Input::LocalResponse.new("#{V1_DATA_DIR}/products/invoices/response_v4/complete.json") - mindee_client.load_prediction(Mindee::Product::Invoice::InvoiceV4, local_resp) + mindee_client.load_prediction(Mindee::V1::Product::Invoice::InvoiceV4, local_resp) expect(mindee_client).to_not be_nil end it 'should not load an invalid local response' do local_resp = Mindee::Input::LocalResponse.new("#{V1_DATA_DIR}/geometry/polygon.json") expect do - mindee_client.load_prediction(Mindee::Product::Invoice::InvoiceV4, local_resp) - end.to raise_error Mindee::Errors::MindeeInputError + mindee_client.load_prediction(Mindee::V1::Product::Invoice::InvoiceV4, local_resp) + end.to raise_error Mindee::Error::MindeeInputError end it 'should not validate improper async parameters' do @@ -77,21 +79,21 @@ expect do mindee_client.parse( input_source, - Mindee::Product::Invoice::InvoiceV4, + Mindee::V1::Product::Invoice::InvoiceV4, options: { max_retries: 0 } ) end.to raise_error ArgumentError expect do mindee_client.parse( input_source, - Mindee::Product::Invoice::InvoiceV4, + Mindee::V1::Product::Invoice::InvoiceV4, options: { initial_delay_sec: 0.5 } ) end.to raise_error ArgumentError expect do mindee_client.parse( input_source, - Mindee::Product::Invoice::InvoiceV4, + Mindee::V1::Product::Invoice::InvoiceV4, options: { delay_sec: 0.5 } ) end.to raise_error ArgumentError @@ -101,22 +103,22 @@ expect do mindee_client.send( :initialize_endpoint, - Mindee::Product::Universal::Universal, + Mindee::V1::Product::Universal::Universal, endpoint_name: '', account_name: 'account_name', version: 'version' ) - end.to raise_error Mindee::Errors::MindeeConfigurationError + end.to raise_error Mindee::Error::MindeeConfigurationError expect do mindee_client.send( :initialize_endpoint, - Mindee::Product::Universal::Universal, + Mindee::V1::Product::Universal::Universal, endpoint_name: '', account_name: 'account_name', version: 'version' ) - end.to raise_error Mindee::Errors::MindeeConfigurationError + end.to raise_error Mindee::Error::MindeeConfigurationError end end end diff --git a/spec/v1/extraction/invoice_splitter_extraction_integration.rb b/spec/v1/extraction/invoice_splitter_extraction_integration.rb index 6414dac3d..78d536e43 100644 --- a/spec/v1/extraction/invoice_splitter_extraction_integration.rb +++ b/spec/v1/extraction/invoice_splitter_extraction_integration.rb @@ -4,47 +4,49 @@ require_relative '../../data' require_relative '../../test_utilities' -describe 'PDF Invoice Extraction (Strict Mode)' do - let(:invoice_splitter_5p_path) { File.join(V1_PRODUCT_DATA_DIR, 'invoice_splitter', 'invoice_5p.pdf') } - - def prepare_invoice_return(rst_file_path, invoice_prediction) - rst_content = File.read(rst_file_path) - parsing_version = invoice_prediction.inference.product.version - parsing_id = invoice_prediction.id - - rst_content.gsub!(Mindee::TestUtilities.get_version(rst_content), parsing_version) - rst_content.gsub!(Mindee::TestUtilities.get_id(rst_content), parsing_id) - - rst_content - end - - it 'should extract invoices from a PDF (strict mode)' do - client = Mindee::Client.new - invoice_splitter_input = Mindee::Input::Source::PathInputSource.new( - File.join(V1_PRODUCT_DATA_DIR, 'invoice_splitter', 'default_sample.pdf') - ) - response = client.parse( - invoice_splitter_input, Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, options: { close_file: false } - ) - inference = response.document.inference - - pdf_extractor = Mindee::PDF::PDFExtractor::PDFExtractor.new(invoice_splitter_input) - expect(pdf_extractor.page_count).to eq(2) - - extracted_pdfs_strict = pdf_extractor.extract_invoices(inference.prediction.invoice_page_groups, strict: true) - - expect(extracted_pdfs_strict.length).to eq(2) - expect(extracted_pdfs_strict[0].filename).to eq('default_sample_001-001.pdf') - expect(extracted_pdfs_strict[1].filename).to eq('default_sample_002-002.pdf') - - invoice0 = client.parse(extracted_pdfs_strict[0].as_input_source, Mindee::Product::Invoice::InvoiceV4) - - test_string_rst_invoice0 = prepare_invoice_return( - File.join(V1_PRODUCT_DATA_DIR, 'invoices', 'response_v4', 'summary_full_invoice_p1.rst'), - invoice0.document - ) - - ratio = Mindee::TestUtilities.levenshtein_ratio(invoice0.document.to_s, test_string_rst_invoice0.chomp) - expect(ratio).to be >= 0.90 +if Mindee::Dependency.all_deps_available? # Can't be bypassed by tag as otherwise it will try to load the PDF module. + describe 'PDF Invoice Extraction (Strict Mode)', :all_deps do + let(:invoice_splitter_5p_path) { File.join(V1_PRODUCT_DATA_DIR, 'invoice_splitter', 'invoice_5p.pdf') } + + def prepare_invoice_return(rst_file_path, invoice_prediction) + rst_content = File.read(rst_file_path) + parsing_version = invoice_prediction.inference.product.version + parsing_id = invoice_prediction.id + + rst_content.gsub!(Mindee::TestUtilities.get_version(rst_content), parsing_version) + rst_content.gsub!(Mindee::TestUtilities.get_id(rst_content), parsing_id) + + rst_content + end + + it 'should extract invoices from a PDF (strict mode)' do + client = Mindee::V1::Client.new + invoice_splitter_input = Mindee::Input::Source::PathInputSource.new( + File.join(V1_PRODUCT_DATA_DIR, 'invoice_splitter', 'default_sample.pdf') + ) + response = client.parse( + invoice_splitter_input, Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, options: { close_file: false } + ) + inference = response.document.inference + + pdf_extractor = Mindee::PDF::PDFExtractor.new(invoice_splitter_input) + expect(pdf_extractor.page_count).to eq(2) + + extracted_pdfs_strict = pdf_extractor.extract_invoices(inference.prediction.invoice_page_groups, strict: true) + + expect(extracted_pdfs_strict.length).to eq(2) + expect(extracted_pdfs_strict[0].filename).to eq('default_sample_001-001.pdf') + expect(extracted_pdfs_strict[1].filename).to eq('default_sample_002-002.pdf') + + invoice0 = client.parse(extracted_pdfs_strict[0].as_input_source, Mindee::V1::Product::Invoice::InvoiceV4) + + test_string_rst_invoice0 = prepare_invoice_return( + File.join(V1_PRODUCT_DATA_DIR, 'invoices', 'response_v4', 'summary_full_invoice_p1.rst'), + invoice0.document + ) + + ratio = Mindee::TestUtilities.levenshtein_ratio(invoice0.document.to_s, test_string_rst_invoice0.chomp) + expect(ratio).to be >= 0.90 + end end end diff --git a/spec/v1/extraction/multi_receipts_extractor_spec.rb b/spec/v1/extraction/multi_receipts_extractor_spec.rb index 345837b0b..0c5337fc9 100644 --- a/spec/v1/extraction/multi_receipts_extractor_spec.rb +++ b/spec/v1/extraction/multi_receipts_extractor_spec.rb @@ -1,11 +1,11 @@ # frozen_string_literal: true -require 'mindee/product' +require 'mindee/v1/product' require 'mindee/input/sources' -require 'mindee/extraction' +require 'mindee/v1/extraction' require_relative '../../data' -describe 'multi-receipts extraction' do +describe 'multi-receipts extraction', :all_deps do let(:empty_inference) do double('Inference', prediction: double('Prediction', receipts: nil), pages: []) end @@ -15,7 +15,7 @@ end let(:empty_input_source) do - double('InputSource', count_pages: 0) + double('InputSource', page_count: 0) end let(:multi_receipts_single_page_path) do File.join(V1_DATA_DIR, 'products', 'multi_receipts_detector', 'default_sample.jpg') @@ -37,8 +37,8 @@ it 'splits receipts correctly' do input_sample = Mindee::Input::Source::PathInputSource.new(multi_receipts_single_page_path) response = load_json(multi_receipts_single_page_json_path, 'complete.json') - doc = Mindee::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1.new(response['document']['inference']) - extracted_receipts = Mindee::Extraction.extract_receipts(input_sample, doc) + doc = Mindee::V1::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1.new(response['document']['inference']) + extracted_receipts = Mindee::V1::Extraction.extract_receipts(input_sample, doc) expect(extracted_receipts.size).to eq(6) @@ -85,8 +85,8 @@ it 'splits receipts correctly' do input_sample = Mindee::Input::Source::PathInputSource.new(multi_receipts_multi_page_path) response = load_json(multi_receipts_multi_page_json_path, 'multipage_sample.json') - doc = Mindee::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1.new(response['document']['inference']) - extracted_receipts = Mindee::Extraction.extract_receipts(input_sample, doc) + doc = Mindee::V1::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1.new(response['document']['inference']) + extracted_receipts = Mindee::V1::Extraction.extract_receipts(input_sample, doc) expect(extracted_receipts.size).to eq(5) @@ -125,16 +125,16 @@ context 'when no receipts are found in inference' do it 'raises a MindeeInputError' do expect do - Mindee::Extraction.extract_receipts(empty_input_source, empty_inference) - end.to raise_error(Mindee::Errors::MindeeInputError, + Mindee::V1::Extraction.extract_receipts(empty_input_source, empty_inference) + end.to raise_error(Mindee::Error::MindeeInputError, 'No possible receipts candidates found for Multi-Receipts extraction.') end end context 'when input source has no pages' do it 'returns an empty array' do - extracted_receipts = Mindee::Extraction.extract_receipts(empty_input_source, - valid_inference_with_no_receipts) + extracted_receipts = Mindee::V1::Extraction.extract_receipts(empty_input_source, + valid_inference_with_no_receipts) expect(extracted_receipts).to eq([]) end end diff --git a/spec/v1/extras/cropper_extra_spec.rb b/spec/v1/extras/cropper_extra_spec.rb index 7d121b17b..f1a58d046 100644 --- a/spec/v1/extras/cropper_extra_spec.rb +++ b/spec/v1/extras/cropper_extra_spec.rb @@ -12,7 +12,7 @@ let(:complete_doc) do complete_doc_file = File.read(File.join(cropper_dir, 'complete.json')) complete_doc_json = JSON.parse(complete_doc_file) - Mindee::Parsing::Common::Document.new(Mindee::Product::Receipt::ReceiptV5, complete_doc_json['document']) + Mindee::V1::Parsing::Common::Document.new(Mindee::V1::Product::Receipt::ReceiptV5, complete_doc_json['document']) end describe 'cropper extra' do @@ -20,7 +20,7 @@ expect(complete_doc.inference.pages[0].extras.cropper.croppings.count).to eq(1) cropping = complete_doc.inference.pages[0].extras.cropper.croppings[0] - expect(cropping).to be_a Mindee::Parsing::Standard::PositionField + expect(cropping).to be_a Mindee::V1::Parsing::Standard::PositionField expect(cropping.bounding_box[0].x).to be_within(0.001).of(0.057) expect(cropping.bounding_box[0].y).to be_within(0.001).of(0.008) diff --git a/spec/v1/extras/extras_integration.rb b/spec/v1/extras/extras_integration.rb index fa296ca8f..4e92b7624 100644 --- a/spec/v1/extras/extras_integration.rb +++ b/spec/v1/extras/extras_integration.rb @@ -8,27 +8,27 @@ describe 'cropper extra' do let(:invoice_path) { File.join(V1_DATA_DIR, 'products', 'invoices', 'default_sample.jpg') } - let(:client) { Mindee::Client.new } + let(:client) { Mindee::V1::Client.new } it 'should send correctly' do cropper_extra = Mindee::Input::Source::PathInputSource.new( File.join(invoice_path) ) - cropper_result = client.parse(cropper_extra, Mindee::Product::Invoice::InvoiceV4, options: { cropper: true }, - enqueue: false) + cropper_result = client.parse(cropper_extra, Mindee::V1::Product::Invoice::InvoiceV4, options: { cropper: true }, + enqueue: false) expect(cropper_result.document.inference.pages[0].extras.cropper).to_not be_nil end end describe 'Full Text OCR extra' do let(:invoice_path) { File.join(V1_DATA_DIR, 'products', 'invoices', 'default_sample.jpg') } - let(:client) { Mindee::Client.new } + let(:client) { Mindee::V1::Client.new } it 'should send correctly' do full_text_ocr_input = Mindee::Input::Source::PathInputSource.new( File.join(invoice_path) ) full_text_ocr_result = client.parse( full_text_ocr_input, - Mindee::Product::InternationalId::InternationalIdV2, + Mindee::V1::Product::InternationalId::InternationalIdV2, options: { full_text: true } ) expect(full_text_ocr_result.document.extras.full_text_ocr).to_not be_nil diff --git a/spec/v1/extras/full_text_ocr_spec.rb b/spec/v1/extras/full_text_ocr_spec.rb index 706c8e5c4..b0ddaaa22 100644 --- a/spec/v1/extras/full_text_ocr_spec.rb +++ b/spec/v1/extras/full_text_ocr_spec.rb @@ -6,8 +6,8 @@ shared_context 'load pages' do let(:load_pages) do prediction_data = JSON.parse(File.read(File.join(EXTRAS_DIR, 'full_text_ocr', 'complete.json'))) - Mindee::Parsing::Common::ApiResponse.new( - Mindee::Product::InternationalId::InternationalIdV2, + Mindee::V1::Parsing::Common::ApiResponse.new( + Mindee::V1::Product::InternationalId::InternationalIdV2, prediction_data, prediction_data.to_json ).document.inference.pages @@ -17,8 +17,8 @@ shared_context 'load document' do let(:load_document) do prediction_data = JSON.parse(File.read(File.join(EXTRAS_DIR, 'full_text_ocr', 'complete.json'))) - Mindee::Parsing::Common::ApiResponse.new( - Mindee::Product::InternationalId::InternationalIdV2, + Mindee::V1::Parsing::Common::ApiResponse.new( + Mindee::V1::Product::InternationalId::InternationalIdV2, prediction_data, prediction_data.to_json ).document @@ -27,8 +27,8 @@ prediction_data = JSON.parse( File.read(File.join(V1_PRODUCT_DATA_DIR, 'bank_statement_fr', 'response_v2', 'complete.json')) ) - Mindee::Parsing::Common::ApiResponse.new( - Mindee::Product::FR::BankStatement::BankStatementV2, + Mindee::V1::Parsing::Common::ApiResponse.new( + Mindee::V1::Product::FR::BankStatement::BankStatementV2, prediction_data, prediction_data.to_json ).document @@ -137,8 +137,8 @@ 'extras' => {}, 'n_pages' => 0, } - built_doc = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::BankStatement::BankStatementV2, + built_doc = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::BankStatement::BankStatementV2, synthetic_response ) expect(built_doc.extras).to be_nil diff --git a/spec/v1/http/endpoint_spec.rb b/spec/v1/http/endpoint_spec.rb index 495c5ac61..03624f4d9 100644 --- a/spec/v1/http/endpoint_spec.rb +++ b/spec/v1/http/endpoint_spec.rb @@ -2,28 +2,34 @@ require 'mindee' -describe Mindee::HTTP::Endpoint do +describe Mindee::V1::HTTP::Endpoint do context 'An endpoint' do it 'should initialize' do - endpoint = Mindee::HTTP::Endpoint.new('mindee', 'blahblah', '3', - api_key: 'invalid-key') + endpoint = Mindee::V1::HTTP::Endpoint.new( + 'mindee', 'blahblah', '3', + api_key: 'invalid-key' + ) expect(endpoint.request_timeout).to eq(120) expect(endpoint.api_key).to eq('invalid-key') end it 'should have a default root url' do - endpoint = Mindee::HTTP::Endpoint.new('mindee', 'blahblah', '3', - api_key: 'invalid-key') - expect(endpoint.url_root).to eq("#{Mindee::HTTP::BASE_URL_DEFAULT}/products/mindee/blahblah/v3") + endpoint = Mindee::V1::HTTP::Endpoint.new( + 'mindee', 'blahblah', '3', + api_key: 'invalid-key' + ) + expect(endpoint.url_root).to eq("#{Mindee::V1::HTTP::BASE_URL_DEFAULT}/products/mindee/blahblah/v3") end it 'should have an editable root url' do - ENV[Mindee::HTTP::BASE_URL_ENV_NAME] = 'localhost:1234/my-fake-root-url' - endpoint = Mindee::HTTP::Endpoint.new('mindee', 'blahblah', '3', - api_key: 'invalid-key') - expect(endpoint.url_root).to_not eq(Mindee::HTTP::BASE_URL_DEFAULT) + ENV[Mindee::V1::HTTP::BASE_URL_ENV_NAME] = 'localhost:1234/my-fake-root-url' + endpoint = Mindee::V1::HTTP::Endpoint.new( + 'mindee', 'blahblah', '3', + api_key: 'invalid-key' + ) + expect(endpoint.url_root).to_not eq(Mindee::V1::HTTP::BASE_URL_DEFAULT) expect(endpoint.url_root).to eq('localhost:1234/my-fake-root-url/products/mindee/blahblah/v3') - ENV.delete(Mindee::HTTP::BASE_URL_ENV_NAME) + ENV.delete(Mindee::V1::HTTP::BASE_URL_ENV_NAME) end end end diff --git a/spec/v1/http/error_handler_integration.rb b/spec/v1/http/error_handler_integration.rb index d5761d1f8..edec057ec 100644 --- a/spec/v1/http/error_handler_integration.rb +++ b/spec/v1/http/error_handler_integration.rb @@ -7,31 +7,33 @@ describe Mindee::HTTP::ErrorHandler do context 'An HTTP call' do it 'should make an invalid API sync parse call raising an exception' do - mindee_client1 = Mindee::Client.new(api_key: 'invalid-api-key') - file = File.open("#{FILE_TYPES_DIR}/receipt.jpg", 'rb') - input_source = mindee_client1.source_from_file(file, 'receipt.jpg') - doc_class = Mindee::Product::Receipt::ReceiptV5 - expect do - mindee_client1.parse(input_source, doc_class, options: { all_words: false, close_file: true }) - end.to raise_error Mindee::Errors::MindeeHTTPClientError + mindee_client1 = Mindee::V1::Client.new(api_key: 'invalid-api-key') + File.open("#{FILE_TYPES_DIR}/receipt.jpg", 'rb') do |file| + input_source = mindee_client1.source_from_file(file, 'receipt.jpg') + doc_class = Mindee::V1::Product::Receipt::ReceiptV5 + expect do + mindee_client1.parse(input_source, doc_class, options: { all_words: false, close_file: true }) + end.to raise_error Mindee::Error::MindeeHTTPClientError + end end it 'should make an invalid API async enqueue call raising an exception' do - mindee_client1 = Mindee::Client.new(api_key: 'invalid-api-key') - file = File.open("#{V1_DATA_DIR}/products/invoice_splitter/default_sample.pdf", 'rb') - input_source = mindee_client1.source_from_file(file, 'default_sample.pdf') - doc_class = Mindee::Product::Invoice::InvoiceV4 - expect do - mindee_client1.enqueue(input_source, doc_class) - end.to raise_error Mindee::Errors::MindeeHTTPClientError + mindee_client1 = Mindee::V1::Client.new(api_key: 'invalid-api-key') + File.open("#{V1_DATA_DIR}/products/invoice_splitter/default_sample.pdf", 'rb') do |file| + input_source = mindee_client1.source_from_file(file, 'default_sample.pdf') + doc_class = Mindee::V1::Product::Invoice::InvoiceV4 + expect do + mindee_client1.enqueue(input_source, doc_class) + end.to raise_error Mindee::Error::MindeeHTTPClientError + end end it 'should make an invalid API async parse call raising an exception' do - mindee_client1 = Mindee::Client.new(api_key: 'invalid-api-key') - doc_class = Mindee::Product::InvoiceSplitter::InvoiceSplitterV1 + mindee_client1 = Mindee::V1::Client.new(api_key: 'invalid-api-key') + doc_class = Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1 expect do mindee_client1.parse_queued('invalid-job-id', doc_class) - end.to raise_error Mindee::Errors::MindeeHTTPClientError + end.to raise_error Mindee::Error::MindeeHTTPClientError end end end diff --git a/spec/v1/http/error_handler_spec.rb b/spec/v1/http/error_handler_spec.rb index 17157fd80..bfb792e5a 100644 --- a/spec/v1/http/error_handler_spec.rb +++ b/spec/v1/http/error_handler_spec.rb @@ -16,7 +16,7 @@ error400 = Mindee::HTTP::ErrorHandler.handle_error('dummy-url', error_obj) expect do raise error400 - end.to raise_error Mindee::Errors::MindeeHTTPClientError + end.to raise_error Mindee::Error::MindeeHTTPClientError expect(error400.status_code).to eq(400) expect(error400.api_code).to eq('SomeCode') expect(error400.api_message).to eq('Some scary message here') @@ -29,7 +29,7 @@ error401 = Mindee::HTTP::ErrorHandler.handle_error('dummy-url', error_obj) expect do raise error401 - end.to raise_error Mindee::Errors::MindeeHTTPClientError + end.to raise_error Mindee::Error::MindeeHTTPClientError expect(error401.status_code).to eq(401) expect(error401.api_code).to eq('Unauthorized') expect(error401.api_message).to eq('Authorization required') @@ -42,7 +42,7 @@ error429 = Mindee::HTTP::ErrorHandler.handle_error('dummy-url', error_obj) expect do raise error429 - end.to raise_error Mindee::Errors::MindeeHTTPClientError + end.to raise_error Mindee::Error::MindeeHTTPClientError expect(error429.status_code).to eq(429) expect(error429.api_code).to eq('TooManyRequests') expect(error429.api_message).to eq('Too many requests') @@ -55,7 +55,7 @@ error500 = Mindee::HTTP::ErrorHandler.handle_error('dummy-url', error_obj) expect do raise error500 - end.to raise_error Mindee::Errors::MindeeHTTPServerError + end.to raise_error Mindee::Error::MindeeHTTPServerError expect(error500.status_code).to eq(500) expect(error500.api_code).to eq('failure') expect(error500.api_message).to eq('Inference failed') @@ -68,7 +68,7 @@ error500 = Mindee::HTTP::ErrorHandler.handle_error('dummy-url', error_obj) expect do raise error500 - end.to raise_error Mindee::Errors::MindeeHTTPServerError + end.to raise_error Mindee::Error::MindeeHTTPServerError expect(error500.status_code).to eq(500) expect(error500.api_code).to eq('UnknownError') expect(error500.api_message).to eq('Server sent back an unexpected reply.') @@ -86,7 +86,7 @@ error500 = Mindee::HTTP::ErrorHandler.handle_error('dummy-url', error_obj) expect do raise error500 - end.to raise_error Mindee::Errors::MindeeHTTPServerError + end.to raise_error Mindee::Error::MindeeHTTPServerError expect(error500.status_code).to eq(500) expect(error500.api_code).to eq('ServerError') expect(error500.api_message).to eq('An error occurred') diff --git a/spec/v1/input/local_response_v1_spec.rb b/spec/v1/input/local_response_v1_spec.rb index abfad1a06..97f84b652 100644 --- a/spec/v1/input/local_response_v1_spec.rb +++ b/spec/v1/input/local_response_v1_spec.rb @@ -56,14 +56,14 @@ it 'should trigger an error when something invalid is passed' do expect do Mindee::Input::LocalResponse.new(123) - end.to raise_error Mindee::Errors::MindeeInputError + end.to raise_error Mindee::Error::MindeeInputError end it 'should trigger an error when the payload is not hashable' do local_response = Mindee::Input::LocalResponse.new('Your mother was a hamster.') expect do local_response.as_hash - end.to raise_error Mindee::Errors::MindeeInputError + end.to raise_error Mindee::Error::MindeeInputError end end end diff --git a/spec/v1/input/sources/url_input_source_integration.rb b/spec/v1/input/sources/url_input_source_integration.rb index 230ee0356..cf2f48477 100644 --- a/spec/v1/input/sources/url_input_source_integration.rb +++ b/spec/v1/input/sources/url_input_source_integration.rb @@ -1,9 +1,10 @@ # frozen_string_literal: true require 'mindee' +require 'tempfile' describe Mindee::Input::Source::URLInputSource do - let(:client) { Mindee::Client.new(api_key: ENV.fetch('MINDEE_API_KEY')) } + let(:client) { Mindee::V1::Client.new(api_key: ENV.fetch('MINDEE_API_KEY')) } it 'retrieves response from a remote file' do remote_input = Mindee::Input::Source::URLInputSource.new(ENV.fetch('MINDEE_V2_SE_TESTS_BLANK_PDF_URL')) @@ -11,7 +12,7 @@ local_input = remote_input.as_local_input_source expect(local_input.filename).to eq('blank_1.pdf') - result = client.parse(local_input, Mindee::Product::Invoice::InvoiceV4) + result = client.parse(local_input, Mindee::V1::Product::Invoice::InvoiceV4) expect(result.document.n_pages).to eq(1) end @@ -21,7 +22,7 @@ allow(Tempfile).to receive(:new).and_call_original allow(Tempfile).to receive(:create).and_call_original - result = client.parse(remote_input, Mindee::Product::Invoice::InvoiceV4) + result = client.parse(remote_input, Mindee::V1::Product::Invoice::InvoiceV4) expect(result.document.n_pages).to eq(1) expect(Tempfile).not_to have_received(:new) diff --git a/spec/v1/ocr_spec.rb b/spec/v1/ocr_spec.rb index 4119d0f89..be8c3cc20 100644 --- a/spec/v1/ocr_spec.rb +++ b/spec/v1/ocr_spec.rb @@ -1,17 +1,18 @@ # frozen_string_literal: true require 'json' -require 'mindee/parsing' +require 'mindee/v1/parsing' require_relative '../data' -describe Mindee::Parsing::Common do - include Mindee::Parsing::Common +describe Mindee::V1::Parsing::Common do + include Mindee::V1::Parsing::Common + context 'An OCR extraction' do json_data = load_json(V1_OCR_DIR, 'complete.json') it 'should extract ocr data from a document' do expected_text = read_file(V1_OCR_DIR, 'ocr.txt') - ocr = Mindee::Parsing::Common::OCR::OCR.new(json_data['document']['ocr']) + ocr = Mindee::V1::Parsing::Common::OCR::OCR.new(json_data['document']['ocr']) expect(ocr.to_s).to eq(expected_text) expect(ocr.mvision_v1.pages[0].to_s).to eq(expected_text) end diff --git a/spec/v1/parsing/standard/date_field_spec.rb b/spec/v1/parsing/standard/date_field_spec.rb index 2f7763e9a..f8f56851b 100644 --- a/spec/v1/parsing/standard/date_field_spec.rb +++ b/spec/v1/parsing/standard/date_field_spec.rb @@ -2,7 +2,7 @@ require 'mindee' -describe Mindee::Parsing::Standard::DateField do +describe Mindee::V1::Parsing::Standard::DateField do describe 'constructor with date' do let(:field_dict) do { @@ -19,7 +19,7 @@ end it 'sets value' do - field = Mindee::Parsing::Standard::DateField.new(field_dict, 0) + field = Mindee::V1::Parsing::Standard::DateField.new(field_dict, 0) expect(field.value).to eq('2018-04-01') expect(field.date_object).to be_a(Date) expect(field.is_computed).to be(true) @@ -35,7 +35,7 @@ end it 'sets no date' do - field = Mindee::Parsing::Standard::DateField.new(field_dict, 0) + field = Mindee::V1::Parsing::Standard::DateField.new(field_dict, 0) expect(field.value).to be_nil end end diff --git a/spec/v1/parsing/standard/string_field_spec.rb b/spec/v1/parsing/standard/string_field_spec.rb index 6363008d6..79e16ce14 100644 --- a/spec/v1/parsing/standard/string_field_spec.rb +++ b/spec/v1/parsing/standard/string_field_spec.rb @@ -2,7 +2,7 @@ require 'mindee' -describe Mindee::Parsing::Standard::StringField do +describe Mindee::V1::Parsing::Standard::StringField do describe 'constructor without raw_value' do let(:field_dict) do { @@ -18,7 +18,7 @@ end it 'sets value and raw_value to nil' do - field = Mindee::Parsing::Standard::StringField.new(field_dict) + field = Mindee::V1::Parsing::Standard::StringField.new(field_dict) expect(field.value).to eq('hello world') expect(field.raw_value).to be_nil end @@ -40,7 +40,7 @@ end it 'sets value and raw_value accordingly' do - field = Mindee::Parsing::Standard::StringField.new(field_dict) + field = Mindee::V1::Parsing::Standard::StringField.new(field_dict) expect(field.value).to eq('hello world') expect(field.raw_value).to eq('HelLO wOrld') end diff --git a/spec/v1/parsing/universal/universal_list_field_spec.rb b/spec/v1/parsing/universal/universal_list_field_spec.rb index eb8ff92e6..bf22515f3 100644 --- a/spec/v1/parsing/universal/universal_list_field_spec.rb +++ b/spec/v1/parsing/universal/universal_list_field_spec.rb @@ -2,7 +2,7 @@ require 'mindee' -describe Mindee::Parsing::Universal::UniversalListField do +describe Mindee::V1::Parsing::Universal::UniversalListField do let(:raw_prediction) { [{ 'value' => 'Item1' }, { 'value' => 'Item2' }] } subject(:universal_list_field) { described_class.new(raw_prediction) } diff --git a/spec/v1/parsing/universal/universal_object_field_spec.rb b/spec/v1/parsing/universal/universal_object_field_spec.rb index 22c1e4f95..41a98a8fc 100644 --- a/spec/v1/parsing/universal/universal_object_field_spec.rb +++ b/spec/v1/parsing/universal/universal_object_field_spec.rb @@ -2,7 +2,7 @@ require 'mindee' -describe Mindee::Parsing::Universal::UniversalObjectField do +describe Mindee::V1::Parsing::Universal::UniversalObjectField do let(:raw_prediction) do { 'page_id' => 3, @@ -71,7 +71,7 @@ it 'handles the position key by setting it as a PositionField instance' do position_field = object_field_with_rect.rectangle - expect(position_field).to be_a(Mindee::Parsing::Standard::PositionField) + expect(position_field).to be_a(Mindee::V1::Parsing::Standard::PositionField) end end diff --git a/spec/v1/product/barcode_reader_v1_spec.rb b/spec/v1/product/barcode_reader_v1_spec.rb index fa44de21d..55aa36092 100644 --- a/spec/v1/product/barcode_reader_v1_spec.rb +++ b/spec/v1/product/barcode_reader_v1_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../data' DIR_BARCODE_READER_V1 = File.join(V1_DATA_DIR, 'products', 'barcode_reader', 'response_v1').freeze -describe Mindee::Product::BarcodeReader::BarcodeReaderV1 do +describe Mindee::V1::Product::BarcodeReader::BarcodeReaderV1 do context 'A Barcode Reader V1' do it 'should load an empty document prediction' do response = load_json(DIR_BARCODE_READER_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::BarcodeReader::BarcodeReaderV1, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::BarcodeReader::BarcodeReaderV1, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_BARCODE_READER_V1, 'summary_full.rst') response = load_json(DIR_BARCODE_READER_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::BarcodeReader::BarcodeReaderV1, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::BarcodeReader::BarcodeReaderV1, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/bill_of_lading_v1_spec.rb b/spec/v1/product/bill_of_lading_v1_spec.rb deleted file mode 100644 index 0d1683557..000000000 --- a/spec/v1/product/bill_of_lading_v1_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../data' - -DIR_BILL_OF_LADING_V1 = File.join(V1_DATA_DIR, 'products', 'bill_of_lading', 'response_v1').freeze - -describe Mindee::Product::BillOfLading::BillOfLadingV1 do - context 'A Bill of Lading V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_BILL_OF_LADING_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::BillOfLading::BillOfLadingV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_BILL_OF_LADING_V1, 'summary_full.rst') - response = load_json(DIR_BILL_OF_LADING_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::BillOfLading::BillOfLadingV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/business_card_v1_spec.rb b/spec/v1/product/business_card_v1_spec.rb deleted file mode 100644 index afafb2e6f..000000000 --- a/spec/v1/product/business_card_v1_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../data' - -DIR_BUSINESS_CARD_V1 = File.join(V1_DATA_DIR, 'products', 'business_card', 'response_v1').freeze - -describe Mindee::Product::BusinessCard::BusinessCardV1 do - context 'A Business Card V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_BUSINESS_CARD_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::BusinessCard::BusinessCardV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_BUSINESS_CARD_V1, 'summary_full.rst') - response = load_json(DIR_BUSINESS_CARD_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::BusinessCard::BusinessCardV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/cropper_v1_spec.rb b/spec/v1/product/cropper_v1_spec.rb index bda490c3a..858dbcc4b 100644 --- a/spec/v1/product/cropper_v1_spec.rb +++ b/spec/v1/product/cropper_v1_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../data' DIR_CROPPER_V1 = File.join(V1_DATA_DIR, 'products', 'cropper', 'response_v1').freeze -describe Mindee::Product::Cropper::CropperV1 do +describe Mindee::V1::Product::Cropper::CropperV1 do context 'A Cropper V1' do it 'should load an empty document prediction' do response = load_json(DIR_CROPPER_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::Cropper::CropperV1, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Cropper::CropperV1, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_CROPPER_V1, 'summary_full.rst') response = load_json(DIR_CROPPER_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::Cropper::CropperV1, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Cropper::CropperV1, response['document'] ) expect(document.to_s).to eq(to_string) @@ -31,8 +31,8 @@ it 'should load a complete page 0 prediction' do to_string = read_file(DIR_CROPPER_V1, 'summary_page0.rst') response = load_json(DIR_CROPPER_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::Cropper::CropperV1, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Cropper::CropperV1, response['document'] ) page = document.inference.pages[0] diff --git a/spec/v1/product/delivery_note_v1_spec.rb b/spec/v1/product/delivery_note_v1_spec.rb deleted file mode 100644 index 329e92f16..000000000 --- a/spec/v1/product/delivery_note_v1_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../data' - -DIR_DELIVERY_NOTE_V1 = File.join(V1_DATA_DIR, 'products', 'delivery_notes', 'response_v1').freeze - -describe Mindee::Product::DeliveryNote::DeliveryNoteV1 do - context 'A Delivery note V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_DELIVERY_NOTE_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::DeliveryNote::DeliveryNoteV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_DELIVERY_NOTE_V1, 'summary_full.rst') - response = load_json(DIR_DELIVERY_NOTE_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::DeliveryNote::DeliveryNoteV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/driver_license_v1_spec.rb b/spec/v1/product/driver_license_v1_spec.rb deleted file mode 100644 index 40fd3d067..000000000 --- a/spec/v1/product/driver_license_v1_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../data' - -DIR_DRIVER_LICENSE_V1 = File.join(V1_DATA_DIR, 'products', 'driver_license', 'response_v1').freeze - -describe Mindee::Product::DriverLicense::DriverLicenseV1 do - context 'A Driver License V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_DRIVER_LICENSE_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::DriverLicense::DriverLicenseV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_DRIVER_LICENSE_V1, 'summary_full.rst') - response = load_json(DIR_DRIVER_LICENSE_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::DriverLicense::DriverLicenseV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/financial_document_v1_spec.rb b/spec/v1/product/financial_document_v1_spec.rb index ca83c7013..319676287 100644 --- a/spec/v1/product/financial_document_v1_spec.rb +++ b/spec/v1/product/financial_document_v1_spec.rb @@ -1,20 +1,22 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../data' DIR_FINANCIAL_DOCUMENT_V1 = File.join(V1_DATA_DIR, 'products', 'financial_document', 'response_v1').freeze -describe Mindee::Product::FinancialDocument::FinancialDocumentV1 do +describe Mindee::V1::Product::FinancialDocument::FinancialDocumentV1 do context 'A FinancialDocumentV1' do context 'when processing an invoice' do it 'should load an empty document prediction' do response = load_json(DIR_FINANCIAL_DOCUMENT_V1, 'empty.json') - document = Mindee::Parsing::Common::Document.new(Mindee::Product::FinancialDocument::FinancialDocumentV1, - response['document']) + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FinancialDocument::FinancialDocumentV1, + response['document'] + ) expect(document.inference.product.type).to eq('standard') prediction = document.inference.prediction expect(prediction.invoice_number.value).to be_nil @@ -47,8 +49,10 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_FINANCIAL_DOCUMENT_V1, 'summary_full_invoice.rst') response = load_json(DIR_FINANCIAL_DOCUMENT_V1, 'complete_invoice.json') - document = Mindee::Parsing::Common::Document.new(Mindee::Product::FinancialDocument::FinancialDocumentV1, - response['document']) + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FinancialDocument::FinancialDocumentV1, + response['document'] + ) prediction = document.inference.prediction expect(prediction.invoice_number.bounding_box.top_left.x).to eq(prediction.invoice_number.polygon[0][0]) expect(document.to_s).to eq(to_string) @@ -57,8 +61,10 @@ it 'should load a complete page 0 prediction' do to_string = read_file(DIR_FINANCIAL_DOCUMENT_V1, 'summary_page0_invoice.rst') response = load_json(DIR_FINANCIAL_DOCUMENT_V1, 'complete_invoice.json') - document = Mindee::Parsing::Common::Document.new(Mindee::Product::FinancialDocument::FinancialDocumentV1, - response['document']) + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FinancialDocument::FinancialDocumentV1, + response['document'] + ) page = document.inference.pages[0] expect(page.orientation.value).to eq(0) expect(page.prediction.due_date.page_id).to eq(0) @@ -69,8 +75,10 @@ context 'when processing a receipt' do it 'should load an empty document prediction' do response = load_json(DIR_FINANCIAL_DOCUMENT_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new(Mindee::Product::FinancialDocument::FinancialDocumentV1, - response['document']).inference + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FinancialDocument::FinancialDocumentV1, + response['document'] + ).inference expect(inference.product.type).to eq('standard') expect(inference.prediction.date.value).to be_nil expect(inference.prediction.date.page_id).to be_nil @@ -80,8 +88,10 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_FINANCIAL_DOCUMENT_V1, 'summary_full_receipt.rst') response = load_json(DIR_FINANCIAL_DOCUMENT_V1, 'complete_receipt.json') - document = Mindee::Parsing::Common::Document.new(Mindee::Product::FinancialDocument::FinancialDocumentV1, - response['document']) + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FinancialDocument::FinancialDocumentV1, + response['document'] + ) expect(document.inference.prediction.date.page_id).to eq(0) expect(document.to_s).to eq(to_string) end @@ -89,8 +99,10 @@ it 'should load a complete page 0 prediction' do to_string = read_file(DIR_FINANCIAL_DOCUMENT_V1, 'summary_page0_receipt.rst') response = load_json(DIR_FINANCIAL_DOCUMENT_V1, 'complete_receipt.json') - document = Mindee::Parsing::Common::Document.new(Mindee::Product::FinancialDocument::FinancialDocumentV1, - response['document']) + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FinancialDocument::FinancialDocumentV1, + response['document'] + ) page = document.inference.pages[0] expect(page.orientation.value).to eq(0) expect(page.prediction.date.page_id).to eq(0) diff --git a/spec/v1/product/fr/bank_account_details_v1_spec.rb b/spec/v1/product/fr/bank_account_details_v1_spec.rb index 4266d9df9..7afbb01d1 100644 --- a/spec/v1/product/fr/bank_account_details_v1_spec.rb +++ b/spec/v1/product/fr/bank_account_details_v1_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../../data' DIR_FR_BANK_ACCOUNT_DETAILS_V1 = File.join(V1_DATA_DIR, 'products', 'bank_account_details', 'response_v1').freeze -describe Mindee::Product::FR::BankAccountDetails::BankAccountDetailsV1 do +describe Mindee::V1::Product::FR::BankAccountDetails::BankAccountDetailsV1 do context 'A Bank Account Details V1' do it 'should load an empty document prediction' do response = load_json(DIR_FR_BANK_ACCOUNT_DETAILS_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::BankAccountDetails::BankAccountDetailsV1, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::BankAccountDetails::BankAccountDetailsV1, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_FR_BANK_ACCOUNT_DETAILS_V1, 'summary_full.rst') response = load_json(DIR_FR_BANK_ACCOUNT_DETAILS_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::BankAccountDetails::BankAccountDetailsV1, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::BankAccountDetails::BankAccountDetailsV1, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/fr/bank_account_details_v2_spec.rb b/spec/v1/product/fr/bank_account_details_v2_spec.rb index 15f9a2152..d9f57bfcc 100644 --- a/spec/v1/product/fr/bank_account_details_v2_spec.rb +++ b/spec/v1/product/fr/bank_account_details_v2_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../../data' DIR_FR_BANK_ACCOUNT_DETAILS_V2 = File.join(V1_DATA_DIR, 'products', 'bank_account_details', 'response_v2').freeze -describe Mindee::Product::FR::BankAccountDetails::BankAccountDetailsV2 do +describe Mindee::V1::Product::FR::BankAccountDetails::BankAccountDetailsV2 do context 'A Bank Account Details V2' do it 'should load an empty document prediction' do response = load_json(DIR_FR_BANK_ACCOUNT_DETAILS_V2, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::BankAccountDetails::BankAccountDetailsV2, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::BankAccountDetails::BankAccountDetailsV2, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_FR_BANK_ACCOUNT_DETAILS_V2, 'summary_full.rst') response = load_json(DIR_FR_BANK_ACCOUNT_DETAILS_V2, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::BankAccountDetails::BankAccountDetailsV2, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::BankAccountDetails::BankAccountDetailsV2, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/fr/bank_statement_v2_spec.rb b/spec/v1/product/fr/bank_statement_v2_spec.rb index 666b5ef5e..9e079cacf 100644 --- a/spec/v1/product/fr/bank_statement_v2_spec.rb +++ b/spec/v1/product/fr/bank_statement_v2_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../../data' DIR_FR_BANK_STATEMENT_V2 = File.join(V1_DATA_DIR, 'products', 'bank_statement_fr', 'response_v2').freeze -describe Mindee::Product::FR::BankStatement::BankStatementV2 do +describe Mindee::V1::Product::FR::BankStatement::BankStatementV2 do context 'A Bank Statement V2' do it 'should load an empty document prediction' do response = load_json(DIR_FR_BANK_STATEMENT_V2, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::BankStatement::BankStatementV2, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::BankStatement::BankStatementV2, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_FR_BANK_STATEMENT_V2, 'summary_full.rst') response = load_json(DIR_FR_BANK_STATEMENT_V2, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::BankStatement::BankStatementV2, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::BankStatement::BankStatementV2, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/fr/carte_grise_v1_spec.rb b/spec/v1/product/fr/carte_grise_v1_spec.rb deleted file mode 100644 index 0a94ec5ed..000000000 --- a/spec/v1/product/fr/carte_grise_v1_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../../data' - -DIR_FR_CARTE_GRISE_V1 = File.join(V1_DATA_DIR, 'products', 'carte_grise', 'response_v1').freeze - -describe Mindee::Product::FR::CarteGrise::CarteGriseV1 do - context 'A Carte Grise V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_FR_CARTE_GRISE_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::CarteGrise::CarteGriseV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_FR_CARTE_GRISE_V1, 'summary_full.rst') - response = load_json(DIR_FR_CARTE_GRISE_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::CarteGrise::CarteGriseV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/fr/energy_bill_v1_spec.rb b/spec/v1/product/fr/energy_bill_v1_spec.rb deleted file mode 100644 index ec9ae55bc..000000000 --- a/spec/v1/product/fr/energy_bill_v1_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../../data' - -DIR_FR_ENERGY_BILL_V1 = File.join(V1_DATA_DIR, 'products', 'energy_bill_fra', 'response_v1').freeze - -describe Mindee::Product::FR::EnergyBill::EnergyBillV1 do - context 'A Energy Bill V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_FR_ENERGY_BILL_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::EnergyBill::EnergyBillV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_FR_ENERGY_BILL_V1, 'summary_full.rst') - response = load_json(DIR_FR_ENERGY_BILL_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::EnergyBill::EnergyBillV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/fr/health_card_v1_spec.rb b/spec/v1/product/fr/health_card_v1_spec.rb deleted file mode 100644 index 5add26748..000000000 --- a/spec/v1/product/fr/health_card_v1_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../../data' - -DIR_FR_HEALTH_CARD_V1 = File.join(V1_DATA_DIR, 'products', 'french_healthcard', 'response_v1').freeze - -describe Mindee::Product::FR::HealthCard::HealthCardV1 do - context 'A Health Card V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_FR_HEALTH_CARD_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::HealthCard::HealthCardV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_FR_HEALTH_CARD_V1, 'summary_full.rst') - response = load_json(DIR_FR_HEALTH_CARD_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::HealthCard::HealthCardV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/fr/id_card_v1_spec.rb b/spec/v1/product/fr/id_card_v1_spec.rb index c73602e06..35bcaab36 100644 --- a/spec/v1/product/fr/id_card_v1_spec.rb +++ b/spec/v1/product/fr/id_card_v1_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../../data' DIR_FR_ID_CARD_V1 = File.join(V1_DATA_DIR, 'products', 'idcard_fr', 'response_v1').freeze -describe Mindee::Product::FR::IdCard::IdCardV1 do +describe Mindee::V1::Product::FR::IdCard::IdCardV1 do context 'A Carte Nationale d\'Identité V1' do it 'should load an empty document prediction' do response = load_json(DIR_FR_ID_CARD_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::IdCard::IdCardV1, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::IdCard::IdCardV1, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_FR_ID_CARD_V1, 'summary_full.rst') response = load_json(DIR_FR_ID_CARD_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::IdCard::IdCardV1, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::IdCard::IdCardV1, response['document'] ) expect(document.to_s).to eq(to_string) @@ -31,8 +31,8 @@ it 'should load a complete page 0 prediction' do to_string = read_file(DIR_FR_ID_CARD_V1, 'summary_page0.rst') response = load_json(DIR_FR_ID_CARD_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::IdCard::IdCardV1, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::IdCard::IdCardV1, response['document'] ) page = document.inference.pages[0] diff --git a/spec/v1/product/fr/id_card_v2_spec.rb b/spec/v1/product/fr/id_card_v2_spec.rb index db44a18d8..48e63ae37 100644 --- a/spec/v1/product/fr/id_card_v2_spec.rb +++ b/spec/v1/product/fr/id_card_v2_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../../data' DIR_FR_ID_CARD_V2 = File.join(V1_DATA_DIR, 'products', 'idcard_fr', 'response_v2').freeze -describe Mindee::Product::FR::IdCard::IdCardV2 do +describe Mindee::V1::Product::FR::IdCard::IdCardV2 do context 'A Carte Nationale d\'Identité V2' do it 'should load an empty document prediction' do response = load_json(DIR_FR_ID_CARD_V2, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::IdCard::IdCardV2, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::IdCard::IdCardV2, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_FR_ID_CARD_V2, 'summary_full.rst') response = load_json(DIR_FR_ID_CARD_V2, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::IdCard::IdCardV2, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::IdCard::IdCardV2, response['document'] ) expect(document.to_s).to eq(to_string) @@ -31,8 +31,8 @@ it 'should load a complete page 0 prediction' do to_string = read_file(DIR_FR_ID_CARD_V2, 'summary_page0.rst') response = load_json(DIR_FR_ID_CARD_V2, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::IdCard::IdCardV2, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::FR::IdCard::IdCardV2, response['document'] ) page = document.inference.pages[0] diff --git a/spec/v1/product/fr/payslip_v3_spec.rb b/spec/v1/product/fr/payslip_v3_spec.rb deleted file mode 100644 index a9d179562..000000000 --- a/spec/v1/product/fr/payslip_v3_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../../data' - -DIR_FR_PAYSLIP_V3 = File.join(V1_DATA_DIR, 'products', 'payslip_fra', 'response_v3').freeze - -describe Mindee::Product::FR::Payslip::PayslipV3 do - context 'A Payslip V3' do - it 'should load an empty document prediction' do - response = load_json(DIR_FR_PAYSLIP_V3, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::Payslip::PayslipV3, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_FR_PAYSLIP_V3, 'summary_full.rst') - response = load_json(DIR_FR_PAYSLIP_V3, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::FR::Payslip::PayslipV3, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/ind/indian_passport_v1_spec.rb b/spec/v1/product/ind/indian_passport_v1_spec.rb deleted file mode 100644 index 65d44bdd6..000000000 --- a/spec/v1/product/ind/indian_passport_v1_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../../data' - -DIR_IND_INDIAN_PASSPORT_V1 = File.join(V1_DATA_DIR, 'products', 'ind_passport', 'response_v1').freeze - -describe Mindee::Product::IND::IndianPassport::IndianPassportV1 do - context 'A Passport - India V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_IND_INDIAN_PASSPORT_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::IND::IndianPassport::IndianPassportV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_IND_INDIAN_PASSPORT_V1, 'summary_full.rst') - response = load_json(DIR_IND_INDIAN_PASSPORT_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::IND::IndianPassport::IndianPassportV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/international_id_v2_spec.rb b/spec/v1/product/international_id_v2_spec.rb index 6e4e3bf7d..dfd58b855 100644 --- a/spec/v1/product/international_id_v2_spec.rb +++ b/spec/v1/product/international_id_v2_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../data' DIR_INTERNATIONAL_ID_V2 = File.join(V1_DATA_DIR, 'products', 'international_id', 'response_v2').freeze -describe Mindee::Product::InternationalId::InternationalIdV2 do +describe Mindee::V1::Product::InternationalId::InternationalIdV2 do context 'A International ID V2' do it 'should load an empty document prediction' do response = load_json(DIR_INTERNATIONAL_ID_V2, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::InternationalId::InternationalIdV2, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::InternationalId::InternationalIdV2, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_INTERNATIONAL_ID_V2, 'summary_full.rst') response = load_json(DIR_INTERNATIONAL_ID_V2, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::InternationalId::InternationalIdV2, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::InternationalId::InternationalIdV2, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/invoice_splitter_v1_spec.rb b/spec/v1/product/invoice_splitter_v1_spec.rb index 2b9e889bd..105fd6fcf 100644 --- a/spec/v1/product/invoice_splitter_v1_spec.rb +++ b/spec/v1/product/invoice_splitter_v1_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../data' DIR_INVOICE_SPLITTER_V1 = File.join(V1_DATA_DIR, 'products', 'invoice_splitter', 'response_v1').freeze -describe Mindee::Product::InvoiceSplitter::InvoiceSplitterV1 do +describe Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1 do context 'A Invoice Splitter V1' do it 'should load an empty document prediction' do response = load_json(DIR_INVOICE_SPLITTER_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_INVOICE_SPLITTER_V1, 'summary_full.rst') response = load_json(DIR_INVOICE_SPLITTER_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::InvoiceSplitter::InvoiceSplitterV1, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::InvoiceSplitter::InvoiceSplitterV1, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/invoice_v4_spec.rb b/spec/v1/product/invoice_v4_spec.rb index 9c7278401..7da88bddd 100644 --- a/spec/v1/product/invoice_v4_spec.rb +++ b/spec/v1/product/invoice_v4_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../data' DIR_INVOICE_V4 = File.join(V1_DATA_DIR, 'products', 'invoices', 'response_v4').freeze -describe Mindee::Product::Invoice::InvoiceV4 do +describe Mindee::V1::Product::Invoice::InvoiceV4 do context 'A Invoice V4' do it 'should load an empty document prediction' do response = load_json(DIR_INVOICE_V4, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::Invoice::InvoiceV4, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Invoice::InvoiceV4, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_INVOICE_V4, 'summary_full.rst') response = load_json(DIR_INVOICE_V4, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::Invoice::InvoiceV4, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Invoice::InvoiceV4, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/multi_receipts_detector_v1_spec.rb b/spec/v1/product/multi_receipts_detector_v1_spec.rb index dce0041ee..75aecd79a 100644 --- a/spec/v1/product/multi_receipts_detector_v1_spec.rb +++ b/spec/v1/product/multi_receipts_detector_v1_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../data' DIR_MULTI_RECEIPTS_DETECTOR_V1 = File.join(V1_DATA_DIR, 'products', 'multi_receipts_detector', 'response_v1').freeze -describe Mindee::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1 do +describe Mindee::V1::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1 do context 'A Multi Receipts Detector V1' do it 'should load an empty document prediction' do response = load_json(DIR_MULTI_RECEIPTS_DETECTOR_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_MULTI_RECEIPTS_DETECTOR_V1, 'summary_full.rst') response = load_json(DIR_MULTI_RECEIPTS_DETECTOR_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::MultiReceiptsDetector::MultiReceiptsDetectorV1, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/nutrition_facts_label_v1_spec.rb b/spec/v1/product/nutrition_facts_label_v1_spec.rb deleted file mode 100644 index 910df0a99..000000000 --- a/spec/v1/product/nutrition_facts_label_v1_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../data' - -DIR_NUTRITION_FACTS_LABEL_V1 = File.join(V1_DATA_DIR, 'products', 'nutrition_facts', 'response_v1').freeze - -describe Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1 do - context 'A Nutrition Facts Label V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_NUTRITION_FACTS_LABEL_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_NUTRITION_FACTS_LABEL_V1, 'summary_full.rst') - response = load_json(DIR_NUTRITION_FACTS_LABEL_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::NutritionFactsLabel::NutritionFactsLabelV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/passport_v1_spec.rb b/spec/v1/product/passport_v1_spec.rb index 2bf0b5e4d..0d69e0a56 100644 --- a/spec/v1/product/passport_v1_spec.rb +++ b/spec/v1/product/passport_v1_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../data' DIR_PASSPORT_V1 = File.join(V1_DATA_DIR, 'products', 'passport', 'response_v1').freeze -describe Mindee::Product::Passport::PassportV1 do +describe Mindee::V1::Product::Passport::PassportV1 do context 'A Passport V1' do it 'should load an empty document prediction' do response = load_json(DIR_PASSPORT_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::Passport::PassportV1, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Passport::PassportV1, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_PASSPORT_V1, 'summary_full.rst') response = load_json(DIR_PASSPORT_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::Passport::PassportV1, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Passport::PassportV1, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/receipt_v5_spec.rb b/spec/v1/product/receipt_v5_spec.rb index 9153c5b79..ec0ba325f 100644 --- a/spec/v1/product/receipt_v5_spec.rb +++ b/spec/v1/product/receipt_v5_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../data' DIR_RECEIPT_V5 = File.join(V1_DATA_DIR, 'products', 'expense_receipts', 'response_v5').freeze -describe Mindee::Product::Receipt::ReceiptV5 do +describe Mindee::V1::Product::Receipt::ReceiptV5 do context 'A Receipt V5' do it 'should load an empty document prediction' do response = load_json(DIR_RECEIPT_V5, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::Receipt::ReceiptV5, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Receipt::ReceiptV5, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_RECEIPT_V5, 'summary_full.rst') response = load_json(DIR_RECEIPT_V5, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::Receipt::ReceiptV5, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Receipt::ReceiptV5, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/resume_v1_spec.rb b/spec/v1/product/resume_v1_spec.rb index dce4c9b49..eee2ba71b 100644 --- a/spec/v1/product/resume_v1_spec.rb +++ b/spec/v1/product/resume_v1_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'json' -require 'mindee/product' -require 'mindee/parsing' +require 'mindee/v1/product' +require 'mindee/v1/parsing' require_relative '../../data' DIR_RESUME_V1 = File.join(V1_DATA_DIR, 'products', 'resume', 'response_v1').freeze -describe Mindee::Product::Resume::ResumeV1 do +describe Mindee::V1::Product::Resume::ResumeV1 do context 'A Resume V1' do it 'should load an empty document prediction' do response = load_json(DIR_RESUME_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::Resume::ResumeV1, + inference = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Resume::ResumeV1, response['document'] ).inference expect(inference.product.type).to eq('standard') @@ -22,8 +22,8 @@ it 'should load a complete document prediction' do to_string = read_file(DIR_RESUME_V1, 'summary_full.rst') response = load_json(DIR_RESUME_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::Resume::ResumeV1, + document = Mindee::V1::Parsing::Common::Document.new( + Mindee::V1::Product::Resume::ResumeV1, response['document'] ) expect(document.to_s).to eq(to_string) diff --git a/spec/v1/product/universal_spec.rb b/spec/v1/product/universal_spec.rb index 99c39ad59..178ce4729 100644 --- a/spec/v1/product/universal_spec.rb +++ b/spec/v1/product/universal_spec.rb @@ -5,13 +5,13 @@ require_relative '../../data' -StringField = Mindee::Parsing::Standard.const_get(:StringField) -PositionField = Mindee::Parsing::Standard.const_get(:PositionField) -UniversalListField = Mindee::Parsing::Universal.const_get(:UniversalListField) -UniversalObjectField = Mindee::Parsing::Universal.const_get(:UniversalObjectField) -Universal = Mindee::Product::Universal.const_get(:Universal) -UniversalPage = Mindee::Product::Universal.const_get(:UniversalPage) -Document = Mindee::Parsing::Common.const_get(:Document) +StringField = Mindee::V1::Parsing::Standard.const_get(:StringField) +PositionField = Mindee::V1::Parsing::Standard.const_get(:PositionField) +UniversalListField = Mindee::V1::Parsing::Universal.const_get(:UniversalListField) +UniversalObjectField = Mindee::V1::Parsing::Universal.const_get(:UniversalObjectField) +Universal = Mindee::V1::Product::Universal.const_get(:Universal) +UniversalPage = Mindee::V1::Product::Universal.const_get(:UniversalPage) +Document = Mindee::V1::Parsing::Common.const_get(:Document) describe 'International ID v1 document' do let(:international_id_v1_complete_doc) do diff --git a/spec/v1/product/us/bank_check_v1_spec.rb b/spec/v1/product/us/bank_check_v1_spec.rb deleted file mode 100644 index a0d8cc97d..000000000 --- a/spec/v1/product/us/bank_check_v1_spec.rb +++ /dev/null @@ -1,42 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../../data' - -DIR_US_BANK_CHECK_V1 = File.join(V1_DATA_DIR, 'products', 'bank_check', 'response_v1').freeze - -describe Mindee::Product::US::BankCheck::BankCheckV1 do - context 'A Bank Check V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_US_BANK_CHECK_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::US::BankCheck::BankCheckV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_US_BANK_CHECK_V1, 'summary_full.rst') - response = load_json(DIR_US_BANK_CHECK_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::US::BankCheck::BankCheckV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - it 'should load a complete page 0 prediction' do - to_string = read_file(DIR_US_BANK_CHECK_V1, 'summary_page0.rst') - response = load_json(DIR_US_BANK_CHECK_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::US::BankCheck::BankCheckV1, - response['document'] - ) - page = document.inference.pages[0] - expect(page.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/us/healthcare_card_v1_spec.rb b/spec/v1/product/us/healthcare_card_v1_spec.rb deleted file mode 100644 index f544aaec7..000000000 --- a/spec/v1/product/us/healthcare_card_v1_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../../data' - -DIR_US_HEALTHCARE_CARD_V1 = File.join(V1_DATA_DIR, 'products', 'us_healthcare_cards', 'response_v1').freeze - -describe Mindee::Product::US::HealthcareCard::HealthcareCardV1 do - context 'A Healthcare Card V1' do - it 'should load an empty document prediction' do - response = load_json(DIR_US_HEALTHCARE_CARD_V1, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::US::HealthcareCard::HealthcareCardV1, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_US_HEALTHCARE_CARD_V1, 'summary_full.rst') - response = load_json(DIR_US_HEALTHCARE_CARD_V1, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::US::HealthcareCard::HealthcareCardV1, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/product/us/us_mail_v3_spec.rb b/spec/v1/product/us/us_mail_v3_spec.rb deleted file mode 100644 index 6730c75ff..000000000 --- a/spec/v1/product/us/us_mail_v3_spec.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -require 'json' -require 'mindee/product' -require 'mindee/parsing' - -require_relative '../../../data' - -DIR_US_US_MAIL_V3 = File.join(V1_DATA_DIR, 'products', 'us_mail', 'response_v3').freeze - -describe Mindee::Product::US::UsMail::UsMailV3 do - context 'A US Mail V3' do - it 'should load an empty document prediction' do - response = load_json(DIR_US_US_MAIL_V3, 'empty.json') - inference = Mindee::Parsing::Common::Document.new( - Mindee::Product::US::UsMail::UsMailV3, - response['document'] - ).inference - expect(inference.product.type).to eq('standard') - end - - it 'should load a complete document prediction' do - to_string = read_file(DIR_US_US_MAIL_V3, 'summary_full.rst') - response = load_json(DIR_US_US_MAIL_V3, 'complete.json') - document = Mindee::Parsing::Common::Document.new( - Mindee::Product::US::UsMail::UsMailV3, - response['document'] - ) - expect(document.to_s).to eq(to_string) - end - end -end diff --git a/spec/v1/workflow/workflow_integration.rb b/spec/v1/workflow/workflow_integration.rb index 6bbe76a35..2cd4afaac 100644 --- a/spec/v1/workflow/workflow_integration.rb +++ b/spec/v1/workflow/workflow_integration.rb @@ -4,9 +4,9 @@ require 'mindee' require_relative '../../data' -describe Mindee::Client do +describe Mindee::V1::Client do describe 'execute_workflow call to API' do - let(:client) { Mindee::Client.new } + let(:client) { Mindee::V1::Client.new } let(:sample_input) do Mindee::Input::Source::PathInputSource.new( File.join(V1_PRODUCT_DATA_DIR, 'financial_document', 'default_sample.jpg') @@ -16,7 +16,7 @@ it 'should return a valid response' do current_date_time = Time.now.strftime('%Y-%m-%d-%H:%M:%S') document_alias = "ruby-#{current_date_time}" - priority = Mindee::Parsing::Common::ExecutionPriority::LOW + priority = Mindee::V1::Parsing::Common::ExecutionPriority::LOW response = client.execute_workflow( sample_input, @@ -33,7 +33,7 @@ options = { workflow_id: workflow_id, rag: true } response = client.parse( sample_input, - Mindee::Product::FinancialDocument::FinancialDocumentV1, + Mindee::V1::Product::FinancialDocument::FinancialDocumentV1, options: options ) expect(response.document.to_s).to_not be_empty @@ -44,7 +44,7 @@ options = { workflow_id: workflow_id } response = client.parse( sample_input, - Mindee::Product::FinancialDocument::FinancialDocumentV1, + Mindee::V1::Product::FinancialDocument::FinancialDocumentV1, options: options ) expect(response.document.to_s).to_not be_empty diff --git a/spec/v1/workflow/workflow_spec.rb b/spec/v1/workflow/workflow_spec.rb index f05ae4cde..62965e6b3 100644 --- a/spec/v1/workflow/workflow_spec.rb +++ b/spec/v1/workflow/workflow_spec.rb @@ -4,7 +4,7 @@ require 'mindee' require_relative '../../data' -describe Mindee::Client do +describe Mindee::V1::Client do describe 'execute_workflow' do it 'should deserialize response correctly when sending a document to an execution' do json_file_path = "#{V1_DATA_DIR}/workflows/success.json" @@ -14,7 +14,7 @@ allow(Net::HTTP).to receive(:start).and_return(mocked_response) - mocked_execution = Mindee::Parsing::Common::WorkflowResponse.new( + mocked_execution = Mindee::V1::Parsing::Common::WorkflowResponse.new( Universal, JSON.parse(mocked_response.body, object_class: Hash), mocked_response.body @@ -46,7 +46,7 @@ allow(Net::HTTP).to receive(:start).and_return(mocked_response) - mocked_execution = Mindee::Parsing::Common::WorkflowResponse.new( + mocked_execution = Mindee::V1::Parsing::Common::WorkflowResponse.new( Universal, JSON.parse(mocked_response.body, object_class: Hash), mocked_response.body diff --git a/spec/v2/client_v2_integration.rb b/spec/v2/client_v2_integration.rb index 598a72b94..8cda5f3cd 100644 --- a/spec/v2/client_v2_integration.rb +++ b/spec/v2/client_v2_integration.rb @@ -1,13 +1,17 @@ # frozen_string_literal: true require 'mindee' +require 'mindee/v2/product' -describe 'Mindee::ClientV2 – integration tests (V2)', :integration, order: :defined do +using Mindee::V2::Product::Extraction::Params +using Mindee::V2::Product::Extraction + +describe 'Mindee::V2::Client – integration tests (V2)', :integration, order: :defined do let(:api_key) { ENV.fetch('MINDEE_V2_API_KEY') } - let(:model_id) { ENV.fetch('MINDEE_V2_FINDOC_MODEL_ID') } + let(:model_id) { ENV.fetch('MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID') } let(:blank_pdf_url) { ENV.fetch('MINDEE_V2_SE_TESTS_BLANK_PDF_URL') } - let(:client) { Mindee::ClientV2.new(api_key: api_key) } + let(:client) { Mindee::V2::Client.new(api_key: api_key) } context 'An input file' do it 'parses an empty multi-page PDF successfully' do src_path = File.join(FILE_TYPES_DIR, 'pdf', 'multipage_cut-2.pdf') @@ -19,7 +23,7 @@ max_retries: 80 ) - inference_params = Mindee::Input::InferenceParameters.new( + inference_params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( model_id, rag: false, raw_text: true, @@ -30,25 +34,25 @@ text_context: 'this is a test' ) - response = client.enqueue_and_get_inference(input, inference_params) + response = client.enqueue_and_get_result(Mindee::V2::Product::Extraction::Extraction, input, inference_params) expect(response).not_to be_nil expect(response.inference).not_to be_nil file = response.inference.file expect(file).not_to be_nil - expect(file).to be_a(Mindee::Parsing::V2::InferenceFile) + expect(file).to be_a(Mindee::V2::Parsing::InferenceFile) expect(file.name).to eq('multipage_cut-2.pdf') expect(file.page_count).to eq(2) model = response.inference.model expect(model).not_to be_nil - expect(model).to be_a(Mindee::Parsing::V2::InferenceModel) + expect(model).to be_a(Mindee::V2::Parsing::InferenceModel) expect(model.id).to eq(model_id) active_options = response.inference.active_options expect(active_options).not_to be_nil - expect(active_options).to be_a(Mindee::Parsing::V2::InferenceActiveOptions) + expect(active_options).to be_a(Mindee::V2::Parsing::InferenceActiveOptions) expect(active_options.raw_text).to eq(true) expect(active_options.polygon).to eq(false) expect(active_options.confidence).to eq(false) @@ -68,7 +72,7 @@ src_path = File.join(V1_PRODUCT_DATA_DIR, 'financial_document', 'default_sample.jpg') input = Mindee::Input::Source::FileInputSource.new(File.open(src_path, 'rb'), 'default_sample.jpg') - inference_params = Mindee::Input::InferenceParameters.new( + inference_params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( model_id, raw_text: false, polygon: false, @@ -77,23 +81,23 @@ file_alias: 'rb_integration_test' ) - response = client.enqueue_and_get_inference(input, inference_params) + response = client.enqueue_and_get_result(Mindee::V2::Product::Extraction::Extraction, input, inference_params) expect(response).not_to be_nil file = response.inference.file expect(file).not_to be_nil - expect(file).to be_a(Mindee::Parsing::V2::InferenceFile) + expect(file).to be_a(Mindee::V2::Parsing::InferenceFile) expect(file.name).to eq('default_sample.jpg') expect(file.page_count).to eq(1) model = response.inference.model expect(model).not_to be_nil - expect(model).to be_a(Mindee::Parsing::V2::InferenceModel) + expect(model).to be_a(Mindee::V2::Parsing::InferenceModel) expect(model.id).to eq(model_id) active_options = response.inference.active_options expect(active_options).not_to be_nil - expect(active_options).to be_a(Mindee::Parsing::V2::InferenceActiveOptions) + expect(active_options).to be_a(Mindee::V2::Parsing::InferenceActiveOptions) expect(active_options.raw_text).to eq(false) expect(active_options.polygon).to eq(false) expect(active_options.confidence).to eq(false) @@ -116,25 +120,25 @@ src_path = File.join(FILE_TYPES_DIR, 'pdf', 'blank_1.pdf') input = Mindee::Input::Source::FileInputSource.new(File.open(src_path, 'rb'), 'blank_1.pdf') - inference_params = Mindee::Input::InferenceParameters.new('INVALID_MODEL_ID') + inference_params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new('INVALID_MODEL_ID') expect do - client.enqueue_inference(input, inference_params) - end.to raise_error(Mindee::Errors::MindeeHTTPErrorV2) { |e| expect(e.status).to eq(422) } + client.enqueue(Mindee::V2::Product::Extraction::Extraction, input, inference_params) + end.to raise_error(Mindee::Error::MindeeHTTPErrorV2) { |e| expect(e.status).to eq(422) } end it 'raises MindeeHTTPErrorV2 (422) on invalid webhook id' do src_path = File.join(FILE_TYPES_DIR, 'pdf', 'blank_1.pdf') input = Mindee::Input::Source::FileInputSource.new(File.open(src_path, 'rb'), 'blank_1.pdf') - params = Mindee::Input::InferenceParameters.new( + params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( model_id, webhook_ids: ['INVALID_WEBHOOK_ID'] ) expect do - client.enqueue_inference(input, params) - end.to raise_error(Mindee::Errors::MindeeHTTPErrorV2) { |e| + client.enqueue(Mindee::V2::Product::Extraction::Extraction, input, params) + end.to raise_error(Mindee::Error::MindeeHTTPErrorV2) { |e| expect(e.status).to eq(422) expect(e.code).to start_with('422-') expect(e.detail).to_not be_nil @@ -148,28 +152,28 @@ src_path = File.join(FILE_TYPES_DIR, 'pdf', 'blank_1.pdf') input = Mindee::Input::Source::FileInputSource.new(File.open(src_path, 'rb'), 'blank_1.pdf') - inference_params = Mindee::Input::InferenceParameters.new( + inference_params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( model_id, webhook_ids: ['fc405e37-4ba4-4d03-aeba-533a8d1f0f21', 'fc405e37-4ba4-4d03-aeba-533a8d1f0f21'] ) expect do - client.enqueue_inference(input, inference_params) - end.to raise_error(Mindee::Errors::MindeeHTTPErrorV2) { |e| + client.enqueue(Mindee::V2::Product::Extraction::Extraction, input, inference_params) + end.to raise_error(Mindee::Error::MindeeHTTPErrorV2) { |e| expect(e.status).to eq(422) expect(e.code).to start_with('422-') expect(e.detail).to_not be_nil expect(e.title).to_not be_nil expect(e.errors).to be_an_instance_of(Array) expect(e.errors.count).to be_positive - expect(e.errors[0]).to be_an_instance_of(Mindee::Parsing::V2::ErrorItem) + expect(e.errors[0]).to be_an_instance_of(Mindee::V2::Parsing::ErrorItem) } end it 'raises MindeeHTTPErrorV2 on invalid job id' do expect do - client.get_inference('INVALID_JOB_ID') - end.to raise_error(Mindee::Errors::MindeeHTTPErrorV2) { |e| + client.get_result(Mindee::V2::Product::Extraction::Extraction, 'INVALID_JOB_ID') + end.to raise_error(Mindee::Error::MindeeHTTPErrorV2) { |e| expect(e.status).to eq(422) expect(e.code).to start_with('422-') expect(e.detail).to_not be_nil @@ -187,7 +191,7 @@ 'default_sample.jpg' ) - inference_params = Mindee::Input::InferenceParameters.new( + inference_params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( 'fc405e37-4ba4-4d03-aeba-533a8d1f0f21', raw_text: false, polygon: false, @@ -195,8 +199,8 @@ rag: false, file_alias: 'rb_integration_test' ) - client.enqueue_and_get_inference(input, inference_params) - end.to raise_error(Mindee::Errors::MindeeHTTPErrorV2) { |e| + client.enqueue_and_get_result(Mindee::V2::Product::Extraction::Extraction, input, inference_params) + end.to raise_error(Mindee::Error::MindeeHTTPErrorV2) { |e| expect(e.status).to eq(404) expect(e.code).to start_with('404-') expect(e.detail).to_not be_nil @@ -210,9 +214,9 @@ it 'parses an URL input source without errors' do url_input = Mindee::Input::Source::URLInputSource.new(blank_pdf_url) - inference_params = Mindee::Input::InferenceParameters.new(model_id) + inference_params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new(model_id) - response = client.enqueue_and_get_inference(url_input, inference_params) + response = client.enqueue_and_get_result(Mindee::V2::Product::Extraction::Extraction, url_input, inference_params) expect(response).not_to be_nil expect(response.inference).not_to be_nil @@ -225,7 +229,7 @@ 'data_schema_replace_param.json')) input = Mindee::Input::Source::PathInputSource.new(File.join(FILE_TYPES_DIR, 'pdf', 'blank_1.pdf')) - inference_params = Mindee::Input::InferenceParameters.new( + inference_params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( model_id, raw_text: false, polygon: false, @@ -235,17 +239,17 @@ data_schema: data_schema_replace ) - response = client.enqueue_and_get_inference(input, inference_params) + response = client.enqueue_and_get_result(Mindee::V2::Product::Extraction::Extraction, input, inference_params) expect(response).not_to be_nil model = response.inference.model expect(model).not_to be_nil - expect(model).to be_a(Mindee::Parsing::V2::InferenceModel) + expect(model).to be_a(Mindee::V2::Parsing::InferenceModel) expect(model.id).to eq(model_id) active_options = response.inference.active_options expect(active_options).not_to be_nil - expect(active_options).to be_a(Mindee::Parsing::V2::InferenceActiveOptions) + expect(active_options).to be_a(Mindee::V2::Parsing::InferenceActiveOptions) expect(active_options.raw_text).to eq(false) expect(active_options.polygon).to eq(false) expect(active_options.confidence).to eq(false) diff --git a/spec/v2/client_v2_spec.rb b/spec/v2/client_v2_spec.rb index 57c3c2fa0..67236dcbd 100644 --- a/spec/v2/client_v2_spec.rb +++ b/spec/v2/client_v2_spec.rb @@ -2,16 +2,20 @@ require 'json' require 'mindee' +require 'mindee/v2/product' require_relative '../http/mock_http_response' # <- the original helper -describe Mindee::ClientV2 do +using Mindee::V2::Product::Extraction::Params +using Mindee::V2::Product::Extraction + +describe Mindee::V2::Client do let(:input_doc) { Mindee::Input::Source::PathInputSource.new(File.join(FILE_TYPES_DIR, 'pdf', 'blank.pdf')) } let(:base_url) { 'https://dummy-url' } let(:api_key) { 'dummy-api-key' } let(:client) do ENV['MINDEE_V2_BASE_URL'] = 'https://dummy-url' - Mindee::ClientV2.new(api_key: api_key) + Mindee::V2::Client.new(api_key: api_key) end let(:api) do client.instance_variable_get(:@mindee_api) @@ -30,7 +34,7 @@ def build_mock_http_response(hash, status_code = 400, status_msg = 'Bad Request' def stub_next_request_with(method, hash:, status_code: 0) fake_response = build_mock_http_response(hash, status_code) - allow_any_instance_of(Mindee::HTTP::MindeeApiV2) + allow_any_instance_of(Mindee::V2::HTTP::MindeeApiV2) .to receive(method) .and_return(fake_response) end @@ -45,13 +49,13 @@ def stub_next_request_with(method, hash:, status_code: 0) it 'enqueue(path) raises MindeeHTTPErrorV2 on 4xx' do expect do stub_next_request_with(:enqueue, hash: JSON.generate(json400)) - inference_params = Mindee::Input::InferenceParameters.new( + params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( 'dummy-model', raw_text: false, text_context: 'Hello my name is mud.' ) - client.enqueue_inference(input_doc, inference_params) - end.to raise_error(Mindee::Errors::MindeeHTTPErrorV2) { |e| + client.enqueue(Mindee::V2::Product::Extraction::Extraction, input_doc, params) + end.to raise_error(Mindee::Error::MindeeHTTPErrorV2) { |e| expect(e.status).to eq(400) expect(e.detail).to eq('Unsupported content.') } @@ -60,22 +64,22 @@ def stub_next_request_with(method, hash:, status_code: 0) it 'enqueue_and_get_inference(path) raises MindeeHTTPErrorV2 on 4xx' do expect do stub_next_request_with(:enqueue, hash: JSON.generate(json400)) - inference_params = Mindee::Input::InferenceParameters.new('dummy-model') - client.enqueue_and_get_inference(input_doc, inference_params) - end.to raise_error(Mindee::Errors::MindeeHTTPErrorV2) { |e| + params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new('dummy-model') + client.enqueue_and_get_result(Mindee::V2::Product::Extraction::Extraction, input_doc, params) + end.to raise_error(Mindee::Error::MindeeHTTPErrorV2) { |e| expect(e.status).to eq(400) expect(e.detail).to eq('Unsupported content.') } end - it 'bubbles-up HTTP errors with details' do + it 'bubbles-up HTTP error with details' do error_hash = json400.merge({ status: 413, detail: 'File exceeds size limit' }) expect do stub_next_request_with(:enqueue, hash: JSON.generate(error_hash)) - inference_params = Mindee::Input::InferenceParameters.new('dummy-model') - client.enqueue_inference(input_doc, inference_params) - end.to raise_error(Mindee::Errors::MindeeHTTPErrorV2) { |e| + params = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new('dummy-model') + client.enqueue(Mindee::V2::Product::Extraction::Extraction, input_doc, params) + end.to raise_error(Mindee::Error::MindeeHTTPErrorV2) { |e| expect(e.status).to eq(413) expect(e.detail).to include('File exceeds size limit') } @@ -84,10 +88,11 @@ def stub_next_request_with(method, hash:, status_code: 0) it 'get_job(job_id) returns a fully-formed JobResponse' do json_path = File.join(V2_DATA_DIR, 'job', 'ok_processing.json') parsed = File.read(json_path) - stub_next_request_with(:inference_job_req_get, hash: parsed, status_code: 200) + stub_next_request_with(:poll, hash: parsed, status_code: 200) resp = client.get_job('123e4567-e89b-12d3-a456-426614174000') - expect(resp).to be_a(Mindee::Parsing::V2::JobResponse) + expect(resp).to be_a(Mindee::V2::Parsing::JobResponse) + expect(resp.raw_http).to eq(JSON.generate(JSON.parse(parsed))) expect(resp.job.status).to eq('Processing') expect( resp.job.created_at.strftime('%Y-%m-%dT%H:%M:%S.%6N') @@ -98,10 +103,11 @@ def stub_next_request_with(method, hash:, status_code: 0) it 'should deserialize a job properly' do json_path = File.join(V2_DATA_DIR, 'job', 'ok_processed_webhooks_ok.json') parsed = File.read(json_path) - stub_next_request_with(:inference_job_req_get, hash: parsed, status_code: 200) + stub_next_request_with(:poll, hash: parsed, status_code: 200) resp = client.get_job('123e4567-e89b-12d3-a456-426614174000') - expect(resp).to be_a(Mindee::Parsing::V2::JobResponse) + expect(resp).to be_a(Mindee::V2::Parsing::JobResponse) + expect(resp.raw_http).to eq(JSON.generate(JSON.parse(parsed))) expect(resp.job.status).to eq('Processed') expect(resp.job.model_id).to eq('87654321-4321-4321-4321-CBA987654321') expect(resp.job.filename).to eq('default_sample.jpg') diff --git a/spec/v2/file_operation/crop_operation_integration.rb b/spec/v2/file_operation/crop_operation_integration.rb new file mode 100644 index 000000000..f531a0267 --- /dev/null +++ b/spec/v2/file_operation/crop_operation_integration.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +require 'mindee' +require 'mindee/v2/file_operation' +require 'mindee/v2/product' + +describe Mindee::V2::FileOperation::Crop, :integration, :v2, :all_deps do + let(:crop_sample) do + File.join(V2_PRODUCT_DATA_DIR, 'crop', 'default_sample.jpg') + end + + let(:v2_client) do + Mindee::V2::Client.new + end + + let(:crop_model_id) do + ENV.fetch('MINDEE_V2_SE_TESTS_CROP_MODEL_ID') + end + + let(:findoc_model_id) do + ENV.fetch('MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID') + end + + after(:all) do + FileUtils.rm_f("#{OUTPUT_DIR}/crop_001.jpg") + FileUtils.rm_f("#{OUTPUT_DIR}/crop_002.jpg") + end + + # Validates the parsed financial document response properties. + # + # @param findoc_response [Mindee::V2::InferenceResponse] The inference response to check. + def check_findoc_return(findoc_response) + expect(findoc_response.inference.model.id.length).to be > 0 + expect(findoc_response.inference.result.fields['total_amount'].value).to be > 0 + end + + it 'extracts crops from image correctly' do + crop_input = Mindee::Input::Source::PathInputSource.new(crop_sample) + + crop_params = { model_id: crop_model_id, close_file: false } + + response = v2_client.enqueue_and_get_result( + Mindee::V2::Product::Crop::Crop, + crop_input, + crop_params + ) + + expect(response.inference.result.crops.size).to eq(2) + + extracted_images = described_class.extract_crops(crop_input, response.inference.result.crops) + + expect(extracted_images.size).to eq(2) + expect(extracted_images[0].filename).to eq('default_sample.jpg_page0-0.jpg') + expect(extracted_images[1].filename).to eq('default_sample.jpg_page0-1.jpg') + + findoc_params = { model_id: findoc_model_id, close_file: false } + + invoice0 = v2_client.enqueue_and_get_result( + Mindee::V2::Product::Extraction::Extraction, + extracted_images[0].as_input_source, + findoc_params + ) + + check_findoc_return(invoice0) + + extracted_images.save_all_to_disk(OUTPUT_DIR) + + expect(File.size(File.join(OUTPUT_DIR, 'crop_001.jpg'))).to be_between(600_000, 672_913) + expect(File.size(File.join(OUTPUT_DIR, 'crop_002.jpg'))).to be_between(600_000, 675_728) + end +end diff --git a/spec/v2/file_operation/crop_operation_spec.rb b/spec/v2/file_operation/crop_operation_spec.rb new file mode 100644 index 000000000..e97277c9c --- /dev/null +++ b/spec/v2/file_operation/crop_operation_spec.rb @@ -0,0 +1,61 @@ +# frozen_string_literal: true + +require 'json' +require 'mini_magick' if Mindee::Dependency.all_deps_available? +require 'mindee' +require 'mindee/v2/file_operation' +require 'mindee/v2/product' + +describe Mindee::V2::FileOperation::Crop, :v2, :all_deps do + let(:crops_single_page_path) do + File.join(V2_PRODUCT_DATA_DIR, 'crop', 'default_sample.jpg') + end + + let(:crops_multi_page_path) do + File.join(V2_PRODUCT_DATA_DIR, 'crop', 'multipage_sample.pdf') + end + + let(:crops_single_page_json_path) do + File.join(V2_PRODUCT_DATA_DIR, 'crop', 'crop_single.json') + end + + let(:crops_multi_page_json_path) do + File.join(V2_PRODUCT_DATA_DIR, 'crop', 'crop_multiple.json') + end + + it 'processes single page crop split correctly' do + input_sample = Mindee::Input::Source::PathInputSource.new(crops_single_page_path) + response_hash = JSON.parse(File.read(crops_single_page_json_path)) + doc = Mindee::V2::Product::Crop::CropResponse.new(response_hash) + + extracted_crops = described_class.extract_crops(input_sample, doc.inference.result.crops) + + expect(extracted_crops.size).to eq(1) + + expect(extracted_crops[0].page_id).to eq(0) + expect(extracted_crops[0].element_id).to eq(0) + + image_buffer0 = MiniMagick::Image.read(extracted_crops[0].buffer) + expect(image_buffer0.dimensions).to eq([2822, 1572]) + end + + it 'processes multi page receipt split correctly' do + input_sample = Mindee::Input::Source::PathInputSource.new(crops_multi_page_path) + response_hash = JSON.parse(File.read(crops_multi_page_json_path)) + doc = Mindee::V2::Product::Crop::CropResponse.new(response_hash) + + extracted_crops = described_class.extract_crops(input_sample, doc.inference.result.crops) + + expect(extracted_crops.size).to eq(2) + + expect(extracted_crops[0].page_id).to eq(0) + expect(extracted_crops[0].element_id).to eq(0) + image_buffer0 = MiniMagick::Image.read(extracted_crops[0].buffer) + expect(image_buffer0.dimensions).to eq([156, 758]) + + expect(extracted_crops[1].page_id).to eq(0) + expect(extracted_crops[1].element_id).to eq(1) + image_buffer1 = MiniMagick::Image.read(extracted_crops[1].buffer) + expect(image_buffer1.dimensions).to eq([187, 690]) + end +end diff --git a/spec/v2/file_operation/split_operation_integration.rb b/spec/v2/file_operation/split_operation_integration.rb new file mode 100644 index 000000000..dad47b1d4 --- /dev/null +++ b/spec/v2/file_operation/split_operation_integration.rb @@ -0,0 +1,84 @@ +# frozen_string_literal: true + +require 'mindee' +require 'mindee/v2/file_operation' +require 'mindee/v2/product' +require 'fileutils' + +describe Mindee::V2::Product::Split::Split, :integration, :v2, :all_deps do + let(:split_sample) do + File.join(V2_PRODUCT_DATA_DIR, 'split', 'default_sample.pdf') + end + + let(:invoice_splitter_5p_path) do + File.join(V2_PRODUCT_DATA_DIR, 'split', 'invoice_5p.pdf') + end + + let(:v2_client) do + Mindee::V2::Client.new + end + + let(:split_model_id) do + ENV.fetch('MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID') + end + + let(:findoc_model_id) do + ENV.fetch('MINDEE_V2_SE_TESTS_FINDOC_MODEL_ID') + end + + after(:all) do + FileUtils.rm_f("#{OUTPUT_DIR}/split_001.pdf") + FileUtils.rm_f("#{OUTPUT_DIR}/split_002.pdf") + end + + # Validates the parsed financial document response properties. + # + # @param findoc_response [Mindee::V2::InferenceResponse] The inference response to check. + def check_findoc_return(findoc_response) + expect(findoc_response.inference.model.id.length).to be > 0 + expect(findoc_response.inference.result.fields['total_amount'].value).to be > 0 + end + + it 'extracts splits from pdf correctly' do + split_input = Mindee::Input::Source::PathInputSource.new(split_sample) + + split_params = { model_id: split_model_id, close_file: false } + + response = v2_client.enqueue_and_get_result( + Mindee::V2::Product::Split::Split, + split_input, + split_params + ) + + expect(response.inference.file.page_count).to eq(2) + + extracted_pdfs = response.extract_from_file(split_input) + + expect(extracted_pdfs.size).to eq(2) + expect(extracted_pdfs[0].filename).to eq('default_sample_001-001.pdf') + expect(extracted_pdfs[1].filename).to eq('default_sample_002-002.pdf') + + findoc_params = { model_id: findoc_model_id, close_file: false } + + invoice0 = v2_client.enqueue_and_get_result( + Mindee::V2::Product::Extraction::Extraction, + extracted_pdfs[0].as_input_source, + findoc_params + ) + + check_findoc_return(invoice0) + + extracted_pdfs.save_all_to_disk(OUTPUT_DIR) + + extracted_pdfs.each_with_index do |pdf, i| + local_input = Mindee::Input::Source::PathInputSource.new(File.join(OUTPUT_DIR, format('split_%03d.pdf', i + 1))) + begin + expect(local_input.page_count).to eq(pdf.page_count) + ensure + local_input.close if local_input.respond_to?(:close) + end + end + ensure + split_input.close if split_input.respond_to?(:close) + end +end diff --git a/spec/v2/file_operation/split_operation_spec.rb b/spec/v2/file_operation/split_operation_spec.rb new file mode 100644 index 000000000..c0d87fb46 --- /dev/null +++ b/spec/v2/file_operation/split_operation_spec.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require 'json' +require 'mindee' +require 'mindee/v2/product' + +describe Mindee::V2::Product::Split::SplitResponse, :v2, :all_deps do + let(:splits_default) do + File.join(V2_PRODUCT_DATA_DIR, 'extraction', 'financial_document', 'default_sample.jpg') + end + + let(:splits_5p) do + File.join(V2_PRODUCT_DATA_DIR, 'split', 'invoice_5p.pdf') + end + + let(:splits_single_page_json_path) do + File.join(V2_PRODUCT_DATA_DIR, 'split', 'split_single.json') + end + + let(:splits_multi_page_json_path) do + File.join(V2_PRODUCT_DATA_DIR, 'split', 'split_multiple.json') + end + + it 'processes single page split correctly' do + input_sample = Mindee::Input::Source::PathInputSource.new(splits_default) + response_hash = JSON.parse(File.read(splits_single_page_json_path)) + doc = described_class.new(response_hash) + + extracted_splits = doc.extract_from_file(input_sample) + + expect(extracted_splits.size).to eq(1) + + expect(extracted_splits[0].page_count).to eq(1) + end + + it 'processes multi page receipt split correctly' do + input_sample = Mindee::Input::Source::PathInputSource.new(splits_5p) + response_hash = JSON.parse(File.read(splits_multi_page_json_path)) + doc = described_class.new(response_hash) + + extracted_splits = doc.extract_from_file(input_sample) + + expect(extracted_splits.size).to eq(3) + + expect(extracted_splits[0].page_count).to eq(1) + expect(extracted_splits[1].page_count).to eq(3) + expect(extracted_splits[2].page_count).to eq(1) + end +end diff --git a/spec/v2/input/local_response_v2_spec.rb b/spec/v2/input/local_response_v2_spec.rb index ee5dd549d..21582c149 100644 --- a/spec/v2/input/local_response_v2_spec.rb +++ b/spec/v2/input/local_response_v2_spec.rb @@ -11,8 +11,8 @@ def assert_local_response(local_response) dummy_secret_key, 'invalid signature' )).to be(false) expect(local_response.get_hmac_signature(dummy_secret_key)).to eq(signature) - inference_response = local_response.deserialize_response(Mindee::Parsing::V2::InferenceResponse) - expect(inference_response).to be_a(Mindee::Parsing::V2::InferenceResponse) + inference_response = local_response.deserialize_response(Mindee::V2::Product::Extraction::ExtractionResponse) + expect(inference_response).to be_a(Mindee::V2::Product::Extraction::ExtractionResponse) expect(inference_response).not_to be_nil expect(inference_response.inference).not_to be_nil end @@ -50,14 +50,14 @@ def assert_local_response(local_response) it 'should trigger an error when something invalid is passed' do expect do Mindee::Input::LocalResponse.new(123) - end.to raise_error Mindee::Errors::MindeeInputError + end.to raise_error Mindee::Error::MindeeInputError end it 'should trigger an error when the payload is not hashable' do local_response = Mindee::Input::LocalResponse.new('Your mother was a hamster.') expect do local_response.as_hash - end.to raise_error Mindee::Errors::MindeeInputError + end.to raise_error Mindee::Error::MindeeInputError end end end diff --git a/spec/v2/parser_spec.rb b/spec/v2/parser_spec.rb new file mode 100644 index 000000000..97d2dc812 --- /dev/null +++ b/spec/v2/parser_spec.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require 'json' +require_relative '../../bin/v2/parser' + +describe MindeeCLI::V2Parser do + subject(:parser) { described_class.new([]) } + + it 'keeps already parsed raw payloads unchanged' do + payload = { 'api_request' => { 'status' => 'success' } } + expect(parser.__send__(:raw_payload, payload)).to eq(payload) + end + + it 'parses JSON string payloads' do + payload = { 'api_request' => { 'status' => 'success' } } + expect(parser.__send__(:raw_payload, JSON.generate(payload))).to eq(payload) + end + + it 'parses double-encoded JSON string payloads once more' do + payload = { 'api_request' => { 'status' => 'success' } } + double_encoded = JSON.generate(JSON.generate(payload)) + expect(parser.__send__(:raw_payload, double_encoded)).to eq(payload) + end +end diff --git a/spec/v2/parsing/common_response_spec.rb b/spec/v2/parsing/common_response_spec.rb new file mode 100644 index 000000000..530c4dc23 --- /dev/null +++ b/spec/v2/parsing/common_response_spec.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +require 'json' +require 'mindee' +require 'mindee/v2/parsing/common_response' + +describe Mindee::V2::Parsing::CommonResponse do + it 'stores raw_http as a JSON string' do + server_response = { + 'api_request' => { 'status' => 'success' }, + 'job' => { 'status' => 'Processing' }, + } + + response = described_class.new(server_response) + expect(response.raw_http).to be_a(String) + expect(JSON.parse(response.raw_http)).to eq(server_response) + end +end diff --git a/spec/v2/parsing/inference_spec.rb b/spec/v2/parsing/inference_spec.rb index 31f2c2b04..d0a4fe1e6 100644 --- a/spec/v2/parsing/inference_spec.rb +++ b/spec/v2/parsing/inference_spec.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require 'mindee' +require 'mindee/v2/parsing/field' describe 'inference' do let(:findoc_path) { File.join(V2_PRODUCT_DATA_DIR, 'extraction', 'financial_document') } @@ -19,13 +20,13 @@ def load_v2_inference(resource_path) local_response = Mindee::Input::LocalResponse.new(resource_path) - local_response.deserialize_response(Mindee::Parsing::V2::InferenceResponse) + local_response.deserialize_response(Mindee::V2::Product::Extraction::ExtractionResponse) end - simple_field = Mindee::Parsing::V2::Field::SimpleField - object_field = Mindee::Parsing::V2::Field::ObjectField - list_field = Mindee::Parsing::V2::Field::ListField - field_confidence = Mindee::Parsing::V2::Field::FieldConfidence + simple_field = Mindee::V2::Parsing::Field::SimpleField + object_field = Mindee::V2::Parsing::Field::ObjectField + list_field = Mindee::V2::Parsing::Field::ListField + field_confidence = Mindee::V2::Parsing::Field::FieldConfidence describe 'simple' do it 'loads a blank inference with valid properties' do @@ -33,7 +34,7 @@ def load_v2_inference(resource_path) fields = response.inference.result.fields expect(fields).not_to be_empty - expect(fields).to be_a(Mindee::Parsing::V2::Field::InferenceFields) + expect(fields).to be_a(Mindee::V2::Parsing::Field::InferenceFields) expect(fields.size).to eq(21) expect(fields).to have_key('taxes') @@ -64,7 +65,7 @@ def load_v2_inference(resource_path) inference = response.inference job = inference.job expect(job).not_to be_nil - expect(job).to be_a(Mindee::Parsing::V2::InferenceJob) + expect(job).to be_a(Mindee::V2::Parsing::InferenceJob) expect(job.id).to eq('12345678-1234-1234-1234-jobid1234567') expect(inference).not_to be_nil @@ -191,7 +192,7 @@ def load_standard_fields expect(active_options.raw_text).to eq(true) fields = response.inference.result.fields - expect(fields).to be_a(Mindee::Parsing::V2::Field::InferenceFields) + expect(fields).to be_a(Mindee::V2::Parsing::Field::InferenceFields) fields end @@ -291,13 +292,13 @@ def load_standard_fields raw_text = response.inference.result.raw_text expect(raw_text).not_to be_nil - expect(raw_text).to be_a(Mindee::Parsing::V2::RawText) + expect(raw_text).to be_a(Mindee::V2::Parsing::RawText) expect(raw_text.to_s).to eq(File.read(raw_text_str_path, encoding: 'UTF-8')) expect(raw_text.pages.length).to eq(2) first = raw_text.pages.first - expect(first).to be_a(Mindee::Parsing::V2::RawTextPage) + expect(first).to be_a(Mindee::V2::Parsing::RawTextPage) expect(first.content).to eq('This is the raw text of the first page...') raw_text.pages.each do |page| diff --git a/spec/v2/parsing/job_webhook_spec.rb b/spec/v2/parsing/job_webhook_spec.rb index b07e62635..3fbead365 100644 --- a/spec/v2/parsing/job_webhook_spec.rb +++ b/spec/v2/parsing/job_webhook_spec.rb @@ -1,8 +1,9 @@ # frozen_string_literal: true require 'mindee' +require 'mindee/v2/parsing/job_webhook' -describe Mindee::Parsing::V2::JobWebhook do +describe Mindee::V2::Parsing::JobWebhook do describe '#initialize' do context 'when error key is present but value is nil' do it 'does not raise an error and sets @error to nil' do @@ -52,7 +53,7 @@ expect(webhook.id).to eq('12345678-1234-1234-1234-123456789012') expect(webhook.status).to eq('Failed') - expect(webhook.error).to be_a(Mindee::Parsing::V2::ErrorResponse) + expect(webhook.error).to be_a(Mindee::V2::Parsing::ErrorResponse) expect(webhook.error.status).to eq(500) expect(webhook.error.detail).to eq('Internal server error') end diff --git a/spec/v2/product/classification/classification_integration.rb b/spec/v2/product/classification/classification_integration.rb index e0c0b3266..f0ac7ebbf 100644 --- a/spec/v2/product/classification/classification_integration.rb +++ b/spec/v2/product/classification/classification_integration.rb @@ -3,13 +3,13 @@ require 'mindee' require 'mindee/v2/product' -describe Mindee::ClientV2, :integration, :v2 do +describe Mindee::V2::Product::Classification, :integration, :v2 do let(:classification_model_id) do ENV.fetch('MINDEE_V2_SE_TESTS_CLASSIFICATION_MODEL_ID', nil) end let(:v2_client) do - Mindee::ClientV2.new + Mindee::V2::Client.new end it 'processes classification default sample correctly' do diff --git a/spec/v2/product/crop/crop_integration.rb b/spec/v2/product/crop/crop_integration.rb index f8095c565..653a9ebab 100644 --- a/spec/v2/product/crop/crop_integration.rb +++ b/spec/v2/product/crop/crop_integration.rb @@ -3,13 +3,13 @@ require 'mindee' require 'mindee/v2/product' -describe Mindee::ClientV2, :integration, :v2 do +describe Mindee::V2::Product::Crop, :integration, :v2 do let(:crop_model_id) do ENV.fetch('MINDEE_V2_SE_TESTS_CROP_MODEL_ID', nil) end let(:v2_client) do - Mindee::ClientV2.new + Mindee::V2::Client.new end it 'processes crop default sample correctly' do diff --git a/spec/v2/input/inference_parameter_spec.rb b/spec/v2/product/extraction/extraction_parameter_spec.rb similarity index 64% rename from spec/v2/input/inference_parameter_spec.rb rename to spec/v2/product/extraction/extraction_parameter_spec.rb index bd4ae299c..41dd26f67 100644 --- a/spec/v2/input/inference_parameter_spec.rb +++ b/spec/v2/product/extraction/extraction_parameter_spec.rb @@ -1,27 +1,27 @@ # frozen_string_literal: true -require 'mindee/input/inference_parameters' -require 'mindee/input/data_schema' +require 'mindee/v2/product/extraction/params/data_schema' +require 'mindee/v2/product/extraction/params/extraction_parameters' -describe Mindee::Input::InferenceParameters do +describe Mindee::V2::Product::Extraction::Params::ExtractionParameters do let(:extracted_schema_content) do File.read(File.join(V2_PRODUCT_DATA_DIR, 'extraction', 'data_schema_replace_param.json')) end let(:extracted_schema_hash) { JSON.parse(extracted_schema_content) } let(:extracted_schema_str) { extracted_schema_hash.to_json } - let(:extracted_schema_object) { Mindee::Input::DataSchema.new(extracted_schema_hash) } + let(:extracted_schema_object) { Mindee::V2::Product::Extraction::Params::DataSchema.new(extracted_schema_hash) } describe 'Data Schema' do describe "shouldn't replace when unset" do it 'should initialize with a data schema' do - param = Mindee::Input::InferenceParameters.new( + param = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( 'dummy-model' ) expect(param.data_schema).to be_nil end it 'should initialize with string' do - param = Mindee::Input::InferenceParameters.new( + param = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( 'dummy-model', data_schema: extracted_schema_str ) @@ -29,7 +29,7 @@ end it 'should initialize with hash' do - param = Mindee::Input::InferenceParameters.new( + param = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( 'dummy-model', data_schema: extracted_schema_hash ) @@ -37,7 +37,7 @@ end it 'should initialize with DataSchema object' do - param = Mindee::Input::InferenceParameters.new( + param = Mindee::V2::Product::Extraction::Params::ExtractionParameters.new( 'dummy-model', data_schema: extracted_schema_object ) diff --git a/spec/v2/product/extraction/extraction_spec.rb b/spec/v2/product/extraction/extraction_spec.rb index 352a822f8..4a676f192 100644 --- a/spec/v2/product/extraction/extraction_spec.rb +++ b/spec/v2/product/extraction/extraction_spec.rb @@ -3,6 +3,11 @@ require 'mindee' require 'mindee/input/local_response' require 'mindee/v2/product' +require 'mindee/v2/parsing/field' +require 'mindee/v2/product/extraction/extraction_response' + +using Mindee::V2::Product::Extraction +using Mindee::V2::Parsing::Field describe 'extraction' do let(:findoc_path) { File.join(V2_PRODUCT_DATA_DIR, 'extraction', 'financial_document') } @@ -24,10 +29,10 @@ def load_v2_extraction_inference(resource_path) local_response.deserialize_response(Mindee::V2::Product::Extraction::ExtractionResponse) end - simple_field = Mindee::Parsing::V2::Field::SimpleField - object_field = Mindee::Parsing::V2::Field::ObjectField - list_field = Mindee::Parsing::V2::Field::ListField - field_confidence = Mindee::Parsing::V2::Field::FieldConfidence + simple_field = Mindee::V2::Parsing::Field::SimpleField + object_field = Mindee::V2::Parsing::Field::ObjectField + list_field = Mindee::V2::Parsing::Field::ListField + field_confidence = Mindee::V2::Parsing::Field::FieldConfidence describe 'simple' do it 'loads a blank extraction inference with valid properties' do @@ -35,7 +40,7 @@ def load_v2_extraction_inference(resource_path) fields = response.inference.result.fields expect(fields).not_to be_empty - expect(fields).to be_a(Mindee::Parsing::V2::Field::InferenceFields) + expect(fields).to be_a(Mindee::V2::Parsing::Field::InferenceFields) expect(fields.size).to eq(21) expect(fields).to have_key('taxes') @@ -66,7 +71,7 @@ def load_v2_extraction_inference(resource_path) inference = response.inference job = inference.job expect(job).not_to be_nil - expect(job).to be_a(Mindee::Parsing::V2::InferenceJob) + expect(job).to be_a(Mindee::V2::Parsing::InferenceJob) expect(job.id).to eq('12345678-1234-1234-1234-jobid1234567') expect(inference).not_to be_nil @@ -193,7 +198,7 @@ def load_standard_fields expect(active_options.raw_text).to eq(true) fields = response.inference.result.fields - expect(fields).to be_a(Mindee::Parsing::V2::Field::InferenceFields) + expect(fields).to be_a(Mindee::V2::Parsing::Field::InferenceFields) fields end @@ -293,13 +298,13 @@ def load_standard_fields raw_text = response.inference.result.raw_text expect(raw_text).not_to be_nil - expect(raw_text).to be_a(Mindee::Parsing::V2::RawText) + expect(raw_text).to be_a(Mindee::V2::Parsing::RawText) expect(raw_text.to_s).to eq(File.read(raw_text_str_path, encoding: 'UTF-8')) expect(raw_text.pages.length).to eq(2) first = raw_text.pages.first - expect(first).to be_a(Mindee::Parsing::V2::RawTextPage) + expect(first).to be_a(Mindee::V2::Parsing::RawTextPage) expect(first.content).to eq('This is the raw text of the first page...') raw_text.pages.each do |page| diff --git a/spec/v2/product/ocr/ocr_integration.rb b/spec/v2/product/ocr/ocr_integration.rb index b12c3e906..3d525a279 100644 --- a/spec/v2/product/ocr/ocr_integration.rb +++ b/spec/v2/product/ocr/ocr_integration.rb @@ -3,13 +3,13 @@ require 'mindee' require 'mindee/v2/product' -describe Mindee::ClientV2, :integration, :v2 do +describe Mindee::V2::Product::OCR, :integration, :v2 do let(:ocr_model_id) do ENV.fetch('MINDEE_V2_SE_TESTS_OCR_MODEL_ID') end let(:v2_client) do - Mindee::ClientV2.new + Mindee::V2::Client.new end it 'processes ocr default sample correctly' do @@ -20,15 +20,15 @@ params = { model_id: ocr_model_id } response = v2_client.enqueue_and_get_result( - Mindee::V2::Product::Ocr::Ocr, + Mindee::V2::Product::OCR::OCR, input_source, params ) expect(response.inference).not_to be_nil expect(response.inference.file.name).to eq('default_sample.jpg') - expect(response.inference).to be_a(Mindee::V2::Product::Ocr::OcrInference) - expect(response.inference.result).to be_a(Mindee::V2::Product::Ocr::OcrResult) + expect(response.inference).to be_a(Mindee::V2::Product::OCR::OCRInference) + expect(response.inference.result).to be_a(Mindee::V2::Product::OCR::OCRResult) expect(response.inference.result.pages.size).to eq(1) expect(response.inference.result.pages[0].words.size).to be > 5 end diff --git a/spec/v2/product/ocr/ocr_spec.rb b/spec/v2/product/ocr/ocr_spec.rb index 039a05854..ff5add243 100644 --- a/spec/v2/product/ocr/ocr_spec.rb +++ b/spec/v2/product/ocr/ocr_spec.rb @@ -3,16 +3,16 @@ require 'json' require 'mindee' -describe Mindee::V2::Product::Ocr::Ocr, :v2 do +describe Mindee::V2::Product::OCR::OCR, :v2 do let(:ocr_data_dir) { File.join(V2_PRODUCT_DATA_DIR, 'ocr') } it 'parses a single page OCR response properly' do json_path = File.join(ocr_data_dir, 'ocr_single.json') json_sample = JSON.parse(File.read(json_path)) - response = Mindee::V2::Product::Ocr::OcrResponse.new(json_sample) + response = Mindee::V2::Product::OCR::OCRResponse.new(json_sample) - expect(response.inference).to be_a(Mindee::V2::Product::Ocr::OcrInference) + expect(response.inference).to be_a(Mindee::V2::Product::OCR::OCRInference) expect(response.inference.result.pages).not_to be_empty expect(response.inference.result.pages.size).to eq(1) @@ -66,11 +66,11 @@ json_path = File.join(ocr_data_dir, 'ocr_multiple.json') json_sample = JSON.parse(File.read(json_path)) - response = Mindee::V2::Product::Ocr::OcrResponse.new(json_sample) + response = Mindee::V2::Product::OCR::OCRResponse.new(json_sample) - expect(response.inference).to be_a(Mindee::V2::Product::Ocr::OcrInference) - expect(response.inference.result).to be_a(Mindee::V2::Product::Ocr::OcrResult) - expect(response.inference.result.pages[0]).to be_a(Mindee::V2::Product::Ocr::OcrPage) + expect(response.inference).to be_a(Mindee::V2::Product::OCR::OCRInference) + expect(response.inference.result).to be_a(Mindee::V2::Product::OCR::OCRResult) + expect(response.inference.result.pages[0]).to be_a(Mindee::V2::Product::OCR::OCRPage) expect(response.inference.result.pages.size).to eq(3) page_zero_words = response.inference.result.pages[0].words diff --git a/spec/v2/product/split/split_integration.rb b/spec/v2/product/split/split_integration.rb index adbfc852a..d328cc914 100644 --- a/spec/v2/product/split/split_integration.rb +++ b/spec/v2/product/split/split_integration.rb @@ -3,13 +3,13 @@ require 'mindee' require 'mindee/v2/product' -describe Mindee::ClientV2, :integration, :v2 do +describe Mindee::V2::Client, :integration, :v2 do let(:split_model_id) do ENV.fetch('MINDEE_V2_SE_TESTS_SPLIT_MODEL_ID') end let(:v2_client) do - Mindee::ClientV2.new + Mindee::V2::Client.new end it 'processes split default sample correctly' do