spacy-haystack 0.1.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,201 @@
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,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023-present deepset GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: spacy-haystack
3
+ Version: 0.1.0
4
+ Summary: Haystack integration for spacy
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/spacy#readme
6
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
7
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/spacy
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: Implementation :: CPython
20
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: click>=8.0.0
23
+ Requires-Dist: haystack-ai>=2.23.0
24
+ Requires-Dist: spacy<3.9,>=3.8.13
25
+ Description-Content-Type: text/markdown
26
+
27
+ # spacy-haystack
28
+
29
+ [![PyPI - Version](https://img.shields.io/pypi/v/spacy-haystack.svg)](https://pypi.org/project/spacy-haystack)
30
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/spacy-haystack.svg)](https://pypi.org/project/spacy-haystack)
31
+
32
+ - [Integration page](https://haystack.deepset.ai/integrations/spacy)
33
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/spacy/CHANGELOG.md)
34
+
35
+ ---
36
+
37
+ ## Contributing
38
+
39
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,13 @@
1
+ # spacy-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/spacy-haystack.svg)](https://pypi.org/project/spacy-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/spacy-haystack.svg)](https://pypi.org/project/spacy-haystack)
5
+
6
+ - [Integration page](https://haystack.deepset.ai/integrations/spacy)
7
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/spacy/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).
@@ -0,0 +1,13 @@
1
+ loaders:
2
+ - modules:
3
+ - haystack_integrations.components.extractors.spacy.named_entity_extractor
4
+ search_path: [../src]
5
+ processors:
6
+ - type: filter
7
+ documented_only: true
8
+ skip_empty_modules: true
9
+ renderer:
10
+ description: Spacy integration for Haystack
11
+ id: integrations-spacy
12
+ filename: spacy.md
13
+ title: Spacy
@@ -0,0 +1,165 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "spacy-haystack"
7
+ dynamic = ["version"]
8
+ description = "Haystack integration for spacy"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ keywords = []
13
+ authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
14
+ classifiers = [
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Development Status :: 4 - Beta",
17
+ "Programming Language :: Python",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Programming Language :: Python :: Implementation :: CPython",
24
+ "Programming Language :: Python :: Implementation :: PyPy",
25
+ ]
26
+ # `click` is required to make spacy work but not declared by spacy itself.
27
+ # See https://github.com/explosion/spaCy/issues/13971
28
+ dependencies = ["haystack-ai>=2.23.0", "spacy>=3.8.13,<3.9", "click>=8.0.0"]
29
+
30
+ [project.urls]
31
+ Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/spacy#readme"
32
+ Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
33
+ Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/spacy"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["src/haystack_integrations"]
37
+
38
+ [tool.hatch.version]
39
+ source = "vcs"
40
+ tag-pattern = 'integrations\/spacy-v(?P<version>.*)'
41
+
42
+ [tool.hatch.version.raw-options]
43
+ root = "../.."
44
+ git_describe_command = 'git describe --tags --match="integrations/spacy-v[0-9]*"'
45
+
46
+ [tool.hatch.envs.default]
47
+ installer = "uv"
48
+ dependencies = ["haystack-pydoc-tools", "ruff"]
49
+
50
+ [tool.hatch.envs.default.scripts]
51
+ docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
52
+ fmt = "ruff check --fix {args}; ruff format {args}"
53
+ fmt-check = "ruff check {args} && ruff format --check {args}"
54
+
55
+ [tool.hatch.envs.test]
56
+ dependencies = [
57
+ "pytest",
58
+ "pytest-asyncio",
59
+ "pytest-cov",
60
+ "pytest-rerunfailures",
61
+ "mypy",
62
+ "pip",
63
+ # spaCy model used by the integration tests
64
+ "en-core-web-trf @ https://github.com/explosion/spacy-models/releases/download/en_core_web_trf-3.8.0/en_core_web_trf-3.8.0-py3-none-any.whl",
65
+ ]
66
+
67
+ [tool.hatch.envs.test.scripts]
68
+ unit = 'pytest -m "not integration" {args:tests}'
69
+ integration = 'pytest -m "integration" {args:tests}'
70
+ all = 'pytest {args:tests}'
71
+ unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}'
72
+ integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}'
73
+ types = "mypy -p haystack_integrations.components.extractors.spacy {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.ruff]
82
+ line-length = 120
83
+
84
+ [tool.ruff.lint]
85
+ select = [
86
+ "A",
87
+ "ANN",
88
+ "ARG",
89
+ "B",
90
+ "C",
91
+ "D102", # Missing docstring in public method
92
+ "D103", # Missing docstring in public function
93
+ "D205", # 1 blank line required between summary line and description
94
+ "D209", # Closing triple quotes go to new line
95
+ "D213", # summary lines must be positioned on the second physical line of the docstring
96
+ "D417", # Missing argument descriptions in the docstring
97
+ "D419", # Docstring is empty
98
+ "DTZ",
99
+ "E",
100
+ "EM",
101
+ "F",
102
+ "I",
103
+ "ICN",
104
+ "ISC",
105
+ "N",
106
+ "PLC",
107
+ "PLE",
108
+ "PLR",
109
+ "PLW",
110
+ "Q",
111
+ "RUF",
112
+ "S",
113
+ "T",
114
+ "TID",
115
+ "UP",
116
+ "W",
117
+ "YTT",
118
+ ]
119
+ ignore = [
120
+ # Allow non-abstract empty methods in abstract base classes
121
+ "B027",
122
+ # Allow function calls in argument defaults (common Haystack pattern for Secret.from_env_var)
123
+ "B008",
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
+ # Allow `Any` type - used legitimately for dynamic types and SDK boundaries
135
+ "ANN401",
136
+ ]
137
+
138
+ [tool.ruff.lint.isort]
139
+ known-first-party = ["haystack_integrations"]
140
+
141
+ [tool.ruff.lint.flake8-tidy-imports]
142
+ ban-relative-imports = "parents"
143
+
144
+ [tool.ruff.lint.per-file-ignores]
145
+ # Tests can use magic values, assertions, relative imports, and don't need type annotations
146
+ "tests/**/*" = ["PLR2004", "S101", "TID252", "D", "ANN"]
147
+
148
+ [tool.coverage.run]
149
+ source = ["haystack_integrations"]
150
+ branch = true
151
+ parallel = false
152
+ relative_files = true
153
+
154
+ [tool.coverage.report]
155
+ omit = ["*/tests/*", "*/__init__.py"]
156
+ show_missing = true
157
+ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
158
+
159
+ [tool.pytest.ini_options]
160
+ addopts = "--strict-markers"
161
+ markers = [
162
+ "integration: integration tests",
163
+ ]
164
+ log_cli = true
165
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,6 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from .named_entity_extractor import NamedEntityAnnotation, SpacyNamedEntityExtractor
5
+
6
+ __all__ = ["NamedEntityAnnotation", "SpacyNamedEntityExtractor"]
@@ -0,0 +1,255 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from collections.abc import Iterator
6
+ from contextlib import contextmanager
7
+ from dataclasses import dataclass, replace
8
+ from typing import Any
9
+
10
+ from haystack import ComponentError, DeserializationError, Document, component, default_from_dict, default_to_dict
11
+ from haystack.utils.device import ComponentDevice
12
+ from thinc.api import get_current_ops, set_current_ops
13
+
14
+ import spacy
15
+ from spacy import Language as SpacyPipeline
16
+
17
+
18
+ @dataclass
19
+ class NamedEntityAnnotation:
20
+ """
21
+ Describes a single NER annotation.
22
+
23
+ :param entity:
24
+ Entity label.
25
+ :param start:
26
+ Start index of the entity in the document.
27
+ :param end:
28
+ End index of the entity in the document.
29
+ :param score:
30
+ Score calculated by the model.
31
+ """
32
+
33
+ entity: str
34
+ start: int
35
+ end: int
36
+ score: float | None = None
37
+
38
+
39
+ @component
40
+ class SpacyNamedEntityExtractor:
41
+ """
42
+ Annotates named entities in a collection of documents.
43
+
44
+ The component can be used with any [spaCy model](https://spacy.io/models) that contains
45
+ an NER component. Annotations are stored as metadata in the documents.
46
+
47
+ Usage example:
48
+ ```python
49
+ from haystack import Document
50
+
51
+ from haystack_integrations.components.extractors.spacy import SpacyNamedEntityExtractor
52
+
53
+ documents = [
54
+ Document(content="I'm Merlin, the happy pig!"),
55
+ Document(content="My name is Clara and I live in Berkeley, California."),
56
+ ]
57
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_sm")
58
+ results = extractor.run(documents=documents)["documents"]
59
+ annotations = [SpacyNamedEntityExtractor.get_stored_annotations(doc) for doc in results]
60
+ print(annotations)
61
+ ```
62
+ """
63
+
64
+ _METADATA_KEY = "named_entities"
65
+
66
+ def __init__(
67
+ self,
68
+ *,
69
+ model: str,
70
+ pipeline_kwargs: dict[str, Any] | None = None,
71
+ device: ComponentDevice | None = None,
72
+ ) -> None:
73
+ """
74
+ Create a Named Entity extractor component.
75
+
76
+ :param model:
77
+ Name of the spaCy model or a path to the model on
78
+ the local disk.
79
+ :param pipeline_kwargs:
80
+ Keyword arguments passed to the pipeline. The
81
+ pipeline can override these arguments.
82
+ :param device:
83
+ The device on which the model is loaded. If `None`,
84
+ the default device is automatically selected.
85
+ :raises ValueError:
86
+ If the device represents multiple devices, which the
87
+ spaCy backend does not support.
88
+ """
89
+ self.model_name_or_path = model
90
+ self.pipeline_kwargs = pipeline_kwargs or {}
91
+ self.device = ComponentDevice.resolve_device(device)
92
+
93
+ if self.device.has_multiple_devices:
94
+ msg = "spaCy backend for named entity extractor only supports inference on single devices"
95
+ raise ValueError(msg)
96
+
97
+ self.pipeline: SpacyPipeline | None = None
98
+ self._warmed_up: bool = False
99
+
100
+ def warm_up(self) -> None:
101
+ """
102
+ Initialize the component.
103
+
104
+ :raises ComponentError:
105
+ If the component fails to initialize successfully.
106
+ """
107
+ if self._warmed_up:
108
+ return
109
+
110
+ try:
111
+ # We need to initialize the model on the GPU if needed.
112
+ with self._select_device():
113
+ self.pipeline = spacy.load(self.model_name_or_path)
114
+
115
+ if not self.pipeline.has_pipe("ner"):
116
+ msg = f"spaCy pipeline '{self.model_name_or_path}' does not contain an NER component"
117
+ raise ComponentError(msg)
118
+
119
+ # Disable unnecessary pipes.
120
+ pipes_to_keep = ("ner", "tok2vec", "transformer", "curated_transformer")
121
+ for name in self.pipeline.pipe_names:
122
+ if name not in pipes_to_keep:
123
+ self.pipeline.disable_pipe(name)
124
+
125
+ self.pipeline_kwargs = {k: v for k, v in self.pipeline_kwargs.items() if k not in ("texts", "batch_size")}
126
+ self._warmed_up = True
127
+ except Exception as e:
128
+ msg = f"{self.__class__.__name__} failed to initialize."
129
+ raise ComponentError(msg) from e
130
+
131
+ @component.output_types(documents=list[Document])
132
+ def run(self, documents: list[Document], batch_size: int = 1) -> dict[str, Any]:
133
+ """
134
+ Annotate named entities in each document and store the annotations in the document's metadata.
135
+
136
+ :param documents:
137
+ Documents to process.
138
+ :param batch_size:
139
+ Batch size used for processing the documents.
140
+ :returns:
141
+ Processed documents.
142
+ :raises ComponentError:
143
+ If the model fails to process a document.
144
+ """
145
+ if not self._warmed_up:
146
+ self.warm_up()
147
+
148
+ texts = [doc.content if doc.content is not None else "" for doc in documents]
149
+ annotations = self._annotate(texts, batch_size=batch_size)
150
+
151
+ if len(annotations) != len(documents):
152
+ msg = (
153
+ "NER model did not return the correct number of annotations; "
154
+ f"got {len(annotations)} but expected {len(documents)}"
155
+ )
156
+ raise ComponentError(msg)
157
+
158
+ new_documents = []
159
+ for doc, doc_annotations in zip(documents, annotations, strict=True):
160
+ new_meta = {**doc.meta, self._METADATA_KEY: doc_annotations}
161
+ new_documents.append(replace(doc, meta=new_meta))
162
+
163
+ return {"documents": new_documents}
164
+
165
+ def _annotate(self, texts: list[str], *, batch_size: int = 1) -> list[list[NamedEntityAnnotation]]:
166
+ """
167
+ Predict annotations for a collection of documents.
168
+
169
+ :param texts:
170
+ Raw texts to be annotated.
171
+ :param batch_size:
172
+ Size of text batches that are
173
+ passed to the model.
174
+ :returns:
175
+ NER annotations.
176
+ """
177
+ if not self.initialized:
178
+ msg = "NER model was not initialized - Did you call `warm_up()`?"
179
+ raise ComponentError(msg)
180
+
181
+ assert self.pipeline is not None # noqa: S101
182
+ with self._select_device():
183
+ outputs = list(self.pipeline.pipe(texts=texts, batch_size=batch_size, **self.pipeline_kwargs))
184
+
185
+ return [
186
+ [
187
+ NamedEntityAnnotation(entity=entity.label_, start=entity.start_char, end=entity.end_char)
188
+ for entity in doc.ents
189
+ ]
190
+ for doc in outputs
191
+ ]
192
+
193
+ def to_dict(self) -> dict[str, Any]:
194
+ """
195
+ Serializes the component to a dictionary.
196
+
197
+ :returns:
198
+ Dictionary with serialized data.
199
+ """
200
+ return default_to_dict(
201
+ self,
202
+ model=self.model_name_or_path,
203
+ device=self.device,
204
+ pipeline_kwargs=self.pipeline_kwargs,
205
+ )
206
+
207
+ @classmethod
208
+ def from_dict(cls, data: dict[str, Any]) -> "SpacyNamedEntityExtractor":
209
+ """
210
+ Deserializes the component from a dictionary.
211
+
212
+ :param data:
213
+ Dictionary to deserialize from.
214
+ :returns:
215
+ Deserialized component.
216
+ """
217
+ try:
218
+ return default_from_dict(cls, data)
219
+ except Exception as e:
220
+ msg = f"Couldn't deserialize {cls.__name__} instance"
221
+ raise DeserializationError(msg) from e
222
+
223
+ @property
224
+ def initialized(self) -> bool:
225
+ """
226
+ Returns if the extractor is ready to annotate text.
227
+ """
228
+ return self.pipeline is not None
229
+
230
+ @classmethod
231
+ def get_stored_annotations(cls, document: Document) -> list[NamedEntityAnnotation] | None:
232
+ """
233
+ Returns the document's named entity annotations stored in its metadata, if any.
234
+
235
+ :param document:
236
+ Document whose annotations are to be fetched.
237
+ :returns:
238
+ The stored annotations.
239
+ """
240
+
241
+ return document.meta.get(cls._METADATA_KEY)
242
+
243
+ @contextmanager
244
+ def _select_device(self) -> Iterator[None]:
245
+ """
246
+ Context manager used to run spaCy models on a specific GPU in a scoped manner.
247
+ """
248
+ device_id = self.device.to_spacy()
249
+ previous_ops = get_current_ops()
250
+ try:
251
+ if device_id >= 0:
252
+ spacy.require_gpu(device_id)
253
+ yield
254
+ finally:
255
+ set_current_ops(previous_ops)
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,339 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from unittest.mock import patch
6
+
7
+ import pytest
8
+ from haystack import ComponentError, DeserializationError, Document, Pipeline
9
+ from haystack.utils.device import ComponentDevice, DeviceMap
10
+ from thinc.api import NumpyOps, get_current_ops, set_current_ops
11
+
12
+ from haystack_integrations.components.extractors.spacy import (
13
+ NamedEntityAnnotation,
14
+ SpacyNamedEntityExtractor,
15
+ )
16
+
17
+ MODULE = "haystack_integrations.components.extractors.spacy.named_entity_extractor"
18
+ COMPONENT_TYPE = f"{MODULE}.SpacyNamedEntityExtractor"
19
+
20
+
21
+ @pytest.fixture
22
+ def raw_texts() -> list:
23
+ return [
24
+ "My name is Clara and I live in Berkeley, California.",
25
+ "I'm Merlin, the happy pig!",
26
+ "New York State declared a state of emergency after the announcement of the end of the world.",
27
+ "", # Intentionally empty.
28
+ ]
29
+
30
+
31
+ @pytest.fixture
32
+ def spacy_annotations() -> list:
33
+ return [
34
+ [
35
+ NamedEntityAnnotation(entity="PERSON", start=11, end=16),
36
+ NamedEntityAnnotation(entity="GPE", start=31, end=39),
37
+ NamedEntityAnnotation(entity="GPE", start=41, end=51),
38
+ ],
39
+ [NamedEntityAnnotation(entity="PERSON", start=4, end=10)],
40
+ [NamedEntityAnnotation(entity="GPE", start=0, end=14)],
41
+ [],
42
+ ]
43
+
44
+
45
+ def test_named_entity_extractor_init():
46
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
47
+ assert extractor.model_name_or_path == "en_core_web_trf"
48
+ assert extractor.pipeline_kwargs == {}
49
+ assert not extractor.initialized
50
+
51
+
52
+ def test_init_raises_with_multiple_devices():
53
+ device = ComponentDevice.from_multiple(DeviceMap.from_dict({"layer1": "cpu", "layer2": "cuda:0"}))
54
+ with pytest.raises(ValueError, match="only supports inference on single devices"):
55
+ SpacyNamedEntityExtractor(model="en_core_web_trf", device=device)
56
+
57
+
58
+ def test_named_entity_extractor_to_dict():
59
+ extractor = SpacyNamedEntityExtractor(
60
+ model="en_core_web_trf",
61
+ device=ComponentDevice.from_str("cuda:1"),
62
+ )
63
+
64
+ serde_data = extractor.to_dict()
65
+ assert serde_data == {
66
+ "type": COMPONENT_TYPE,
67
+ "init_parameters": {
68
+ "model": "en_core_web_trf",
69
+ "device": {"type": "single", "device": "cuda:1"},
70
+ "pipeline_kwargs": {},
71
+ },
72
+ }
73
+
74
+
75
+ def test_named_entity_extractor_to_dict_with_parameters():
76
+ extractor = SpacyNamedEntityExtractor(
77
+ model="en_core_web_trf",
78
+ device=ComponentDevice.from_str("cuda:1"),
79
+ pipeline_kwargs={"n_process": 2},
80
+ )
81
+
82
+ serde_data = extractor.to_dict()
83
+ assert serde_data == {
84
+ "type": COMPONENT_TYPE,
85
+ "init_parameters": {
86
+ "model": "en_core_web_trf",
87
+ "device": {"type": "single", "device": "cuda:1"},
88
+ "pipeline_kwargs": {"n_process": 2},
89
+ },
90
+ }
91
+
92
+
93
+ def test_named_entity_extractor_from_dict():
94
+ data = {
95
+ "type": COMPONENT_TYPE,
96
+ "init_parameters": {
97
+ "model": "en_core_web_trf",
98
+ "device": None,
99
+ "pipeline_kwargs": None,
100
+ },
101
+ }
102
+ extractor = SpacyNamedEntityExtractor.from_dict(data)
103
+
104
+ assert extractor.model_name_or_path == "en_core_web_trf"
105
+ assert extractor.pipeline_kwargs == {}
106
+
107
+
108
+ def test_named_entity_extractor_from_dict_no_default_parameters():
109
+ data = {
110
+ "type": COMPONENT_TYPE,
111
+ "init_parameters": {"model": "en_core_web_trf"},
112
+ }
113
+ extractor = SpacyNamedEntityExtractor.from_dict(data)
114
+
115
+ assert extractor.model_name_or_path == "en_core_web_trf"
116
+ assert extractor.device == ComponentDevice.resolve_device(None)
117
+
118
+
119
+ def test_named_entity_extractor_serde():
120
+ extractor = SpacyNamedEntityExtractor(
121
+ model="en_core_web_trf",
122
+ device=ComponentDevice.from_str("cuda:1"),
123
+ )
124
+
125
+ serde_data = extractor.to_dict()
126
+ new_extractor = SpacyNamedEntityExtractor.from_dict(serde_data)
127
+
128
+ assert new_extractor.model_name_or_path == extractor.model_name_or_path
129
+ assert new_extractor.device == extractor.device
130
+
131
+ with pytest.raises(DeserializationError, match=r"Couldn't deserialize"):
132
+ serde_data["init_parameters"].pop("model")
133
+ _ = SpacyNamedEntityExtractor.from_dict(serde_data)
134
+
135
+
136
+ def test_named_entity_extractor_serde_none_device():
137
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf", device=None)
138
+
139
+ serde_data = extractor.to_dict()
140
+ new_extractor = SpacyNamedEntityExtractor.from_dict(serde_data)
141
+
142
+ assert new_extractor.model_name_or_path == extractor.model_name_or_path
143
+ assert new_extractor.device == extractor.device
144
+
145
+
146
+ # tests for SpacyNamedEntityExtractor serialization/deserialization in a pipeline
147
+ def test_named_entity_extractor_pipeline_serde(tmp_path):
148
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
149
+ p = Pipeline()
150
+ p.add_component(instance=extractor, name="extractor")
151
+
152
+ with open(tmp_path / "test_pipeline.yaml", "w") as f:
153
+ p.dump(f)
154
+ with open(tmp_path / "test_pipeline.yaml") as f:
155
+ q = Pipeline.load(f)
156
+
157
+ assert p.to_dict() == q.to_dict(), "Pipeline serialization/deserialization with SpacyNamedEntityExtractor failed."
158
+
159
+
160
+ def test_warm_up_skips_when_already_warmed_up():
161
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
162
+ extractor._warmed_up = True
163
+
164
+ with patch(f"{MODULE}.spacy.load") as mock_load:
165
+ extractor.warm_up()
166
+ mock_load.assert_not_called()
167
+
168
+
169
+ def test_warm_up_fails_when_model_load_raises():
170
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
171
+
172
+ with patch(f"{MODULE}.spacy") as mock_spacy:
173
+ mock_spacy.load.side_effect = RuntimeError("boom")
174
+
175
+ with pytest.raises(ComponentError, match="failed to initialize"):
176
+ extractor.warm_up()
177
+
178
+
179
+ def test_warm_up_fails_when_model_has_no_ner_component():
180
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
181
+
182
+ with patch(f"{MODULE}.spacy") as mock_spacy:
183
+ mock_spacy.load.return_value.has_pipe.return_value = False
184
+
185
+ with pytest.raises(ComponentError, match="failed to initialize"):
186
+ extractor.warm_up()
187
+
188
+
189
+ def test_named_entity_extractor_run():
190
+ """Test the SpacyNamedEntityExtractor.run method with mocked model interaction."""
191
+ documents = [Document(content="My name is Clara and I live in Berkeley, California.")]
192
+
193
+ expected_annotations = [
194
+ [
195
+ NamedEntityAnnotation(entity="PERSON", start=11, end=16),
196
+ NamedEntityAnnotation(entity="GPE", start=31, end=39),
197
+ NamedEntityAnnotation(entity="GPE", start=41, end=51),
198
+ ]
199
+ ]
200
+
201
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
202
+
203
+ with patch.object(extractor, "_annotate", return_value=expected_annotations) as mock_annotate:
204
+ extractor.pipeline = "mocked_pipeline"
205
+ extractor._warmed_up = True
206
+
207
+ result = extractor.run(documents=documents, batch_size=2)
208
+
209
+ mock_annotate.assert_called_once_with(["My name is Clara and I live in Berkeley, California."], batch_size=2)
210
+
211
+ assert "documents" in result
212
+ assert len(result["documents"]) == 1
213
+
214
+ assert isinstance(result["documents"][0], Document)
215
+ assert result["documents"][0].content == documents[0].content
216
+ assert "named_entities" in result["documents"][0].meta
217
+ assert result["documents"][0].meta["named_entities"] == expected_annotations[0]
218
+ assert "named_entities" not in documents[0].meta
219
+
220
+
221
+ def test_named_entity_extractor_run_fails_with_wrong_number_of_annotations():
222
+ documents = [Document(content="My name is Clara."), Document(content="I'm Merlin, the happy pig!")]
223
+
224
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
225
+
226
+ with patch.object(extractor, "_annotate", return_value=[[]]):
227
+ extractor._warmed_up = True
228
+
229
+ with pytest.raises(ComponentError, match="did not return the correct number of annotations"):
230
+ extractor.run(documents=documents)
231
+
232
+
233
+ def test_run_triggers_warm_up_when_not_warmed_up():
234
+ documents = [Document(content="My name is Clara and I live in Berkeley, California.")]
235
+ expected_annotations = [[NamedEntityAnnotation(entity="PERSON", start=11, end=16)]]
236
+
237
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
238
+
239
+ with (
240
+ patch.object(extractor, "warm_up") as mock_warm_up,
241
+ patch.object(extractor, "_annotate", return_value=expected_annotations),
242
+ ):
243
+ result = extractor.run(documents=documents)
244
+
245
+ mock_warm_up.assert_called_once()
246
+ assert result["documents"][0].meta["named_entities"] == expected_annotations[0]
247
+
248
+
249
+ def test_annotate_raises_when_not_initialized():
250
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
251
+
252
+ with pytest.raises(ComponentError, match="was not initialized"):
253
+ extractor._annotate(["My name is Clara."])
254
+
255
+
256
+ def test_spacy_backend_restores_device_state():
257
+ """
258
+ Verify that SpacyNamedEntityExtractor restores the previous Thinc Ops state after the context manager exits.
259
+ """
260
+ # 1. Setup a custom state
261
+ custom_ops = NumpyOps()
262
+ custom_ops.owner = "test_marker"
263
+ set_current_ops(custom_ops)
264
+
265
+ try:
266
+ # 2. Initialize and enter the device-selection context manager
267
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_sm")
268
+
269
+ with extractor._select_device():
270
+ # Inside the context, the state might change
271
+ pass
272
+
273
+ # 3. Verify state is restored
274
+ final_ops = get_current_ops()
275
+ assert getattr(final_ops, "owner", None) == "test_marker"
276
+
277
+ finally:
278
+ # Clean up global state
279
+ set_current_ops(NumpyOps())
280
+
281
+
282
+ @pytest.mark.integration
283
+ def test_ner_extractor_init():
284
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
285
+ extractor.warm_up()
286
+ assert extractor.initialized
287
+
288
+
289
+ @pytest.mark.integration
290
+ @pytest.mark.parametrize("batch_size", [1, 3])
291
+ def test_ner_extractor(raw_texts, spacy_annotations, batch_size):
292
+ extractor = SpacyNamedEntityExtractor(model="en_core_web_trf")
293
+ extractor.warm_up()
294
+
295
+ _extract_and_check_predictions(extractor, raw_texts, spacy_annotations, batch_size)
296
+
297
+
298
+ @pytest.mark.integration
299
+ @pytest.mark.parametrize("batch_size", [1, 3])
300
+ def test_ner_extractor_in_pipeline(raw_texts, spacy_annotations, batch_size):
301
+ pipeline = Pipeline()
302
+ pipeline.add_component(
303
+ name="ner_extractor",
304
+ instance=SpacyNamedEntityExtractor(model="en_core_web_trf"),
305
+ )
306
+
307
+ outputs = pipeline.run(
308
+ {"ner_extractor": {"documents": [Document(content=text) for text in raw_texts], "batch_size": batch_size}}
309
+ )["ner_extractor"]["documents"]
310
+ predicted = [SpacyNamedEntityExtractor.get_stored_annotations(doc) for doc in outputs]
311
+ _check_predictions(predicted, spacy_annotations)
312
+
313
+
314
+ def _extract_and_check_predictions(extractor, texts, expected, batch_size):
315
+ docs = [Document(content=text) for text in texts]
316
+ outputs = extractor.run(documents=docs, batch_size=batch_size)["documents"]
317
+ for original_doc, output_doc in zip(docs, outputs, strict=True):
318
+ # we don't modify documents in place
319
+ assert original_doc is not output_doc
320
+
321
+ # apart from meta, the documents should be identical
322
+ output_doc_dict = output_doc.to_dict(flatten=False)
323
+ output_doc_dict.pop("meta", None)
324
+ assert original_doc.to_dict() == output_doc_dict
325
+
326
+ predicted = [SpacyNamedEntityExtractor.get_stored_annotations(doc) for doc in outputs]
327
+
328
+ _check_predictions(predicted, expected)
329
+
330
+
331
+ def _check_predictions(predicted, expected):
332
+ assert len(predicted) == len(expected)
333
+ for pred, exp in zip(predicted, expected, strict=True):
334
+ assert len(pred) == len(exp)
335
+
336
+ for a, b in zip(pred, exp, strict=True):
337
+ assert a.entity == b.entity
338
+ assert a.start == b.start
339
+ assert a.end == b.end