jina-haystack 0.0.1__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.
- jina_haystack-0.0.1/.gitignore +133 -0
- jina_haystack-0.0.1/LICENSE.txt +201 -0
- jina_haystack-0.0.1/PKG-INFO +55 -0
- jina_haystack-0.0.1/README.md +32 -0
- jina_haystack-0.0.1/pyproject.toml +161 -0
- jina_haystack-0.0.1/src/jina_haystack/__about__.py +4 -0
- jina_haystack-0.0.1/src/jina_haystack/__init__.py +8 -0
- jina_haystack-0.0.1/src/jina_haystack/document_embedder.py +180 -0
- jina_haystack-0.0.1/src/jina_haystack/text_embedder.py +106 -0
- jina_haystack-0.0.1/tests/__init__.py +3 -0
- jina_haystack-0.0.1/tests/test_document_embedder.py +239 -0
- jina_haystack-0.0.1/tests/test_text_embedder.py +100 -0
|
@@ -0,0 +1,133 @@
|
|
|
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
|
|
@@ -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,55 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: jina-haystack
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/jina/jina-haystack#readme
|
|
5
|
+
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
6
|
+
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/jina/jina-haystack
|
|
7
|
+
Author-email: Joan Fontanals Martinez <joan.fontanals.martinez@jina.ai>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE.txt
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Programming Language :: Python
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
18
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
19
|
+
Requires-Python: >=3.7
|
|
20
|
+
Requires-Dist: haystack-ai
|
|
21
|
+
Requires-Dist: requests
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# jina-haystack
|
|
25
|
+
|
|
26
|
+
[](https://pypi.org/project/jina-haystack)
|
|
27
|
+
[](https://pypi.org/project/jina-haystack)
|
|
28
|
+
|
|
29
|
+
-----
|
|
30
|
+
|
|
31
|
+
**Table of Contents**
|
|
32
|
+
|
|
33
|
+
- [jina-haystack](#jina-haystack)
|
|
34
|
+
- [Installation](#installation)
|
|
35
|
+
- [Usage](#usage)
|
|
36
|
+
- [License](#license)
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```console
|
|
41
|
+
pip install jina-haystack
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Usage
|
|
45
|
+
|
|
46
|
+
You can use `JinaTextEmbedder` and `JinaDocumentEmbedder` by importing as:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from jina_haystack.document_embedder import JinaDocumentEmbedder
|
|
50
|
+
from jina_haystack.text_embedder import JinaTextEmbedder
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## License
|
|
54
|
+
|
|
55
|
+
`jina-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# jina-haystack
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/jina-haystack)
|
|
4
|
+
[](https://pypi.org/project/jina-haystack)
|
|
5
|
+
|
|
6
|
+
-----
|
|
7
|
+
|
|
8
|
+
**Table of Contents**
|
|
9
|
+
|
|
10
|
+
- [jina-haystack](#jina-haystack)
|
|
11
|
+
- [Installation](#installation)
|
|
12
|
+
- [Usage](#usage)
|
|
13
|
+
- [License](#license)
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
```console
|
|
18
|
+
pip install jina-haystack
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
You can use `JinaTextEmbedder` and `JinaDocumentEmbedder` by importing as:
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from jina_haystack.document_embedder import JinaDocumentEmbedder
|
|
27
|
+
from jina_haystack.text_embedder import JinaTextEmbedder
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## License
|
|
31
|
+
|
|
32
|
+
`jina-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "jina-haystack"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = ''
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.7"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
keywords = []
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Joan Fontanals Martinez", email = "joan.fontanals.martinez@jina.ai" },
|
|
15
|
+
]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Programming Language :: Python",
|
|
19
|
+
"Programming Language :: Python :: 3.7",
|
|
20
|
+
"Programming Language :: Python :: 3.8",
|
|
21
|
+
"Programming Language :: Python :: 3.9",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: Implementation :: CPython",
|
|
25
|
+
"Programming Language :: Python :: Implementation :: PyPy",
|
|
26
|
+
]
|
|
27
|
+
dependencies = ["requests", "haystack-ai"]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/jina/jina-haystack#readme"
|
|
31
|
+
Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
|
|
32
|
+
Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/jina/jina-haystack"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.version]
|
|
35
|
+
path = "src/jina_haystack/__about__.py"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.envs.default]
|
|
38
|
+
dependencies = [
|
|
39
|
+
"coverage[toml]>=6.5",
|
|
40
|
+
"pytest",
|
|
41
|
+
]
|
|
42
|
+
[tool.hatch.envs.default.scripts]
|
|
43
|
+
test = "pytest {args:tests}"
|
|
44
|
+
test-cov = "coverage run -m pytest {args:tests}"
|
|
45
|
+
cov-report = [
|
|
46
|
+
"- coverage combine",
|
|
47
|
+
"coverage report",
|
|
48
|
+
]
|
|
49
|
+
cov = [
|
|
50
|
+
"test-cov",
|
|
51
|
+
"cov-report",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
[[tool.hatch.envs.all.matrix]]
|
|
55
|
+
python = ["3.7", "3.8", "3.9", "3.10", "3.11"]
|
|
56
|
+
|
|
57
|
+
[tool.hatch.envs.lint]
|
|
58
|
+
detached = true
|
|
59
|
+
dependencies = [
|
|
60
|
+
"black>=23.1.0",
|
|
61
|
+
"mypy>=1.0.0",
|
|
62
|
+
"ruff>=0.0.243",
|
|
63
|
+
]
|
|
64
|
+
[tool.hatch.envs.lint.scripts]
|
|
65
|
+
typing = "mypy --install-types --non-interactive {args:src/jina_haystack tests}"
|
|
66
|
+
style = [
|
|
67
|
+
"ruff {args:.}",
|
|
68
|
+
"black --check --diff {args:.}",
|
|
69
|
+
]
|
|
70
|
+
fmt = [
|
|
71
|
+
"black {args:.}",
|
|
72
|
+
"ruff --fix {args:.}",
|
|
73
|
+
"style",
|
|
74
|
+
]
|
|
75
|
+
all = [
|
|
76
|
+
"style",
|
|
77
|
+
"typing",
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
[tool.black]
|
|
81
|
+
target-version = ["py37"]
|
|
82
|
+
line-length = 120
|
|
83
|
+
skip-string-normalization = true
|
|
84
|
+
|
|
85
|
+
[tool.ruff]
|
|
86
|
+
target-version = "py37"
|
|
87
|
+
line-length = 120
|
|
88
|
+
select = [
|
|
89
|
+
"A",
|
|
90
|
+
"ARG",
|
|
91
|
+
"B",
|
|
92
|
+
"C",
|
|
93
|
+
"DTZ",
|
|
94
|
+
"E",
|
|
95
|
+
"EM",
|
|
96
|
+
"F",
|
|
97
|
+
"I",
|
|
98
|
+
"ICN",
|
|
99
|
+
"ISC",
|
|
100
|
+
"N",
|
|
101
|
+
"PLC",
|
|
102
|
+
"PLE",
|
|
103
|
+
"PLR",
|
|
104
|
+
"PLW",
|
|
105
|
+
"Q",
|
|
106
|
+
"RUF",
|
|
107
|
+
"S",
|
|
108
|
+
"T",
|
|
109
|
+
"TID",
|
|
110
|
+
"UP",
|
|
111
|
+
"W",
|
|
112
|
+
"YTT",
|
|
113
|
+
]
|
|
114
|
+
ignore = [
|
|
115
|
+
# Allow non-abstract empty methods in abstract base classes
|
|
116
|
+
"B027",
|
|
117
|
+
# Ignore checks for possible passwords
|
|
118
|
+
"S105", "S106", "S107",
|
|
119
|
+
# Ignore complexity
|
|
120
|
+
"C901", "PLR0911", "PLR0912", "PLR0913", "PLR0915",
|
|
121
|
+
]
|
|
122
|
+
unfixable = [
|
|
123
|
+
# Don't touch unused imports
|
|
124
|
+
"F401",
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
[tool.ruff.isort]
|
|
128
|
+
known-first-party = ["jina_haystack"]
|
|
129
|
+
|
|
130
|
+
[tool.ruff.flake8-tidy-imports]
|
|
131
|
+
ban-relative-imports = "all"
|
|
132
|
+
|
|
133
|
+
[tool.ruff.per-file-ignores]
|
|
134
|
+
# Tests can use magic values, assertions, and relative imports
|
|
135
|
+
"tests/**/*" = ["PLR2004", "S101", "TID252"]
|
|
136
|
+
|
|
137
|
+
[tool.coverage.run]
|
|
138
|
+
source_pkgs = ["jina_haystack", "tests"]
|
|
139
|
+
branch = true
|
|
140
|
+
parallel = true
|
|
141
|
+
omit = [
|
|
142
|
+
"src/jina_haystack/__about__.py",
|
|
143
|
+
]
|
|
144
|
+
|
|
145
|
+
[tool.coverage.paths]
|
|
146
|
+
jina_haystack = ["src/jina_haystack", "*/jina-haystack/src/jina_haystack"]
|
|
147
|
+
tests = ["tests", "*/jina-haystack/tests"]
|
|
148
|
+
|
|
149
|
+
[tool.coverage.report]
|
|
150
|
+
exclude_lines = [
|
|
151
|
+
"no cov",
|
|
152
|
+
"if __name__ == .__main__.:",
|
|
153
|
+
"if TYPE_CHECKING:",
|
|
154
|
+
]
|
|
155
|
+
|
|
156
|
+
[[tool.mypy.overrides]]
|
|
157
|
+
module = [
|
|
158
|
+
"haystack.*",
|
|
159
|
+
"pytest.*"
|
|
160
|
+
]
|
|
161
|
+
ignore_missing_imports = true
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
from jina_haystack.document_embedder import JinaDocumentEmbedder
|
|
6
|
+
from jina_haystack.text_embedder import JinaTextEmbedder
|
|
7
|
+
|
|
8
|
+
__all__ = ["JinaDocumentEmbedder", "JinaTextEmbedder"]
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import os
|
|
5
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
from haystack import Document, component, default_to_dict
|
|
9
|
+
from tqdm import tqdm
|
|
10
|
+
|
|
11
|
+
JINA_API_URL: str = "https://api.jina.ai/v1/embeddings"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@component
|
|
15
|
+
class JinaDocumentEmbedder:
|
|
16
|
+
"""
|
|
17
|
+
A component for computing Document embeddings using Jina AI models.
|
|
18
|
+
The embedding of each Document is stored in the `embedding` field of the Document.
|
|
19
|
+
|
|
20
|
+
Usage example:
|
|
21
|
+
```python
|
|
22
|
+
from haystack import Document
|
|
23
|
+
from jina_haystack import JinaDocumentEmbedder
|
|
24
|
+
|
|
25
|
+
doc = Document(content="I love pizza!")
|
|
26
|
+
|
|
27
|
+
document_embedder = JinaDocumentEmbedder()
|
|
28
|
+
|
|
29
|
+
result = document_embedder.run([doc])
|
|
30
|
+
print(result['documents'][0].embedding)
|
|
31
|
+
|
|
32
|
+
# [0.017020374536514282, -0.023255806416273117, ...]
|
|
33
|
+
```
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
api_key: Optional[str] = None,
|
|
39
|
+
model_name: str = "jina-embeddings-v2-base-en",
|
|
40
|
+
prefix: str = "",
|
|
41
|
+
suffix: str = "",
|
|
42
|
+
batch_size: int = 32,
|
|
43
|
+
progress_bar: bool = True,
|
|
44
|
+
metadata_fields_to_embed: Optional[List[str]] = None,
|
|
45
|
+
embedding_separator: str = "\n",
|
|
46
|
+
):
|
|
47
|
+
"""
|
|
48
|
+
Create a JinaDocumentEmbedder component.
|
|
49
|
+
:param api_key: The Jina API key. It can be explicitly provided or automatically read from the
|
|
50
|
+
environment variable JINA_API_KEY (recommended).
|
|
51
|
+
:param model_name: The name of the Jina model to use. Check the list of available models on `https://jina.ai/embeddings/`
|
|
52
|
+
:param prefix: A string to add to the beginning of each text.
|
|
53
|
+
:param suffix: A string to add to the end of each text.
|
|
54
|
+
:param batch_size: Number of Documents to encode at once.
|
|
55
|
+
:param progress_bar: Whether to show a progress bar or not. Can be helpful to disable in production deployments
|
|
56
|
+
to keep the logs clean.
|
|
57
|
+
:param metadata_fields_to_embed: List of meta fields that should be embedded along with the Document text.
|
|
58
|
+
:param embedding_separator: Separator used to concatenate the meta fields to the Document text.
|
|
59
|
+
"""
|
|
60
|
+
# if the user does not provide the API key, check if it is set in the module client
|
|
61
|
+
if api_key is None:
|
|
62
|
+
try:
|
|
63
|
+
api_key = os.environ["JINA_API_KEY"]
|
|
64
|
+
except KeyError as e:
|
|
65
|
+
msg = (
|
|
66
|
+
"JinaDocumentEmbedder expects a Jina API key. "
|
|
67
|
+
"Set the JINA_API_KEY environment variable (recommended) or pass it explicitly."
|
|
68
|
+
)
|
|
69
|
+
raise ValueError(msg) from e
|
|
70
|
+
|
|
71
|
+
self.model_name = model_name
|
|
72
|
+
self.prefix = prefix
|
|
73
|
+
self.suffix = suffix
|
|
74
|
+
self.prefix = prefix
|
|
75
|
+
self.suffix = suffix
|
|
76
|
+
self.batch_size = batch_size
|
|
77
|
+
self.progress_bar = progress_bar
|
|
78
|
+
self.metadata_fields_to_embed = metadata_fields_to_embed or []
|
|
79
|
+
self.embedding_separator = embedding_separator
|
|
80
|
+
self._session = requests.Session()
|
|
81
|
+
self._session.headers.update(
|
|
82
|
+
{
|
|
83
|
+
"Authorization": f"Bearer {api_key}",
|
|
84
|
+
"Accept-Encoding": "identity",
|
|
85
|
+
"Content-type": "application/json",
|
|
86
|
+
}
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
def _get_telemetry_data(self) -> Dict[str, Any]:
|
|
90
|
+
"""
|
|
91
|
+
Data that is sent to Posthog for usage analytics.
|
|
92
|
+
"""
|
|
93
|
+
return {"model": self.model_name}
|
|
94
|
+
|
|
95
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
96
|
+
"""
|
|
97
|
+
This method overrides the default serializer in order to avoid leaking the `api_key` value passed
|
|
98
|
+
to the constructor.
|
|
99
|
+
"""
|
|
100
|
+
return default_to_dict(
|
|
101
|
+
self,
|
|
102
|
+
model_name=self.model_name,
|
|
103
|
+
prefix=self.prefix,
|
|
104
|
+
suffix=self.suffix,
|
|
105
|
+
batch_size=self.batch_size,
|
|
106
|
+
progress_bar=self.progress_bar,
|
|
107
|
+
metadata_fields_to_embed=self.metadata_fields_to_embed,
|
|
108
|
+
embedding_separator=self.embedding_separator,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
def _prepare_texts_to_embed(self, documents: List[Document]) -> List[str]:
|
|
112
|
+
"""
|
|
113
|
+
Prepare the texts to embed by concatenating the Document text with the metadata fields to embed.
|
|
114
|
+
"""
|
|
115
|
+
texts_to_embed = []
|
|
116
|
+
for doc in documents:
|
|
117
|
+
meta_values_to_embed = [
|
|
118
|
+
str(doc.meta[key])
|
|
119
|
+
for key in self.metadata_fields_to_embed
|
|
120
|
+
if key in doc.meta and doc.meta[key] is not None
|
|
121
|
+
]
|
|
122
|
+
text_to_embed = (
|
|
123
|
+
self.prefix + self.embedding_separator.join([*meta_values_to_embed, doc.content or ""]) + self.suffix
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
texts_to_embed.append(text_to_embed)
|
|
127
|
+
return texts_to_embed
|
|
128
|
+
|
|
129
|
+
def _embed_batch(self, texts_to_embed: List[str], batch_size: int) -> Tuple[List[List[float]], Dict[str, Any]]:
|
|
130
|
+
"""
|
|
131
|
+
Embed a list of texts in batches.
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
all_embeddings = []
|
|
135
|
+
metadata = {}
|
|
136
|
+
for i in tqdm(
|
|
137
|
+
range(0, len(texts_to_embed), batch_size), disable=not self.progress_bar, desc="Calculating embeddings"
|
|
138
|
+
):
|
|
139
|
+
batch = texts_to_embed[i : i + batch_size]
|
|
140
|
+
response = self._session.post(JINA_API_URL, json={"input": batch, "model": self.model_name}).json()
|
|
141
|
+
if "data" not in response:
|
|
142
|
+
raise RuntimeError(response["detail"])
|
|
143
|
+
|
|
144
|
+
# Sort resulting embeddings by index
|
|
145
|
+
sorted_embeddings = sorted(response["data"], key=lambda e: e["index"])
|
|
146
|
+
embeddings = [result["embedding"] for result in sorted_embeddings]
|
|
147
|
+
all_embeddings.extend(embeddings)
|
|
148
|
+
if "model" not in metadata:
|
|
149
|
+
metadata["model"] = response["model"]
|
|
150
|
+
if "usage" not in metadata:
|
|
151
|
+
metadata["usage"] = dict(response["usage"].items())
|
|
152
|
+
else:
|
|
153
|
+
metadata["usage"]["prompt_tokens"] += response["usage"]["prompt_tokens"]
|
|
154
|
+
metadata["usage"]["total_tokens"] += response["usage"]["total_tokens"]
|
|
155
|
+
|
|
156
|
+
return all_embeddings, metadata
|
|
157
|
+
|
|
158
|
+
@component.output_types(documents=List[Document], metadata=Dict[str, Any])
|
|
159
|
+
def run(self, documents: List[Document]):
|
|
160
|
+
"""
|
|
161
|
+
Embed a list of Documents.
|
|
162
|
+
The embedding of each Document is stored in the `embedding` field of the Document.
|
|
163
|
+
|
|
164
|
+
:param documents: A list of Documents to embed.
|
|
165
|
+
"""
|
|
166
|
+
if not isinstance(documents, list) or documents and not isinstance(documents[0], Document):
|
|
167
|
+
msg = (
|
|
168
|
+
"JinaDocumentEmbedder expects a list of Documents as input."
|
|
169
|
+
"In case you want to embed a string, please use the JinaTextEmbedder."
|
|
170
|
+
)
|
|
171
|
+
raise TypeError(msg)
|
|
172
|
+
|
|
173
|
+
texts_to_embed = self._prepare_texts_to_embed(documents=documents)
|
|
174
|
+
|
|
175
|
+
embeddings, metadata = self._embed_batch(texts_to_embed=texts_to_embed, batch_size=self.batch_size)
|
|
176
|
+
|
|
177
|
+
for doc, emb in zip(documents, embeddings):
|
|
178
|
+
doc.embedding = emb
|
|
179
|
+
|
|
180
|
+
return {"documents": documents, "metadata": metadata}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import os
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
from haystack import component, default_to_dict
|
|
9
|
+
|
|
10
|
+
JINA_API_URL: str = "https://api.jina.ai/v1/embeddings"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@component
|
|
14
|
+
class JinaTextEmbedder:
|
|
15
|
+
"""
|
|
16
|
+
A component for embedding strings using Jina models.
|
|
17
|
+
|
|
18
|
+
Usage example:
|
|
19
|
+
```python
|
|
20
|
+
from jina_haystack import JinaTextEmbedder
|
|
21
|
+
|
|
22
|
+
text_to_embed = "I love pizza!"
|
|
23
|
+
|
|
24
|
+
text_embedder = JinaTextEmbedder()
|
|
25
|
+
|
|
26
|
+
print(text_embedder.run(text_to_embed))
|
|
27
|
+
|
|
28
|
+
# {'embedding': [0.017020374536514282, -0.023255806416273117, ...],
|
|
29
|
+
# 'metadata': {'model': 'jina-embeddings-v2-base-en',
|
|
30
|
+
# 'usage': {'prompt_tokens': 4, 'total_tokens': 4}}}
|
|
31
|
+
```
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
api_key: Optional[str] = None,
|
|
37
|
+
model_name: str = "jina-embeddings-v2-base-en",
|
|
38
|
+
prefix: str = "",
|
|
39
|
+
suffix: str = "",
|
|
40
|
+
):
|
|
41
|
+
"""
|
|
42
|
+
Create an JinaTextEmbedder component.
|
|
43
|
+
|
|
44
|
+
:param api_key: The Jina API key. It can be explicitly provided or automatically read from the
|
|
45
|
+
environment variable JINA_API_KEY (recommended).
|
|
46
|
+
:param model_name: The name of the Jina model to use. Check the list of available models on `https://jina.ai/embeddings/`
|
|
47
|
+
:param prefix: A string to add to the beginning of each text.
|
|
48
|
+
:param suffix: A string to add to the end of each text.
|
|
49
|
+
"""
|
|
50
|
+
# if the user does not provide the API key, check if it is set in the module client
|
|
51
|
+
if api_key is None:
|
|
52
|
+
try:
|
|
53
|
+
api_key = os.environ["JINA_API_KEY"]
|
|
54
|
+
except KeyError as e:
|
|
55
|
+
msg = (
|
|
56
|
+
"JinaTextEmbedder expects a Jina API key. "
|
|
57
|
+
"Set the JINA_API_KEY environment variable (recommended) or pass it explicitly."
|
|
58
|
+
)
|
|
59
|
+
raise ValueError(msg) from e
|
|
60
|
+
|
|
61
|
+
self.model_name = model_name
|
|
62
|
+
self.prefix = prefix
|
|
63
|
+
self.suffix = suffix
|
|
64
|
+
self._session = requests.Session()
|
|
65
|
+
self._session.headers.update(
|
|
66
|
+
{
|
|
67
|
+
"Authorization": f"Bearer {api_key}",
|
|
68
|
+
"Accept-Encoding": "identity",
|
|
69
|
+
"Content-type": "application/json",
|
|
70
|
+
}
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def _get_telemetry_data(self) -> Dict[str, Any]:
|
|
74
|
+
"""
|
|
75
|
+
Data that is sent to Posthog for usage analytics.
|
|
76
|
+
"""
|
|
77
|
+
return {"model": self.model_name}
|
|
78
|
+
|
|
79
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
80
|
+
"""
|
|
81
|
+
This method overrides the default serializer in order to avoid leaking the `api_key` value passed
|
|
82
|
+
to the constructor.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
return default_to_dict(self, model_name=self.model_name, prefix=self.prefix, suffix=self.suffix)
|
|
86
|
+
|
|
87
|
+
@component.output_types(embedding=List[float], metadata=Dict[str, Any])
|
|
88
|
+
def run(self, text: str):
|
|
89
|
+
"""Embed a string."""
|
|
90
|
+
if not isinstance(text, str):
|
|
91
|
+
msg = (
|
|
92
|
+
"JinaTextEmbedder expects a string as an input."
|
|
93
|
+
"In case you want to embed a list of Documents, please use the JinaDocumentEmbedder."
|
|
94
|
+
)
|
|
95
|
+
raise TypeError(msg)
|
|
96
|
+
|
|
97
|
+
text_to_embed = self.prefix + text + self.suffix
|
|
98
|
+
|
|
99
|
+
resp = self._session.post(JINA_API_URL, json={"input": [text_to_embed], "model": self.model_name}).json()
|
|
100
|
+
if "data" not in resp:
|
|
101
|
+
raise RuntimeError(resp["detail"])
|
|
102
|
+
|
|
103
|
+
metadata = {"model": resp["model"], "usage": dict(resp["usage"].items())}
|
|
104
|
+
embedding = resp["data"][0]["embedding"]
|
|
105
|
+
|
|
106
|
+
return {"embedding": embedding, "metadata": metadata}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import json
|
|
5
|
+
from unittest.mock import patch
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
import requests
|
|
9
|
+
from haystack import Document
|
|
10
|
+
|
|
11
|
+
from jina_haystack import JinaDocumentEmbedder
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def mock_session_post_response(*args, **kwargs): # noqa: ARG001
|
|
15
|
+
inputs = kwargs["json"]["input"]
|
|
16
|
+
model = kwargs["json"]["model"]
|
|
17
|
+
mock_response = requests.Response()
|
|
18
|
+
mock_response.status_code = 200
|
|
19
|
+
data = [{"object": "embedding", "index": i, "embedding": [0.1, 0.2, 0.3]} for i in range(len(inputs))]
|
|
20
|
+
mock_response._content = json.dumps(
|
|
21
|
+
{"model": model, "object": "list", "usage": {"total_tokens": 4, "prompt_tokens": 4}, "data": data}
|
|
22
|
+
).encode()
|
|
23
|
+
|
|
24
|
+
return mock_response
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class TestJinaDocumentEmbedder:
|
|
28
|
+
def test_init_default(self, monkeypatch):
|
|
29
|
+
monkeypatch.setenv("JINA_API_KEY", "fake-api-key")
|
|
30
|
+
embedder = JinaDocumentEmbedder()
|
|
31
|
+
|
|
32
|
+
assert embedder.model_name == "jina-embeddings-v2-base-en"
|
|
33
|
+
assert embedder.prefix == ""
|
|
34
|
+
assert embedder.suffix == ""
|
|
35
|
+
assert embedder.batch_size == 32
|
|
36
|
+
assert embedder.progress_bar is True
|
|
37
|
+
assert embedder.metadata_fields_to_embed == []
|
|
38
|
+
assert embedder.embedding_separator == "\n"
|
|
39
|
+
|
|
40
|
+
def test_init_with_parameters(self):
|
|
41
|
+
embedder = JinaDocumentEmbedder(
|
|
42
|
+
api_key="fake-api-key",
|
|
43
|
+
model_name="model",
|
|
44
|
+
prefix="prefix",
|
|
45
|
+
suffix="suffix",
|
|
46
|
+
batch_size=64,
|
|
47
|
+
progress_bar=False,
|
|
48
|
+
metadata_fields_to_embed=["test_field"],
|
|
49
|
+
embedding_separator=" | ",
|
|
50
|
+
)
|
|
51
|
+
assert embedder.model_name == "model"
|
|
52
|
+
assert embedder.prefix == "prefix"
|
|
53
|
+
assert embedder.suffix == "suffix"
|
|
54
|
+
assert embedder.batch_size == 64
|
|
55
|
+
assert embedder.progress_bar is False
|
|
56
|
+
assert embedder.metadata_fields_to_embed == ["test_field"]
|
|
57
|
+
assert embedder.embedding_separator == " | "
|
|
58
|
+
|
|
59
|
+
def test_init_fail_wo_api_key(self, monkeypatch):
|
|
60
|
+
monkeypatch.delenv("JINA_API_KEY", raising=False)
|
|
61
|
+
with pytest.raises(ValueError, match="JinaDocumentEmbedder expects a Jina API key"):
|
|
62
|
+
JinaDocumentEmbedder()
|
|
63
|
+
|
|
64
|
+
def test_to_dict(self):
|
|
65
|
+
component = JinaDocumentEmbedder(api_key="fake-api-key")
|
|
66
|
+
data = component.to_dict()
|
|
67
|
+
assert data == {
|
|
68
|
+
"type": "jina_haystack.document_embedder.JinaDocumentEmbedder",
|
|
69
|
+
"init_parameters": {
|
|
70
|
+
"model_name": "jina-embeddings-v2-base-en",
|
|
71
|
+
"prefix": "",
|
|
72
|
+
"suffix": "",
|
|
73
|
+
"batch_size": 32,
|
|
74
|
+
"progress_bar": True,
|
|
75
|
+
"metadata_fields_to_embed": [],
|
|
76
|
+
"embedding_separator": "\n",
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
def test_to_dict_with_custom_init_parameters(self):
|
|
81
|
+
component = JinaDocumentEmbedder(
|
|
82
|
+
api_key="fake-api-key",
|
|
83
|
+
model_name="model",
|
|
84
|
+
prefix="prefix",
|
|
85
|
+
suffix="suffix",
|
|
86
|
+
batch_size=64,
|
|
87
|
+
progress_bar=False,
|
|
88
|
+
metadata_fields_to_embed=["test_field"],
|
|
89
|
+
embedding_separator=" | ",
|
|
90
|
+
)
|
|
91
|
+
data = component.to_dict()
|
|
92
|
+
assert data == {
|
|
93
|
+
"type": "jina_haystack.document_embedder.JinaDocumentEmbedder",
|
|
94
|
+
"init_parameters": {
|
|
95
|
+
"model_name": "model",
|
|
96
|
+
"prefix": "prefix",
|
|
97
|
+
"suffix": "suffix",
|
|
98
|
+
"batch_size": 64,
|
|
99
|
+
"progress_bar": False,
|
|
100
|
+
"metadata_fields_to_embed": ["test_field"],
|
|
101
|
+
"embedding_separator": " | ",
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
def test_prepare_texts_to_embed_w_metadata(self):
|
|
106
|
+
documents = [
|
|
107
|
+
Document(content=f"document number {i}:\ncontent", meta={"meta_field": f"meta_value {i}"}) for i in range(5)
|
|
108
|
+
]
|
|
109
|
+
|
|
110
|
+
embedder = JinaDocumentEmbedder(
|
|
111
|
+
api_key="fake-api-key", metadata_fields_to_embed=["meta_field"], embedding_separator=" | "
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
prepared_texts = embedder._prepare_texts_to_embed(documents)
|
|
115
|
+
|
|
116
|
+
# note that newline is replaced by space
|
|
117
|
+
assert prepared_texts == [
|
|
118
|
+
"meta_value 0 | document number 0:\ncontent",
|
|
119
|
+
"meta_value 1 | document number 1:\ncontent",
|
|
120
|
+
"meta_value 2 | document number 2:\ncontent",
|
|
121
|
+
"meta_value 3 | document number 3:\ncontent",
|
|
122
|
+
"meta_value 4 | document number 4:\ncontent",
|
|
123
|
+
]
|
|
124
|
+
|
|
125
|
+
def test_prepare_texts_to_embed_w_suffix(self):
|
|
126
|
+
documents = [Document(content=f"document number {i}") for i in range(5)]
|
|
127
|
+
|
|
128
|
+
embedder = JinaDocumentEmbedder(api_key="fake-api-key", prefix="my_prefix ", suffix=" my_suffix")
|
|
129
|
+
|
|
130
|
+
prepared_texts = embedder._prepare_texts_to_embed(documents)
|
|
131
|
+
|
|
132
|
+
assert prepared_texts == [
|
|
133
|
+
"my_prefix document number 0 my_suffix",
|
|
134
|
+
"my_prefix document number 1 my_suffix",
|
|
135
|
+
"my_prefix document number 2 my_suffix",
|
|
136
|
+
"my_prefix document number 3 my_suffix",
|
|
137
|
+
"my_prefix document number 4 my_suffix",
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
def test_embed_batch(self):
|
|
141
|
+
texts = ["text 1", "text 2", "text 3", "text 4", "text 5"]
|
|
142
|
+
|
|
143
|
+
with patch("requests.sessions.Session.post", side_effect=mock_session_post_response):
|
|
144
|
+
embedder = JinaDocumentEmbedder(api_key="fake-api-key", model_name="model")
|
|
145
|
+
|
|
146
|
+
embeddings, metadata = embedder._embed_batch(texts_to_embed=texts, batch_size=2)
|
|
147
|
+
|
|
148
|
+
assert isinstance(embeddings, list)
|
|
149
|
+
assert len(embeddings) == len(texts)
|
|
150
|
+
for embedding in embeddings:
|
|
151
|
+
assert isinstance(embedding, list)
|
|
152
|
+
assert len(embedding) == 3
|
|
153
|
+
assert all(isinstance(x, float) for x in embedding)
|
|
154
|
+
|
|
155
|
+
assert metadata == {"model": "model", "usage": {"prompt_tokens": 3 * 4, "total_tokens": 3 * 4}}
|
|
156
|
+
|
|
157
|
+
def test_run(self):
|
|
158
|
+
docs = [
|
|
159
|
+
Document(content="I love cheese", meta={"topic": "Cuisine"}),
|
|
160
|
+
Document(content="A transformer is a deep learning architecture", meta={"topic": "ML"}),
|
|
161
|
+
]
|
|
162
|
+
|
|
163
|
+
model = "jina-embeddings-v2-base-en"
|
|
164
|
+
with patch("requests.sessions.Session.post", side_effect=mock_session_post_response):
|
|
165
|
+
embedder = JinaDocumentEmbedder(
|
|
166
|
+
api_key="fake-api-key",
|
|
167
|
+
model_name=model,
|
|
168
|
+
prefix="prefix ",
|
|
169
|
+
suffix=" suffix",
|
|
170
|
+
metadata_fields_to_embed=["topic"],
|
|
171
|
+
embedding_separator=" | ",
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
result = embedder.run(documents=docs)
|
|
175
|
+
|
|
176
|
+
documents_with_embeddings = result["documents"]
|
|
177
|
+
metadata = result["metadata"]
|
|
178
|
+
|
|
179
|
+
assert isinstance(documents_with_embeddings, list)
|
|
180
|
+
assert len(documents_with_embeddings) == len(docs)
|
|
181
|
+
for doc in documents_with_embeddings:
|
|
182
|
+
assert isinstance(doc, Document)
|
|
183
|
+
assert isinstance(doc.embedding, list)
|
|
184
|
+
assert len(doc.embedding) == 3
|
|
185
|
+
assert all(isinstance(x, float) for x in doc.embedding)
|
|
186
|
+
assert metadata == {"model": model, "usage": {"prompt_tokens": 4, "total_tokens": 4}}
|
|
187
|
+
|
|
188
|
+
def test_run_custom_batch_size(self):
|
|
189
|
+
docs = [
|
|
190
|
+
Document(content="I love cheese", meta={"topic": "Cuisine"}),
|
|
191
|
+
Document(content="A transformer is a deep learning architecture", meta={"topic": "ML"}),
|
|
192
|
+
]
|
|
193
|
+
model = "jina-embeddings-v2-base-en"
|
|
194
|
+
with patch("requests.sessions.Session.post", side_effect=mock_session_post_response):
|
|
195
|
+
embedder = JinaDocumentEmbedder(
|
|
196
|
+
api_key="fake-api-key",
|
|
197
|
+
model_name=model,
|
|
198
|
+
prefix="prefix ",
|
|
199
|
+
suffix=" suffix",
|
|
200
|
+
metadata_fields_to_embed=["topic"],
|
|
201
|
+
embedding_separator=" | ",
|
|
202
|
+
batch_size=1,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
result = embedder.run(documents=docs)
|
|
206
|
+
|
|
207
|
+
documents_with_embeddings = result["documents"]
|
|
208
|
+
metadata = result["metadata"]
|
|
209
|
+
|
|
210
|
+
assert isinstance(documents_with_embeddings, list)
|
|
211
|
+
assert len(documents_with_embeddings) == len(docs)
|
|
212
|
+
for doc in documents_with_embeddings:
|
|
213
|
+
assert isinstance(doc, Document)
|
|
214
|
+
assert isinstance(doc.embedding, list)
|
|
215
|
+
assert len(doc.embedding) == 3
|
|
216
|
+
assert all(isinstance(x, float) for x in doc.embedding)
|
|
217
|
+
|
|
218
|
+
assert metadata == {"model": model, "usage": {"prompt_tokens": 2 * 4, "total_tokens": 2 * 4}}
|
|
219
|
+
|
|
220
|
+
def test_run_wrong_input_format(self):
|
|
221
|
+
embedder = JinaDocumentEmbedder(api_key="fake-api-key")
|
|
222
|
+
|
|
223
|
+
string_input = "text"
|
|
224
|
+
list_integers_input = [1, 2, 3]
|
|
225
|
+
|
|
226
|
+
with pytest.raises(TypeError, match="JinaDocumentEmbedder expects a list of Documents as input"):
|
|
227
|
+
embedder.run(documents=string_input)
|
|
228
|
+
|
|
229
|
+
with pytest.raises(TypeError, match="JinaDocumentEmbedder expects a list of Documents as input"):
|
|
230
|
+
embedder.run(documents=list_integers_input)
|
|
231
|
+
|
|
232
|
+
def test_run_on_empty_list(self):
|
|
233
|
+
embedder = JinaDocumentEmbedder(api_key="fake-api-key")
|
|
234
|
+
|
|
235
|
+
empty_list_input = []
|
|
236
|
+
result = embedder.run(documents=empty_list_input)
|
|
237
|
+
|
|
238
|
+
assert result["documents"] is not None
|
|
239
|
+
assert not result["documents"] # empty list
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import json
|
|
5
|
+
from unittest.mock import patch
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
import requests
|
|
9
|
+
|
|
10
|
+
from jina_haystack import JinaTextEmbedder
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TestJinaTextEmbedder:
|
|
14
|
+
def test_init_default(self, monkeypatch):
|
|
15
|
+
monkeypatch.setenv("JINA_API_KEY", "fake-api-key")
|
|
16
|
+
embedder = JinaTextEmbedder()
|
|
17
|
+
|
|
18
|
+
assert embedder.model_name == "jina-embeddings-v2-base-en"
|
|
19
|
+
assert embedder.prefix == ""
|
|
20
|
+
assert embedder.suffix == ""
|
|
21
|
+
|
|
22
|
+
def test_init_with_parameters(self):
|
|
23
|
+
embedder = JinaTextEmbedder(
|
|
24
|
+
api_key="fake-api-key",
|
|
25
|
+
model_name="model",
|
|
26
|
+
prefix="prefix",
|
|
27
|
+
suffix="suffix",
|
|
28
|
+
)
|
|
29
|
+
assert embedder.model_name == "model"
|
|
30
|
+
assert embedder.prefix == "prefix"
|
|
31
|
+
assert embedder.suffix == "suffix"
|
|
32
|
+
|
|
33
|
+
def test_init_fail_wo_api_key(self, monkeypatch):
|
|
34
|
+
monkeypatch.delenv("JINA_API_KEY", raising=False)
|
|
35
|
+
with pytest.raises(ValueError, match="JinaTextEmbedder expects a Jina API key"):
|
|
36
|
+
JinaTextEmbedder()
|
|
37
|
+
|
|
38
|
+
def test_to_dict(self):
|
|
39
|
+
component = JinaTextEmbedder(api_key="fake-api-key")
|
|
40
|
+
data = component.to_dict()
|
|
41
|
+
assert data == {
|
|
42
|
+
"type": "jina_haystack.text_embedder.JinaTextEmbedder",
|
|
43
|
+
"init_parameters": {
|
|
44
|
+
"model_name": "jina-embeddings-v2-base-en",
|
|
45
|
+
"prefix": "",
|
|
46
|
+
"suffix": "",
|
|
47
|
+
},
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
def test_to_dict_with_custom_init_parameters(self):
|
|
51
|
+
component = JinaTextEmbedder(
|
|
52
|
+
api_key="fake-api-key",
|
|
53
|
+
model_name="model",
|
|
54
|
+
prefix="prefix",
|
|
55
|
+
suffix="suffix",
|
|
56
|
+
)
|
|
57
|
+
data = component.to_dict()
|
|
58
|
+
assert data == {
|
|
59
|
+
"type": "jina_haystack.text_embedder.JinaTextEmbedder",
|
|
60
|
+
"init_parameters": {
|
|
61
|
+
"model_name": "model",
|
|
62
|
+
"prefix": "prefix",
|
|
63
|
+
"suffix": "suffix",
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
def test_run(self):
|
|
68
|
+
model = "jina-embeddings-v2-base-en"
|
|
69
|
+
with patch("requests.sessions.Session.post") as mock_post:
|
|
70
|
+
# Configure the mock to return a specific response
|
|
71
|
+
mock_response = requests.Response()
|
|
72
|
+
mock_response.status_code = 200
|
|
73
|
+
mock_response._content = json.dumps(
|
|
74
|
+
{
|
|
75
|
+
"model": "jina-embeddings-v2-base-en",
|
|
76
|
+
"object": "list",
|
|
77
|
+
"usage": {"total_tokens": 6, "prompt_tokens": 6},
|
|
78
|
+
"data": [{"object": "embedding", "index": 0, "embedding": [0.1, 0.2, 0.3]}],
|
|
79
|
+
}
|
|
80
|
+
).encode()
|
|
81
|
+
|
|
82
|
+
mock_post.return_value = mock_response
|
|
83
|
+
|
|
84
|
+
embedder = JinaTextEmbedder(api_key="fake-api-key", model_name=model, prefix="prefix ", suffix=" suffix")
|
|
85
|
+
result = embedder.run(text="The food was delicious")
|
|
86
|
+
|
|
87
|
+
assert len(result["embedding"]) == 3
|
|
88
|
+
assert all(isinstance(x, float) for x in result["embedding"])
|
|
89
|
+
assert result["metadata"] == {
|
|
90
|
+
"model": "jina-embeddings-v2-base-en",
|
|
91
|
+
"usage": {"prompt_tokens": 6, "total_tokens": 6},
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
def test_run_wrong_input_format(self):
|
|
95
|
+
embedder = JinaTextEmbedder(api_key="fake-api-key")
|
|
96
|
+
|
|
97
|
+
list_integers_input = [1, 2, 3]
|
|
98
|
+
|
|
99
|
+
with pytest.raises(TypeError, match="JinaTextEmbedder expects a string as an input"):
|
|
100
|
+
embedder.run(text=list_integers_input)
|