lara-haystack 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,146 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ volumes/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ .python-version
87
+
88
+ # pipenv
89
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
90
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
91
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
92
+ # install all needed dependencies.
93
+ #Pipfile.lock
94
+
95
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
96
+ __pypackages__/
97
+
98
+ # Celery stuff
99
+ celerybeat-schedule
100
+ celerybeat.pid
101
+
102
+ # SageMath parsed files
103
+ *.sage.py
104
+
105
+ # Environments
106
+ .env
107
+ .venv
108
+ env/
109
+ venv/
110
+ ENV/
111
+ env.bak/
112
+ venv.bak/
113
+
114
+ # Spyder project settings
115
+ .spyderproject
116
+ .spyproject
117
+
118
+ # Rope project settings
119
+ .ropeproject
120
+
121
+ # mkdocs documentation
122
+ /site
123
+
124
+ # mypy
125
+ .mypy_cache/
126
+ .dmypy.json
127
+ dmypy.json
128
+
129
+ # Pyre type checker
130
+ .pyre/
131
+
132
+ # IDEs
133
+ .vscode
134
+
135
+ # Docs generation artifacts
136
+ _readme_*.md
137
+ .idea
138
+
139
+ # macOS
140
+ .DS_Store
141
+
142
+ # http cache (requests-cache)
143
+ **/http_cache.sqlite
144
+
145
+ # ruff
146
+ .ruff_cache
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: lara-haystack
3
+ Version: 1.0.0
4
+ Summary: Haystack integration for Lara, translated's AI translator
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/lara#readme
6
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/issues
7
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/lara
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Keywords: Haystack,Lara,Translation,Translator
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: Implementation :: CPython
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: haystack-ai>=2.24.1
22
+ Requires-Dist: lara-sdk
23
+ Description-Content-Type: text/markdown
24
+
25
+ # lara-haystack
26
+
27
+ [![PyPI - Version](https://img.shields.io/pypi/v/lara-haystack.svg)](https://pypi.org/project/lara-haystack)
28
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/lara-haystack.svg)](https://pypi.org/project/lara-haystack)
29
+
30
+ - [Integration page](https://haystack.deepset.ai/integrations/lara)
31
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/lara/CHANGELOG.md)
32
+
33
+ ---
34
+
35
+ ## Contributing
36
+
37
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
38
+
39
+ To run integration tests locally, you need to export the `LARA_ACCESS_KEY_ID` and `LARA_ACCESS_KEY_SECRET` environment variables.
@@ -0,0 +1,15 @@
1
+ # lara-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/lara-haystack.svg)](https://pypi.org/project/lara-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/lara-haystack.svg)](https://pypi.org/project/lara-haystack)
5
+
6
+ - [Integration page](https://haystack.deepset.ai/integrations/lara)
7
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/lara/CHANGELOG.md)
8
+
9
+ ---
10
+
11
+ ## Contributing
12
+
13
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
14
+
15
+ To run integration tests locally, you need to export the `LARA_ACCESS_KEY_ID` and `LARA_ACCESS_KEY_SECRET` environment variables.
@@ -0,0 +1,13 @@
1
+ loaders:
2
+ - modules:
3
+ - haystack_integrations.components.translators.lara.document_translator
4
+ search_path: [../src]
5
+ processors:
6
+ - type: filter
7
+ documented_only: true
8
+ skip_empty_modules: true
9
+ renderer:
10
+ description: Lara integration for Haystack
11
+ id: integrations-lara
12
+ filename: lara.md
13
+ title: Lara
@@ -0,0 +1,167 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "lara-haystack"
7
+ dynamic = ["version"]
8
+ description = "Haystack integration for Lara, translated's AI translator"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ keywords = [
13
+ "Haystack",
14
+ "Lara",
15
+ "Translator",
16
+ "Translation",
17
+ ]
18
+ authors = [
19
+ { name = "deepset GmbH", email = "info@deepset.ai" },
20
+ ]
21
+ classifiers = [
22
+ "License :: OSI Approved :: Apache Software License",
23
+ "Development Status :: 4 - Beta",
24
+ "Programming Language :: Python",
25
+ "Programming Language :: Python :: 3.10",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Programming Language :: Python :: 3.13",
29
+ "Programming Language :: Python :: Implementation :: CPython",
30
+ ]
31
+ dependencies = ["haystack-ai>=2.24.1", "lara-sdk"]
32
+
33
+ [project.urls]
34
+ Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/lara#readme"
35
+ Issues = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/issues"
36
+ Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/lara"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/haystack_integrations"]
40
+
41
+ [tool.hatch.version]
42
+ source = "vcs"
43
+ tag-pattern = 'integrations\/lara-v(?P<version>.*)'
44
+
45
+ [tool.hatch.version.raw-options]
46
+ root = "../.."
47
+ git_describe_command = 'git describe --tags --match="integrations/lara-v[0-9]*"'
48
+
49
+ [tool.hatch.envs.default]
50
+ installer = "uv"
51
+ dependencies = ["haystack-pydoc-tools", "ruff"]
52
+
53
+ [tool.hatch.envs.default.scripts]
54
+ docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
55
+ fmt = "ruff check --fix {args}; ruff format {args}"
56
+ fmt-check = "ruff check {args} && ruff format --check {args}"
57
+
58
+ [tool.hatch.envs.test]
59
+ dependencies = [
60
+ "pytest",
61
+ "pytest-asyncio",
62
+ "pytest-cov",
63
+ "pytest-rerunfailures",
64
+ "mypy",
65
+ "pip"
66
+ ]
67
+
68
+ [tool.hatch.envs.test.scripts]
69
+ unit = 'pytest -m "not integration" {args:tests}'
70
+ integration = 'pytest -m "integration" {args:tests}'
71
+ all = 'pytest {args:tests}'
72
+ cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x {args:tests}'
73
+ types = 'mypy -p haystack_integrations.components.translators.lara {args}'
74
+
75
+ [tool.mypy]
76
+ install_types = true
77
+ non_interactive = true
78
+ check_untyped_defs = true
79
+ disallow_incomplete_defs = true
80
+
81
+ [[tool.mypy.overrides]]
82
+ module = [
83
+ "lara_sdk.*"
84
+ ]
85
+ ignore_missing_imports = true
86
+
87
+ [tool.ruff]
88
+ line-length = 120
89
+
90
+ [tool.ruff.lint]
91
+ select = [
92
+ "A",
93
+ "ARG",
94
+ "B",
95
+ "C",
96
+ "DTZ",
97
+ "E",
98
+ "EM",
99
+ "F",
100
+ "I",
101
+ "ICN",
102
+ "ISC",
103
+ "N",
104
+ "PLC",
105
+ "PLE",
106
+ "PLR",
107
+ "PLW",
108
+ "Q",
109
+ "RUF",
110
+ "S",
111
+ "T",
112
+ "TID",
113
+ "UP",
114
+ "W",
115
+ "YTT",
116
+ ]
117
+ ignore = [
118
+ # Allow non-abstract empty methods in abstract base classes
119
+ "B027",
120
+ # Allow function calls in argument defaults (common Haystack pattern for Secret.from_env_var)
121
+ "B008",
122
+ # zip() without strict= is OK when lengths are guaranteed equal
123
+ "B905",
124
+ # Ignore checks for possible passwords
125
+ "S105",
126
+ "S106",
127
+ "S107",
128
+ # Ignore complexity
129
+ "C901",
130
+ "PLR0911",
131
+ "PLR0912",
132
+ "PLR0913",
133
+ "PLR0915",
134
+ ]
135
+ unfixable = [
136
+ # Don't touch unused imports
137
+ "F401",
138
+ ]
139
+
140
+ [tool.ruff.lint.isort]
141
+ known-first-party = ["haystack_integrations"]
142
+
143
+ [tool.ruff.lint.flake8-tidy-imports]
144
+ ban-relative-imports = "parents"
145
+
146
+ [tool.ruff.lint.per-file-ignores]
147
+ # Tests can use magic values, assertions, and relative imports
148
+ "tests/**/*" = ["PLR2004", "S101", "TID252"]
149
+
150
+ [tool.coverage.run]
151
+ source = ["haystack_integrations"]
152
+ branch = true
153
+ parallel = false
154
+
155
+ [tool.coverage.report]
156
+ omit = ["*/tests/*", "*/__init__.py"]
157
+ show_missing = true
158
+ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
159
+
160
+ [tool.pytest.ini_options]
161
+ testpaths = ["tests"]
162
+ addopts = "--strict-markers"
163
+ markers = [
164
+ "integration: integration tests",
165
+ ]
166
+ log_cli = true
167
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from .document_translator import LaraDocumentTranslator
6
+
7
+ __all__ = ["LaraDocumentTranslator"]
@@ -0,0 +1,340 @@
1
+ # SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any, Literal
6
+
7
+ from haystack import Document, component, logging
8
+ from haystack.utils import Secret
9
+ from lara_sdk import Credentials, TextBlock, Translator
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ @component
15
+ class LaraDocumentTranslator:
16
+ """
17
+ Translates the text content of Haystack Documents using translated's Lara translation API.
18
+
19
+ Lara is an adaptive translation AI that combines the fluency and context handling
20
+ of LLMs with low hallucination and latency. It adapts to domains at inference time
21
+ using optional context, instructions, translation memories, and glossaries. You can find
22
+ more detailed information in the [Lara documentation](https://developers.laratranslate.com/docs/introduction).
23
+
24
+
25
+ ### Usage example
26
+ ```python
27
+ from haystack import Document
28
+ from haystack.utils import Secret
29
+ from haystack_integrations.components.lara import LaraDocumentTranslator
30
+
31
+ translator = LaraDocumentTranslator(
32
+ access_key_id=Secret.from_env_var("LARA_ACCESS_KEY_ID"),
33
+ access_key_secret=Secret.from_env_var("LARA_ACCESS_KEY_SECRET"),
34
+ source_lang="en-US",
35
+ target_lang="de-DE",
36
+ )
37
+
38
+ doc = Document(content="Hello, world!")
39
+ result = translator.run(documents=[doc])
40
+ print(result["documents"][0].content)
41
+ ```
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ access_key_id: Secret = Secret.from_env_var("LARA_ACCESS_KEY_ID"),
47
+ access_key_secret: Secret = Secret.from_env_var("LARA_ACCESS_KEY_SECRET"),
48
+ source_lang: str | None = None,
49
+ target_lang: str | None = None,
50
+ context: str | None = None,
51
+ instructions: str | None = None,
52
+ style: Literal["faithful", "fluid", "creative"] = "faithful",
53
+ adapt_to: list[str] | None = None,
54
+ glossaries: list[str] | None = None,
55
+ reasoning: bool = False,
56
+ ):
57
+ """
58
+ Creats an instance of the LaraDocumentTranslator component.
59
+
60
+ :param access_key_id:
61
+ Lara API access key ID. Defaults to the `LARA_ACCESS_KEY_ID` environment variable.
62
+ :param access_key_secret:
63
+ Lara API access key secret. Defaults to the `LARA_ACCESS_KEY_SECRET` environment variable.
64
+ :param source_lang:
65
+ Language code of the source text. If `None`, Lara auto-detects the source language.
66
+ Use locale codes from the
67
+ [supported languages list](https://developers.laratranslate.com/docs/supported-languages).
68
+ :param target_lang:
69
+ Language code of the target text.
70
+ Use locale codes from the
71
+ [supported languages list](https://developers.laratranslate.com/docs/supported-languages).
72
+ :param context:
73
+ Optional external context: text that is not translated but is sent to Lara to
74
+ improve translation quality (e.g. surrounding sentences, prior messages).
75
+ You can find more detailed information in the
76
+ [Lara documentation](https://developers.laratranslate.com/docs/adapt-to-context).
77
+ :param instructions:
78
+ Optional natural-language instructions to guide translation and
79
+ specify domain-specific terminology (e.g. "Be formal", "Use a professional tone").
80
+ You can find more detailed information in the
81
+ [Lara documentation](https://developers.laratranslate.com/docs/adapt-to-instructions).
82
+ :param style:
83
+ One of `"faithful"`, `"fluid"`, or `"creative"`.
84
+ Default is `"faithful"`.
85
+ Style description:
86
+ - `"faithful"`: For accuracy and precision. Keeps original structure and meaning.
87
+ Ideal for manuals, legal documents.
88
+ - `"fluid"`: For readability and natural flow. Smooth, conversational. Good for general content.
89
+ - `"creative"`: For artistic and creative expression. Best for literature, marketing, or content
90
+ where impact and tone matter more than literal wording.
91
+ You can find more detailed information in the
92
+ [Lara documentation](https://support.laratranslate.com/en/translation-styles).
93
+ :param adapt_to:
94
+ Optional list of translation memory IDs. Lara adapts to the style and terminology of these memories
95
+ at inference time. Domain adaptation is available depending on your plan. You can find more
96
+ detailed information in the
97
+ [Lara documentation](https://developers.laratranslate.com/docs/adapt-to-translation-memories).
98
+ :param glossaries:
99
+ Optional list of glossary IDs. Lara applies these glossaries at inference time to enforce
100
+ consistent terminology (e.g. brand names, product terms, legal or technical phrases) across translations.
101
+ Glossary management and availability depends on your plan.
102
+ You can find more detailed information in the
103
+ [Lara documentation](https://developers.laratranslate.com/docs/manage-glossaries).
104
+ :param reasoning:
105
+ If `True`, uses the Lara Think model for higher-quality translation (multi-step linguistic analysis).
106
+ Increases latency and cost. Availability depends on your plan. You can find more detailed information in the
107
+ [Lara documentation](https://developers.laratranslate.com/docs/translate-text#reasoning-lara-think).
108
+ """
109
+
110
+ self.access_key_id = access_key_id
111
+ self.access_key_secret = access_key_secret
112
+ self.source_lang = source_lang
113
+ self.target_lang = target_lang
114
+ self.context = context
115
+ self.instructions = instructions
116
+ self.style = style
117
+ self.adapt_to = adapt_to
118
+ self.glossaries = glossaries
119
+ self.reasoning = reasoning
120
+ self._translator: Translator | None = None
121
+
122
+ def warm_up(self) -> None:
123
+ """
124
+ Warm up the Lara translator by initializing the client.
125
+ """
126
+ if self._translator is None:
127
+ credentials = Credentials(
128
+ access_key_id=self.access_key_id.resolve_value(),
129
+ access_key_secret=self.access_key_secret.resolve_value(),
130
+ )
131
+ self._translator = Translator(credentials=credentials)
132
+
133
+ @component.output_types(documents=list[Document])
134
+ def run(
135
+ self,
136
+ documents: list[Document],
137
+ source_lang: str | list[str | None] | None = None,
138
+ target_lang: str | list[str] | None = None,
139
+ context: str | list[str] | None = None,
140
+ instructions: str | list[str] | None = None,
141
+ style: str | list[str] | None = None,
142
+ adapt_to: list[str] | list[list[str]] | None = None,
143
+ glossaries: list[str] | list[list[str]] | None = None,
144
+ reasoning: bool | list[bool] | None = None,
145
+ ) -> dict[str, list[Document]]:
146
+ """
147
+ Translate the text content of each input Document using the Lara API.
148
+
149
+ Any of the translation parameters (source_lang, target_lang, context,
150
+ instructions, style, adapt_to, glossaries, reasoning) can be passed here
151
+ to override the defaults set when creating the component. They can be a single value
152
+ (applied to all documents) or a list of values with the same length as
153
+ `documents` for per-document settings.
154
+
155
+ :param documents:
156
+ List of Haystack Documents whose `content` is to be translated.
157
+ :param source_lang:
158
+ Source language code(s). Use locale codes from the
159
+ [supported languages list](https://developers.laratranslate.com/docs/supported-languages).
160
+ If `None`, Lara auto-detects the source language. Single value or list (one per document).
161
+ :param target_lang:
162
+ Target language code(s). Use locale codes from the
163
+ [supported languages list](https://developers.laratranslate.com/docs/supported-languages).
164
+ Single value or list (one per document).
165
+ :param context:
166
+ Optional external context: text that is not translated but is sent to Lara to
167
+ improve translation quality (e.g. surrounding sentences, prior messages).
168
+ You can find more detailed information in the
169
+ [Lara documentation](https://developers.laratranslate.com/docs/adapt-to-context).
170
+ :param instructions:
171
+ Optional natural-language instructions to guide translation and specify
172
+ domain-specific terminology (e.g. "Be formal", "Use a professional tone").
173
+ You can find more detailed information in the
174
+ [Lara documentation](https://developers.laratranslate.com/docs/adapt-to-instructions).
175
+ :param style:
176
+ One of `"faithful"`, `"fluid"`, or `"creative"`.
177
+ Style description:
178
+ - `"faithful"`: For accuracy and precision. Keeps original structure and meaning.
179
+ Ideal for manuals, legal documents.
180
+ - `"fluid"`: For readability and natural flow. Smooth, conversational. Good for general content.
181
+ - `"creative"`: For artistic and creative expression. Best for literature, marketing, or content
182
+ where impact and tone matter more than literal wording.
183
+ You can find more detailed information in the
184
+ [Lara documentation](https://support.laratranslate.com/en/translation-styles).
185
+ :param adapt_to:
186
+ Optional list of translation memory IDs. Lara adapts to the style and terminology
187
+ of these memories at inference time. Domain adaptation is available depending on your plan.
188
+ You can find more detailed information in the
189
+ [Lara documentation](https://developers.laratranslate.com/docs/adapt-to-translation-memories).
190
+ :param glossaries:
191
+ Optional list of glossary IDs. Lara applies these glossaries at inference time to enforce
192
+ consistent terminology (e.g. brand names, product terms, legal or technical phrases) across translations.
193
+ Glossary management and availability depends on your plan.
194
+ You can find more detailed information in the
195
+ [Lara documentation](https://developers.laratranslate.com/docs/manage-glossaries).
196
+ :param reasoning:
197
+ If `True`, uses the Lara Think model for higher-quality translation (multi-step linguistic analysis).
198
+ Increases latency and cost. Availability depends on your plan. You can find more detailed information in the
199
+ [Lara documentation](https://developers.laratranslate.com/docs/translate-text#reasoning-lara-think).
200
+ :return:
201
+ A dictionary with the following keys:
202
+ - `documents`: A list of translated documents.
203
+
204
+ :raises ValueError: If any list-valued parameter has length != `len(documents)`.
205
+ """
206
+ if not documents:
207
+ return {"documents": []}
208
+
209
+ if self._translator is None:
210
+ self.warm_up()
211
+
212
+ source_lang = source_lang or self.source_lang
213
+ target_lang = target_lang or self.target_lang
214
+ context = context or self.context
215
+ instructions = instructions or self.instructions
216
+ style = style or self.style
217
+ adapt_to = adapt_to or self.adapt_to
218
+ glossaries = glossaries or self.glossaries
219
+ reasoning = reasoning or self.reasoning
220
+
221
+ validated_params = self._validate_params(
222
+ len(documents),
223
+ source_lang,
224
+ target_lang,
225
+ context,
226
+ style,
227
+ instructions,
228
+ adapt_to,
229
+ glossaries,
230
+ reasoning,
231
+ )
232
+
233
+ translated_documents = []
234
+ for idx, cur_doc in enumerate(documents):
235
+ if not cur_doc.content:
236
+ logger.warning(f"Document {cur_doc.id} has no content, skipping translation.")
237
+ translation = cur_doc.content
238
+ else:
239
+ params = {key: value[idx] for key, value in validated_params.items()}
240
+ text_blocks = [TextBlock(text=cur_doc.content, translatable=True)]
241
+ if params["context"] is not None:
242
+ text_blocks.append(TextBlock(text=params["context"], translatable=False))
243
+
244
+ # Ignoring type because the lara client is only initialized after warm_up and None before
245
+ translation_response = self._translator.translate( # type: ignore[union-attr]
246
+ text=text_blocks,
247
+ source=params["source_lang"],
248
+ target=params["target_lang"],
249
+ instructions=params["instructions"],
250
+ style=params["style"],
251
+ adapt_to=params["adapt_to"],
252
+ glossaries=params["glossaries"],
253
+ reasoning=params["reasoning"],
254
+ )
255
+ translation = translation_response.translation[0].text
256
+
257
+ meta = {"original_document_id": cur_doc.id, **cur_doc.meta}
258
+ translated_doc = Document(content=translation, meta=meta)
259
+ translated_documents.append(translated_doc)
260
+
261
+ return {"documents": translated_documents}
262
+
263
+ @staticmethod
264
+ def _normalize_parameter(
265
+ name: str,
266
+ value: Any,
267
+ num_documents: int,
268
+ allow_list_of_lists: bool = False,
269
+ wrap_scalar: bool = False,
270
+ ) -> list[Any]:
271
+ """
272
+ Validate a single translation parameter and broadcast it to a per-document list.
273
+
274
+ :param name: Human-readable parameter name used in error messages.
275
+ :param value: The raw parameter value (scalar, list, or list-of-lists).
276
+ :param num_documents: Expected number of documents.
277
+ :param allow_list_of_lists: If True, treat a list whose first element is
278
+ itself a list as already per-document (used for adapt_to / glossaries).
279
+ :param wrap_scalar: If True and value is a non-None scalar, wrap it in a
280
+ single-element list before replicating (used for instructions).
281
+ :return: A list of length `num_documents`.
282
+ :raises ValueError: If a list-valued parameter has the wrong length.
283
+ """
284
+ if allow_list_of_lists:
285
+ is_per_doc = isinstance(value, list) and len(value) > 0 and isinstance(value[0], list)
286
+ if is_per_doc:
287
+ if len(value) != num_documents:
288
+ msg = f"If {name} is a list of lists, it must be the same length as the number of documents."
289
+ raise ValueError(msg)
290
+ return value
291
+ return [value] * num_documents
292
+
293
+ if isinstance(value, list):
294
+ if len(value) != num_documents:
295
+ msg = f"If {name} is a list, it must be the same length as the number of documents."
296
+ raise ValueError(msg)
297
+ return value
298
+
299
+ if wrap_scalar and value is not None:
300
+ value = [value]
301
+ return [value] * num_documents
302
+
303
+ def _validate_params(
304
+ self,
305
+ num_documents: int,
306
+ source_lang: str | list[str | None] | None,
307
+ target_lang: str | list[str] | None,
308
+ context: str | list[str] | None,
309
+ style: str | list[str] | None,
310
+ instructions: str | list[str] | None,
311
+ adapt_to: list[str] | list[list[str]] | None,
312
+ glossaries: list[str] | list[list[str]] | None,
313
+ reasoning: bool | list[bool] | None,
314
+ ) -> dict[str, list[Any]]:
315
+ """
316
+ Validates translation parameters and normalizes them to per-document lists.
317
+
318
+ :param num_documents: Number of documents in the current batch.
319
+ :param source_lang: Source language (scalar or list of length num_documents).
320
+ :param target_lang: Target language (scalar or list of length num_documents).
321
+ :param context: Context (scalar or list of length num_documents).
322
+ :param style: Style (scalar or list of length num_documents).
323
+ :param instructions: Instructions (scalar or list of length num_documents).
324
+ :param adapt_to: Adaptation memory IDs (list or list of lists, one per doc).
325
+ :param glossaries: Glossary IDs (list or list of lists, one per doc).
326
+ :param reasoning: Reasoning flag (scalar or list of length num_documents).
327
+ :return: Dictionary mapping each parameter name to a list of length
328
+ `num_documents`.
329
+ :raises ValueError: If any list-valued parameter has length != num_documents.
330
+ """
331
+ return {
332
+ "source_lang": self._normalize_parameter("source language", source_lang, num_documents),
333
+ "target_lang": self._normalize_parameter("target language", target_lang, num_documents),
334
+ "context": self._normalize_parameter("context", context, num_documents),
335
+ "style": self._normalize_parameter("style", style, num_documents),
336
+ "instructions": self._normalize_parameter("instructions", instructions, num_documents, wrap_scalar=True),
337
+ "reasoning": self._normalize_parameter("reasoning", reasoning, num_documents),
338
+ "adapt_to": self._normalize_parameter("adapt to", adapt_to, num_documents, allow_list_of_lists=True),
339
+ "glossaries": self._normalize_parameter("glossaries", glossaries, num_documents, allow_list_of_lists=True),
340
+ }
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,470 @@
1
+ # SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import os
6
+ from unittest.mock import MagicMock, patch
7
+
8
+ import pytest
9
+ from haystack import Document
10
+ from haystack.core.serialization import component_from_dict, component_to_dict
11
+ from haystack.utils import Secret
12
+
13
+ from haystack_integrations.components.translators.lara import LaraDocumentTranslator
14
+
15
+
16
+ class TestLaraDocumentTranslator:
17
+ @pytest.fixture
18
+ def mock_translation_response(self):
19
+ mock_block = MagicMock()
20
+ mock_block.text = "Translated text"
21
+ mock_response = MagicMock()
22
+ mock_response.translation = [mock_block]
23
+ return mock_response
24
+
25
+ def test_init_default(self, monkeypatch):
26
+ monkeypatch.setenv("LARA_ACCESS_KEY_ID", "test-access-key-id")
27
+ monkeypatch.setenv("LARA_ACCESS_KEY_SECRET", "test-access-key-secret")
28
+ translator = LaraDocumentTranslator()
29
+ assert translator.access_key_id.resolve_value() == "test-access-key-id"
30
+ assert translator.access_key_secret.resolve_value() == "test-access-key-secret"
31
+ assert translator.source_lang is None
32
+ assert translator.target_lang is None
33
+ assert translator.context is None
34
+ assert translator.instructions is None
35
+ assert translator.style == "faithful"
36
+ assert translator.adapt_to is None
37
+ assert translator.glossaries is None
38
+ assert translator.reasoning is False
39
+ assert translator._translator is None
40
+
41
+ def test_init_with_parameters(self):
42
+ translator = LaraDocumentTranslator(
43
+ access_key_id=Secret.from_token("key-id"),
44
+ access_key_secret=Secret.from_token("key-secret"),
45
+ source_lang="en-US",
46
+ target_lang="de-DE",
47
+ context="Prior message.",
48
+ instructions=["Be formal"],
49
+ style="fluid",
50
+ adapt_to=["tm-1"],
51
+ glossaries=["glossary-1"],
52
+ reasoning=True,
53
+ )
54
+ assert translator.access_key_id.resolve_value() == "key-id"
55
+ assert translator.access_key_secret.resolve_value() == "key-secret"
56
+ assert translator.source_lang == "en-US"
57
+ assert translator.target_lang == "de-DE"
58
+ assert translator.context == "Prior message."
59
+ assert translator.instructions == ["Be formal"]
60
+ assert translator.style == "fluid"
61
+ assert translator.adapt_to == ["tm-1"]
62
+ assert translator.glossaries == ["glossary-1"]
63
+ assert translator.reasoning is True
64
+
65
+ def test_from_dict(self, monkeypatch):
66
+ monkeypatch.setenv("LARA_ACCESS_KEY_ID", "from-env-id")
67
+ monkeypatch.setenv("LARA_ACCESS_KEY_SECRET", "from-env-secret")
68
+ data = {
69
+ "type": "haystack_integrations.components.translators.lara.document_translator.LaraDocumentTranslator",
70
+ "init_parameters": {
71
+ "access_key_id": {"env_vars": ["LARA_ACCESS_KEY_ID"], "strict": False, "type": "env_var"},
72
+ "access_key_secret": {"env_vars": ["LARA_ACCESS_KEY_SECRET"], "strict": False, "type": "env_var"},
73
+ "source_lang": "en",
74
+ "target_lang": "fr",
75
+ "style": "creative",
76
+ },
77
+ }
78
+ translator = component_from_dict(LaraDocumentTranslator, data, "document_translator")
79
+ assert translator.source_lang == "en"
80
+ assert translator.target_lang == "fr"
81
+ assert translator.style == "creative"
82
+ assert translator.access_key_id.resolve_value() == "from-env-id"
83
+ assert translator.access_key_secret.resolve_value() == "from-env-secret"
84
+
85
+ def test_to_dict(self):
86
+ translator = LaraDocumentTranslator(
87
+ source_lang="en-US",
88
+ target_lang="de-DE",
89
+ )
90
+ data = component_to_dict(translator, "document_translator")
91
+ assert data["type"] == (
92
+ "haystack_integrations.components.translators.lara.document_translator.LaraDocumentTranslator"
93
+ )
94
+ init_params = data["init_parameters"]
95
+ assert init_params["source_lang"] == "en-US"
96
+ assert init_params["target_lang"] == "de-DE"
97
+ assert "access_key_id" in init_params
98
+ assert "access_key_secret" in init_params
99
+
100
+ def test_run_single_document(self, mock_translation_response):
101
+ translator = LaraDocumentTranslator(
102
+ access_key_id=Secret.from_token("key-id"),
103
+ access_key_secret=Secret.from_token("key-secret"),
104
+ source_lang="en-US",
105
+ target_lang="de-DE",
106
+ )
107
+ doc = Document(content="Hello, world!", meta={"source": "test"})
108
+
109
+ with patch(
110
+ "haystack_integrations.components.translators.lara.document_translator.Translator"
111
+ ) as mock_translator_cls:
112
+ mock_translator = MagicMock()
113
+ mock_translator.translate.return_value = mock_translation_response
114
+ mock_translator_cls.return_value = mock_translator
115
+
116
+ result = translator.run(documents=[doc])
117
+
118
+ assert len(result["documents"]) == 1
119
+ out_doc = result["documents"][0]
120
+ assert out_doc.content == "Translated text"
121
+ assert out_doc.meta["original_document_id"] == doc.id
122
+ assert out_doc.meta["source"] == "test"
123
+ mock_translator.translate.assert_called_once()
124
+ call_kwargs = mock_translator.translate.call_args.kwargs
125
+ assert call_kwargs["source"] == "en-US"
126
+ assert call_kwargs["target"] == "de-DE"
127
+
128
+ def test_run_multiple_documents(self, mock_translation_response):
129
+ translator = LaraDocumentTranslator(
130
+ access_key_id=Secret.from_token("key-id"),
131
+ access_key_secret=Secret.from_token("key-secret"),
132
+ target_lang="de-DE",
133
+ )
134
+ doc1 = Document(content="First")
135
+ doc2 = Document(content="Second")
136
+
137
+ with patch(
138
+ "haystack_integrations.components.translators.lara.document_translator.Translator"
139
+ ) as mock_translator_cls:
140
+ mock_translator = MagicMock()
141
+ mock_translator.translate.return_value = mock_translation_response
142
+ mock_translator_cls.return_value = mock_translator
143
+
144
+ result = translator.run(documents=[doc1, doc2])
145
+
146
+ assert len(result["documents"]) == 2
147
+ assert result["documents"][0].content == "Translated text"
148
+ assert result["documents"][1].content == "Translated text"
149
+ assert result["documents"][0].meta["original_document_id"] == doc1.id
150
+ assert result["documents"][1].meta["original_document_id"] == doc2.id
151
+ assert mock_translator.translate.call_count == 2
152
+
153
+ def test_run_with_context_appends_non_translatable_block(self, mock_translation_response):
154
+ translator = LaraDocumentTranslator(
155
+ access_key_id=Secret.from_token("key-id"),
156
+ access_key_secret=Secret.from_token("key-secret"),
157
+ target_lang="de-DE",
158
+ context="Surrounding sentence.",
159
+ )
160
+ doc = Document(content="Translate this.")
161
+
162
+ with patch(
163
+ "haystack_integrations.components.translators.lara.document_translator.Translator"
164
+ ) as mock_translator_cls:
165
+ mock_translator = MagicMock()
166
+ mock_translator.translate.return_value = mock_translation_response
167
+ mock_translator_cls.return_value = mock_translator
168
+
169
+ translator.run(documents=[doc])
170
+
171
+ call_args = mock_translator.translate.call_args
172
+ text_blocks = call_args.kwargs["text"]
173
+ assert len(text_blocks) == 2
174
+ assert text_blocks[0].text == "Translate this."
175
+ assert text_blocks[0].translatable is True
176
+ assert text_blocks[1].text == "Surrounding sentence."
177
+ assert text_blocks[1].translatable is False
178
+
179
+ def test_run_overrides_from_init(self, mock_translation_response):
180
+ translator = LaraDocumentTranslator(
181
+ access_key_id=Secret.from_token("key-id"),
182
+ access_key_secret=Secret.from_token("key-secret"),
183
+ source_lang="en-US",
184
+ target_lang="fr-FR",
185
+ style="faithful",
186
+ )
187
+ doc = Document(content="Hi")
188
+
189
+ with patch(
190
+ "haystack_integrations.components.translators.lara.document_translator.Translator"
191
+ ) as mock_translator_cls:
192
+ mock_translator = MagicMock()
193
+ mock_translator.translate.return_value = mock_translation_response
194
+ mock_translator_cls.return_value = mock_translator
195
+
196
+ translator.run(
197
+ documents=[doc],
198
+ source_lang="en-GB",
199
+ target_lang="es-ES",
200
+ style="creative",
201
+ )
202
+
203
+ call_kwargs = mock_translator.translate.call_args.kwargs
204
+ assert call_kwargs["source"] == "en-GB"
205
+ assert call_kwargs["target"] == "es-ES"
206
+ assert call_kwargs["style"] == "creative"
207
+
208
+ def test_run_no_documents(self):
209
+ translator = LaraDocumentTranslator(
210
+ access_key_id=Secret.from_token("key-id"),
211
+ access_key_secret=Secret.from_token("key-secret"),
212
+ target_lang="de-DE",
213
+ )
214
+ with patch(
215
+ "haystack_integrations.components.translators.lara.document_translator.Translator"
216
+ ) as mock_translator_cls:
217
+ mock_translator = MagicMock()
218
+ mock_translator_cls.return_value = mock_translator
219
+ result = translator.run(documents=[])
220
+ assert result["documents"] == []
221
+ mock_translator.translate.assert_not_called()
222
+
223
+ def test_run_with_no_content_document(self):
224
+ translator = LaraDocumentTranslator(
225
+ access_key_id=Secret.from_token("key-id"),
226
+ access_key_secret=Secret.from_token("key-secret"),
227
+ target_lang="de-DE",
228
+ )
229
+ doc = Document(content="")
230
+ with patch(
231
+ "haystack_integrations.components.translators.lara.document_translator.Translator"
232
+ ) as mock_translator_cls:
233
+ mock_translator = MagicMock()
234
+ mock_translator_cls.return_value = mock_translator
235
+ result = translator.run(documents=[doc])
236
+
237
+ assert result["documents"][0].content == ""
238
+ assert result["documents"][0].meta["original_document_id"] == doc.id
239
+ mock_translator.translate.assert_not_called()
240
+
241
+ def test_validate_params_scalar_expanded_to_list(self):
242
+ translator = LaraDocumentTranslator()
243
+ result = translator._validate_params(
244
+ num_documents=3,
245
+ source_lang="en-US",
246
+ target_lang="de-DE",
247
+ context="ctx",
248
+ style="fluid",
249
+ instructions="Be formal",
250
+ adapt_to=["tm-1"],
251
+ glossaries=["g1"],
252
+ reasoning=False,
253
+ )
254
+ assert result["source_lang"] == ["en-US", "en-US", "en-US"]
255
+ assert result["target_lang"] == ["de-DE", "de-DE", "de-DE"]
256
+ assert result["context"] == ["ctx", "ctx", "ctx"]
257
+ assert result["style"] == ["fluid", "fluid", "fluid"]
258
+ assert result["reasoning"] == [False, False, False]
259
+ assert len(result["instructions"]) == 3
260
+ assert len(result["adapt_to"]) == 3
261
+ assert len(result["glossaries"]) == 3
262
+
263
+ def test_validate_params_list_per_document(self):
264
+ translator = LaraDocumentTranslator()
265
+ result = translator._validate_params(
266
+ num_documents=2,
267
+ source_lang=["en-US", "fr-FR"],
268
+ target_lang=["de-DE", "es-ES"],
269
+ context=None,
270
+ style=["faithful", "creative"],
271
+ instructions=[["Formal"], ["Casual"]],
272
+ adapt_to=[["tm-1"], ["tm-2"]],
273
+ glossaries=[["g1"], ["g2"]],
274
+ reasoning=[True, False],
275
+ )
276
+ assert result["source_lang"] == ["en-US", "fr-FR"]
277
+ assert result["target_lang"] == ["de-DE", "es-ES"]
278
+ assert result["style"] == ["faithful", "creative"]
279
+ assert result["instructions"] == [["Formal"], ["Casual"]]
280
+ assert result["adapt_to"] == [["tm-1"], ["tm-2"]]
281
+ assert result["glossaries"] == [["g1"], ["g2"]]
282
+ assert result["reasoning"] == [True, False]
283
+
284
+ def test_validate_params_source_lang_list_wrong_length_raises(self):
285
+ with pytest.raises(ValueError, match="source language is a list, it must be the same length"):
286
+ translator = LaraDocumentTranslator()
287
+ translator._validate_params(
288
+ num_documents=2,
289
+ source_lang=["en-US", "fr-FR", "es-ES"],
290
+ target_lang="de-DE",
291
+ context=None,
292
+ style=None,
293
+ instructions=None,
294
+ adapt_to=None,
295
+ glossaries=None,
296
+ reasoning=None,
297
+ )
298
+
299
+ def test_validate_params_target_lang_list_wrong_length_raises(self):
300
+ with pytest.raises(ValueError, match="target language is a list, it must be the same length"):
301
+ translator = LaraDocumentTranslator()
302
+ translator._validate_params(
303
+ num_documents=2,
304
+ source_lang=None,
305
+ target_lang=["de-DE"],
306
+ context=None,
307
+ style=None,
308
+ instructions=None,
309
+ adapt_to=None,
310
+ glossaries=None,
311
+ reasoning=None,
312
+ )
313
+
314
+ def test_validate_params_context_list_wrong_length_raises(self):
315
+ with pytest.raises(ValueError, match="context is a list, it must be the same length"):
316
+ translator = LaraDocumentTranslator()
317
+ translator._validate_params(
318
+ num_documents=2,
319
+ source_lang=None,
320
+ target_lang="de-DE",
321
+ context=["c1", "c2", "c3"],
322
+ style=None,
323
+ instructions=None,
324
+ adapt_to=None,
325
+ glossaries=None,
326
+ reasoning=None,
327
+ )
328
+
329
+ def test_validate_params_style_list_wrong_length_raises(self):
330
+ with pytest.raises(ValueError, match="style is a list, it must be the same length"):
331
+ translator = LaraDocumentTranslator()
332
+ translator._validate_params(
333
+ num_documents=2,
334
+ source_lang=None,
335
+ target_lang="de-DE",
336
+ context=None,
337
+ style=["faithful"],
338
+ instructions=None,
339
+ adapt_to=None,
340
+ glossaries=None,
341
+ reasoning=None,
342
+ )
343
+
344
+ def test_validate_params_instructions_list_wrong_length_raises(self):
345
+ with pytest.raises(ValueError, match="instructions is a list, it must be the same length"):
346
+ translator = LaraDocumentTranslator()
347
+ translator._validate_params(
348
+ num_documents=2,
349
+ source_lang=None,
350
+ target_lang="de-DE",
351
+ context=None,
352
+ style=None,
353
+ instructions=[["a"], ["b"], ["c"]],
354
+ adapt_to=None,
355
+ glossaries=None,
356
+ reasoning=None,
357
+ )
358
+
359
+ def test_validate_params_reasoning_list_wrong_length_raises(self):
360
+ with pytest.raises(ValueError, match="reasoning is a list, it must be the same length"):
361
+ translator = LaraDocumentTranslator()
362
+ translator._validate_params(
363
+ num_documents=2,
364
+ source_lang=None,
365
+ target_lang="de-DE",
366
+ context=None,
367
+ style=None,
368
+ instructions=None,
369
+ adapt_to=None,
370
+ glossaries=None,
371
+ reasoning=[True, False, True],
372
+ )
373
+
374
+ def test_validate_params_adapt_to_list_of_lists_wrong_length_raises(self):
375
+ with pytest.raises(ValueError, match="adapt to is a list of lists, it must be the same length"):
376
+ translator = LaraDocumentTranslator()
377
+ translator._validate_params(
378
+ num_documents=2,
379
+ source_lang=None,
380
+ target_lang="de-DE",
381
+ context=None,
382
+ style=None,
383
+ instructions=None,
384
+ adapt_to=[["tm-1"], ["tm-2"], ["tm-3"]],
385
+ glossaries=None,
386
+ reasoning=None,
387
+ )
388
+
389
+ def test_validate_params_glossaries_list_of_lists_wrong_length_raises(self):
390
+ with pytest.raises(ValueError, match="glossaries is a list of lists, it must be the same length"):
391
+ translator = LaraDocumentTranslator()
392
+ translator._validate_params(
393
+ num_documents=2,
394
+ source_lang=None,
395
+ target_lang="de-DE",
396
+ context=None,
397
+ style=None,
398
+ instructions=None,
399
+ adapt_to=None,
400
+ glossaries=[["g1"], ["g2"], ["g3"]],
401
+ reasoning=None,
402
+ )
403
+
404
+ def test_run_list_param_length_mismatch_raises(self):
405
+ translator = LaraDocumentTranslator(
406
+ access_key_id=Secret.from_token("key-id"),
407
+ access_key_secret=Secret.from_token("key-secret"),
408
+ target_lang="de-DE",
409
+ )
410
+ doc1 = Document(content="One")
411
+ doc2 = Document(content="Two")
412
+
413
+ with patch("haystack_integrations.components.translators.lara.document_translator.Translator"):
414
+ with pytest.raises(ValueError, match="source language is a list, it must be the same length"):
415
+ translator.run(
416
+ documents=[doc1, doc2],
417
+ source_lang=["en-US"],
418
+ )
419
+
420
+ def test_run_per_document_params(self):
421
+ translator = LaraDocumentTranslator(
422
+ access_key_id=Secret.from_token("key-id"),
423
+ access_key_secret=Secret.from_token("key-secret"),
424
+ source_lang="en-US",
425
+ target_lang="de-DE",
426
+ )
427
+ doc1 = Document(content="One")
428
+ doc2 = Document(content="Two")
429
+
430
+ responses = [
431
+ MagicMock(translation=[MagicMock(text="Eins")]),
432
+ MagicMock(translation=[MagicMock(text="Zwei")]),
433
+ ]
434
+
435
+ with patch(
436
+ "haystack_integrations.components.translators.lara.document_translator.Translator"
437
+ ) as mock_translator_cls:
438
+ mock_translator = MagicMock()
439
+ mock_translator.translate.side_effect = responses
440
+ mock_translator_cls.return_value = mock_translator
441
+
442
+ translator.run(
443
+ documents=[doc1, doc2],
444
+ source_lang=["en-US", "fr-FR"],
445
+ target_lang=["de-DE", "es-ES"],
446
+ )
447
+
448
+ assert mock_translator.translate.call_count == 2
449
+ first_call = mock_translator.translate.call_args_list[0].kwargs
450
+ second_call = mock_translator.translate.call_args_list[1].kwargs
451
+ assert first_call["source"] == "en-US" and first_call["target"] == "de-DE"
452
+ assert second_call["source"] == "fr-FR" and second_call["target"] == "es-ES"
453
+
454
+ @pytest.mark.integration
455
+ @pytest.mark.skipif(
456
+ not os.environ.get("LARA_ACCESS_KEY_ID") or not os.environ.get("LARA_ACCESS_KEY_SECRET"),
457
+ reason="LARA_ACCESS_KEY_ID and LARA_ACCESS_KEY_SECRET must be set to run integration tests",
458
+ )
459
+ def test_run_translates_document_via_lara_api(self):
460
+ """Translates a document using the real Lara API (no mocks)."""
461
+ translator = LaraDocumentTranslator(
462
+ source_lang="en-US",
463
+ target_lang="de-DE",
464
+ )
465
+ doc = Document(content="Hello, world!", meta={"source": "integration_test"})
466
+
467
+ result = translator.run(documents=[doc])
468
+ assert result["documents"][0].content
469
+ assert result["documents"][0].content != doc.content
470
+ assert "Hallo" in result["documents"][0].content or "Welt" in result["documents"][0].content