fastembed 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.
- fastembed-0.0.1/LICENSE +201 -0
- fastembed-0.0.1/PKG-INFO +69 -0
- fastembed-0.0.1/README.md +43 -0
- fastembed-0.0.1/fastembed/embedding.py +207 -0
- fastembed-0.0.1/fastembed/qdrant_client.py +20 -0
- fastembed-0.0.1/fastembed/qdrant_mixin.py +150 -0
- fastembed-0.0.1/pyproject.toml +42 -0
fastembed-0.0.1/LICENSE
ADDED
|
@@ -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 [yyyy] [name of copyright owner]
|
|
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.
|
fastembed-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: fastembed
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Fast Embedding Creation and Simpler API for Qdrant
|
|
5
|
+
Home-page: https://github.com/qdrant/fastembed
|
|
6
|
+
License: Apache License
|
|
7
|
+
Keywords: vector,embedding,neural,search,qdrant,sentence-transformers
|
|
8
|
+
Author: NirantK
|
|
9
|
+
Author-email: nirant.bits@gmail.com
|
|
10
|
+
Requires-Python: >=3.8.0,<3.12
|
|
11
|
+
Classifier: License :: Other/Proprietary License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
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
|
+
Requires-Dist: onnxruntime (>=1.15.1,<2.0.0)
|
|
18
|
+
Requires-Dist: onnxruntime-silicon (>=1.15.0,<2.0.0) ; sys_platform == "darwin"
|
|
19
|
+
Requires-Dist: requests (>=2.31.0,<3.0.0)
|
|
20
|
+
Requires-Dist: sentence-transformers (>=2.2.2,<3.0.0)
|
|
21
|
+
Requires-Dist: tokenizers (>=0.13.3,<0.14.0)
|
|
22
|
+
Requires-Dist: tqdm (>=4.65.0,<5.0.0)
|
|
23
|
+
Project-URL: Repository, https://github.com/qdrant/fastembed
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# FastEmbed Library
|
|
27
|
+
|
|
28
|
+
FastEmbed is a Python library that provides convenient methods for indexing and searching text documents using Qdrant, a high-dimensional vector indexing and search system.
|
|
29
|
+
|
|
30
|
+
## Features
|
|
31
|
+
|
|
32
|
+
- Batch document insertion with automatic embedding using SentenceTransformers. With support for OpenAI and custom embeddings.
|
|
33
|
+
- Efficient batch searching with support for filtering by metadata.
|
|
34
|
+
- Automatic generation of unique IDs for documents.
|
|
35
|
+
- Convenient alias methods for adding documents and performing queries.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
To install the FastEmbed library, we install Qdrant client as well with pip:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install fastembed qdrant-client
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Usage
|
|
46
|
+
|
|
47
|
+
Here's a simple usage example, which works as is:
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from qdrant_client import QdrantClient
|
|
51
|
+
|
|
52
|
+
# Initialize the client
|
|
53
|
+
client = QdrantClient(":memory:") # or QdrantClient(path="path/to/db")
|
|
54
|
+
|
|
55
|
+
# Prepare your documents, metadata, and IDs
|
|
56
|
+
docs = ["Qdrant has Langchain integrations", "Qdrant also has Llama Index integrations"]
|
|
57
|
+
metadatas = [
|
|
58
|
+
{"source": "Langchain-docs"},
|
|
59
|
+
{"source": "Linkedin-docs"},
|
|
60
|
+
]
|
|
61
|
+
ids = [42, 2]
|
|
62
|
+
|
|
63
|
+
# Use the new add method
|
|
64
|
+
client.add(collection_name="demo_collection", docs={"documents": docs, "metadatas": metadatas, "ids": ids})
|
|
65
|
+
|
|
66
|
+
search_result = client.query(collection_name="demo_collection", query_texts=["This is a query document"])
|
|
67
|
+
print(search_result)
|
|
68
|
+
```
|
|
69
|
+
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# FastEmbed Library
|
|
2
|
+
|
|
3
|
+
FastEmbed is a Python library that provides convenient methods for indexing and searching text documents using Qdrant, a high-dimensional vector indexing and search system.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- Batch document insertion with automatic embedding using SentenceTransformers. With support for OpenAI and custom embeddings.
|
|
8
|
+
- Efficient batch searching with support for filtering by metadata.
|
|
9
|
+
- Automatic generation of unique IDs for documents.
|
|
10
|
+
- Convenient alias methods for adding documents and performing queries.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
To install the FastEmbed library, we install Qdrant client as well with pip:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install fastembed qdrant-client
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
Here's a simple usage example, which works as is:
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from qdrant_client import QdrantClient
|
|
26
|
+
|
|
27
|
+
# Initialize the client
|
|
28
|
+
client = QdrantClient(":memory:") # or QdrantClient(path="path/to/db")
|
|
29
|
+
|
|
30
|
+
# Prepare your documents, metadata, and IDs
|
|
31
|
+
docs = ["Qdrant has Langchain integrations", "Qdrant also has Llama Index integrations"]
|
|
32
|
+
metadatas = [
|
|
33
|
+
{"source": "Langchain-docs"},
|
|
34
|
+
{"source": "Linkedin-docs"},
|
|
35
|
+
]
|
|
36
|
+
ids = [42, 2]
|
|
37
|
+
|
|
38
|
+
# Use the new add method
|
|
39
|
+
client.add(collection_name="demo_collection", docs={"documents": docs, "metadatas": metadatas, "ids": ids})
|
|
40
|
+
|
|
41
|
+
search_result = client.query(collection_name="demo_collection", query_texts=["This is a query document"])
|
|
42
|
+
print(search_result)
|
|
43
|
+
```
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import shutil
|
|
3
|
+
import tarfile
|
|
4
|
+
import tempfile
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, List
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import onnxruntime as ort
|
|
11
|
+
import requests
|
|
12
|
+
from tokenizers import Tokenizer
|
|
13
|
+
from tqdm import tqdm
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# Use pytorches default epsilon for division by zero
|
|
17
|
+
# https://pytorch.org/docs/stable/generated/torch.nn.functional.normalize.html
|
|
18
|
+
def normalize(v):
|
|
19
|
+
norm = np.linalg.norm(v, axis=1)
|
|
20
|
+
norm[norm == 0] = 1e-12
|
|
21
|
+
return v / norm[:, np.newaxis]
|
|
22
|
+
|
|
23
|
+
class Embedding(ABC):
|
|
24
|
+
@abstractmethod
|
|
25
|
+
def encode(self, texts: List[str])->List[np.ndarray]:
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
class DefaultEmbedding(Embedding):
|
|
29
|
+
def download_file_from_gcs(self, url: str, output_path: str, show_progress: bool=True):
|
|
30
|
+
if os.path.exists(output_path):
|
|
31
|
+
return output_path
|
|
32
|
+
response = requests.get(url, stream=True)
|
|
33
|
+
|
|
34
|
+
# Handle HTTP errors
|
|
35
|
+
if response.status_code == 403:
|
|
36
|
+
print("Authentication error: you do not have permission to access this resource.")
|
|
37
|
+
return
|
|
38
|
+
elif response.status_code != 200:
|
|
39
|
+
print(f"HTTP error {response.status_code} while trying to download the file.")
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
# Get the total size of the file
|
|
43
|
+
total_size_in_bytes = int(response.headers.get("content-length", 0))
|
|
44
|
+
|
|
45
|
+
# Warn if the total size is zero
|
|
46
|
+
if total_size_in_bytes == 0:
|
|
47
|
+
print(f"Warning: Content-length header is missing or zero in the response from {url}.")
|
|
48
|
+
|
|
49
|
+
# Initialize the progress bar
|
|
50
|
+
progress_bar = (
|
|
51
|
+
tqdm(total=total_size_in_bytes, unit="iB", unit_scale=True) if total_size_in_bytes and show_progress else None
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
# Attempt to download the file
|
|
55
|
+
try:
|
|
56
|
+
with open(output_path, "wb") as file:
|
|
57
|
+
for chunk in response.iter_content(chunk_size=1024): # Adjust chunk size to your preference
|
|
58
|
+
if chunk: # Filter out keep-alive new chunks
|
|
59
|
+
if progress_bar is not None:
|
|
60
|
+
progress_bar.update(len(chunk))
|
|
61
|
+
file.write(chunk)
|
|
62
|
+
except Exception as e:
|
|
63
|
+
print(f"An error occurred while trying to download the file: {str(e)}")
|
|
64
|
+
return
|
|
65
|
+
finally:
|
|
66
|
+
if progress_bar is not None:
|
|
67
|
+
progress_bar.close()
|
|
68
|
+
return output_path
|
|
69
|
+
|
|
70
|
+
def decompress_to_cache(self, targz_path: str, cache_dir: str=None):
|
|
71
|
+
# Check if targz_path exists and is a file
|
|
72
|
+
if not os.path.isfile(targz_path):
|
|
73
|
+
raise ValueError(f"{targz_path} does not exist or is not a file.")
|
|
74
|
+
|
|
75
|
+
# Check if targz_path is a .tar.gz file
|
|
76
|
+
if not targz_path.endswith(".tar.gz"):
|
|
77
|
+
raise ValueError(f"{targz_path} is not a .tar.gz file.")
|
|
78
|
+
|
|
79
|
+
# Create a temporary directory for caching if cache_dir is not provided
|
|
80
|
+
if cache_dir is None:
|
|
81
|
+
cache_dir = tempfile.mkdtemp()
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
# Open the tar.gz file
|
|
85
|
+
with tarfile.open(targz_path, "r:gz") as tar:
|
|
86
|
+
# Extract all files into the cache directory
|
|
87
|
+
tar.extractall(path=cache_dir)
|
|
88
|
+
print(f"Files have been decompressed into {cache_dir}")
|
|
89
|
+
except tarfile.TarError as e:
|
|
90
|
+
# If any error occurs while opening or extracting the tar.gz file,
|
|
91
|
+
# delete the cache directory (if it was created in this function)
|
|
92
|
+
# and raise the error again
|
|
93
|
+
if "tmp" in cache_dir:
|
|
94
|
+
shutil.rmtree(cache_dir)
|
|
95
|
+
raise ValueError(f"An error occurred while decompressing {targz_path}: {e}")
|
|
96
|
+
|
|
97
|
+
return cache_dir
|
|
98
|
+
|
|
99
|
+
def __init__(self, model_name="sentence-transformers/all-MiniLM-L6-v2"):
|
|
100
|
+
filepath = self.download_file_from_gcs(
|
|
101
|
+
"https://storage.googleapis.com/qdrant-fastembed/fast-all-MiniLM-L6-v2.tar.gz", output_path="fast-all-MiniLM-L6-v2.tar.gz"
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
model_dir = self.decompress_to_cache(targz_path=filepath)
|
|
105
|
+
|
|
106
|
+
model_dir = Path(model_dir) / "fast-all-MiniLM-L6-v2"
|
|
107
|
+
tokenizer_path = model_dir / "tokenizer.json"
|
|
108
|
+
if not tokenizer_path.exists():
|
|
109
|
+
raise ValueError(f"Could not find tokenizer.json in {model_dir}")
|
|
110
|
+
model_path = model_dir / "model_optimized.onnx"
|
|
111
|
+
if not model_path.exists():
|
|
112
|
+
raise ValueError(f"Could not find model_optimized.onnx in {model_dir}")
|
|
113
|
+
|
|
114
|
+
self.tokenizer = Tokenizer.from_file(str(tokenizer_path))
|
|
115
|
+
self.tokenizer.enable_truncation(max_length=256)
|
|
116
|
+
self.tokenizer.enable_padding(pad_id=0, pad_token="[PAD]", length=256)
|
|
117
|
+
self.model = ort.InferenceSession(str(model_path), providers=['CoreMLExecutionProvider', 'CPUExecutionProvider'])
|
|
118
|
+
|
|
119
|
+
def encode(self, documents: List[str], batch_size: int = 32) -> List[np.ndarray]:
|
|
120
|
+
# Encode documents using the model
|
|
121
|
+
# https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2
|
|
122
|
+
|
|
123
|
+
all_embeddings = []
|
|
124
|
+
for i in range(0, len(documents), batch_size):
|
|
125
|
+
batch = documents[i:i + batch_size]
|
|
126
|
+
encoded = [self.tokenizer.encode(d) for d in batch]
|
|
127
|
+
input_ids = np.array([e.ids for e in encoded])
|
|
128
|
+
attention_mask = np.array([e.attention_mask for e in encoded])
|
|
129
|
+
onnx_input = {
|
|
130
|
+
"input_ids": np.array(input_ids, dtype=np.int64),
|
|
131
|
+
"attention_mask": np.array(attention_mask, dtype=np.int64),
|
|
132
|
+
"token_type_ids": np.array([np.zeros(len(e), dtype=np.int64) for e in input_ids], dtype=np.int64),
|
|
133
|
+
}
|
|
134
|
+
model_output = self.model.run(None, onnx_input)
|
|
135
|
+
last_hidden_state = model_output[0]
|
|
136
|
+
# Perform mean pooling with attention weighting
|
|
137
|
+
input_mask_expanded = np.broadcast_to(np.expand_dims(attention_mask, -1), last_hidden_state.shape)
|
|
138
|
+
embeddings = np.sum(last_hidden_state * input_mask_expanded, 1) / np.clip(input_mask_expanded.sum(1), a_min=1e-9, a_max=None)
|
|
139
|
+
embeddings = normalize(embeddings).astype(np.float32)
|
|
140
|
+
all_embeddings.append(embeddings)
|
|
141
|
+
return np.concatenate(all_embeddings)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class SentenceTransformersEmbedding(Embedding):
|
|
148
|
+
def __init__(self, model_name="sentence-transformers/all-MiniLM-L6-v2"):
|
|
149
|
+
try:
|
|
150
|
+
from sentence_transformers import SentenceTransformer
|
|
151
|
+
except ImportError:
|
|
152
|
+
raise ImportError("Please install the sentence-transformers package to use this method.")
|
|
153
|
+
self.model = SentenceTransformer(model_name)
|
|
154
|
+
|
|
155
|
+
def encode(self, texts):
|
|
156
|
+
return self.model.encode(texts)
|
|
157
|
+
|
|
158
|
+
class GeneralTextEmbedding(Embedding):
|
|
159
|
+
"""
|
|
160
|
+
https://huggingface.co/thenlper/gte-large
|
|
161
|
+
|
|
162
|
+
SoTA embedding model for text based retrieval tasks.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
@classmethod
|
|
166
|
+
def average_pool(last_hidden_states: Any,
|
|
167
|
+
attention_mask: Any) -> Any:
|
|
168
|
+
last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
|
|
169
|
+
return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
|
|
170
|
+
|
|
171
|
+
def __init__(self, model_name="thenlper/gte-large"):
|
|
172
|
+
try:
|
|
173
|
+
import torch.nn.functional as F
|
|
174
|
+
from transformers import AutoModel, AutoTokenizer
|
|
175
|
+
except ImportError:
|
|
176
|
+
raise ImportError("Please install the transformers package with torch to use this method.")
|
|
177
|
+
self.tokenizer = AutoTokenizer.from_pretrained("thenlper/gte-large")
|
|
178
|
+
self.model = AutoModel.from_pretrained("thenlper/gte-large")
|
|
179
|
+
|
|
180
|
+
def encode(self, input_texts: List[str]):
|
|
181
|
+
try:
|
|
182
|
+
import torch.nn.functional as F
|
|
183
|
+
except ImportError:
|
|
184
|
+
raise ImportError("Please install Pytorch to use this method.")
|
|
185
|
+
# Tokenize the input texts
|
|
186
|
+
batch_dict = self.tokenizer(input_texts, max_length=512, padding=True, truncation=True, return_tensors='pt')
|
|
187
|
+
|
|
188
|
+
outputs = self.model(**batch_dict)
|
|
189
|
+
embeddings = GeneralTextEmbedding.average_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
|
|
190
|
+
|
|
191
|
+
# (Optionally) normalize embeddings
|
|
192
|
+
embeddings = F.normalize(embeddings, p=2, dim=1)
|
|
193
|
+
scores = (embeddings[:1] @ embeddings[1:].T) * 100
|
|
194
|
+
return scores
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class OpenAIEmbedding(Embedding):
|
|
199
|
+
def __init__(self):
|
|
200
|
+
# Initialize your OpenAI model here
|
|
201
|
+
# self.model = ...
|
|
202
|
+
...
|
|
203
|
+
|
|
204
|
+
def encode(self, texts):
|
|
205
|
+
# Use your OpenAI model to encode the texts
|
|
206
|
+
# return self.model.encode(texts)
|
|
207
|
+
raise NotImplementedError
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# qdrant_client.py
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class QdrantClient:
|
|
5
|
+
# Existing QdrantClient implementation...
|
|
6
|
+
|
|
7
|
+
def __init__(self, *args, **kwargs):
|
|
8
|
+
super().__init__(*args, **kwargs)
|
|
9
|
+
|
|
10
|
+
# Check if fastvector is installed
|
|
11
|
+
try:
|
|
12
|
+
from fastembed.qdrant_mixin import QdrantClientMixin
|
|
13
|
+
|
|
14
|
+
# If it is, add the mixin methods to this instance
|
|
15
|
+
for name, method in QdrantClientMixin.__dict__.items():
|
|
16
|
+
if callable(method):
|
|
17
|
+
setattr(self, name, method.__get__(self, self.__class__))
|
|
18
|
+
except ImportError:
|
|
19
|
+
# If it's not, do nothing
|
|
20
|
+
pass
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from typing import Any, Dict, Generator, List, Optional
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel
|
|
5
|
+
from qdrant_client.models import Distance, PointStruct, SearchParams, VectorParams
|
|
6
|
+
|
|
7
|
+
from .embedding import DefaultEmbedding, Embedding
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class QueryResponse(BaseModel):
|
|
11
|
+
ids: List[str]
|
|
12
|
+
embeddings: Optional[List[List[float]]]
|
|
13
|
+
metadatas: List[Dict[str, Any]]
|
|
14
|
+
distances: List[float]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class QdrantClientMixin:
|
|
18
|
+
def batch_iterable(self, iterable: List[Any], batch_size: int) -> Generator[List[Any], None, None]:
|
|
19
|
+
"""A generator that yields batches of items from an iterable."""
|
|
20
|
+
batch = []
|
|
21
|
+
for item in iterable:
|
|
22
|
+
batch.append(item)
|
|
23
|
+
if len(batch) >= batch_size:
|
|
24
|
+
yield batch
|
|
25
|
+
batch = []
|
|
26
|
+
if batch:
|
|
27
|
+
yield batch
|
|
28
|
+
|
|
29
|
+
def create_collection(
|
|
30
|
+
self,
|
|
31
|
+
collection_name: str,
|
|
32
|
+
vectors_config: VectorParams = VectorParams(size=1536, distance=Distance.COSINE),
|
|
33
|
+
**kwargs,
|
|
34
|
+
) -> None:
|
|
35
|
+
"""
|
|
36
|
+
Create a collection with the given name and vectors config.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
collection_name (str): _description_
|
|
40
|
+
vectors_config (VectorParams, optional): Defaults to VectorParams(size=1536, distance=Distance.COSINE).
|
|
41
|
+
"""
|
|
42
|
+
self.recreate_collection(collection_name=collection_name, vectors_config=vectors_config, **kwargs)
|
|
43
|
+
|
|
44
|
+
def upsert_docs(
|
|
45
|
+
self,
|
|
46
|
+
collection_name: str,
|
|
47
|
+
docs: Dict[str, List[Any]],
|
|
48
|
+
batch_size: int = 512,
|
|
49
|
+
wait: bool = True,
|
|
50
|
+
embedding_model: Embedding = DefaultEmbedding(),
|
|
51
|
+
**kwargs,
|
|
52
|
+
) -> None:
|
|
53
|
+
"""
|
|
54
|
+
Args:
|
|
55
|
+
collection_name (str): _description_
|
|
56
|
+
docs (Dict[str, List[Any]]): _description_
|
|
57
|
+
batch_size (int, optional): _description_. Defaults to 512.
|
|
58
|
+
wait (bool, optional): _description_. Defaults to True.
|
|
59
|
+
embedding_model (Embedding, optional): Defaults to DefaultEmbedding() with all-MiniLM-L6-v2.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
# Iterate over documents and metadatas in batches
|
|
63
|
+
for batch_docs, batch_metadatas in zip(
|
|
64
|
+
self.batch_iterable(docs["documents"], batch_size),
|
|
65
|
+
self.batch_iterable(docs["metadatas"], batch_size),
|
|
66
|
+
):
|
|
67
|
+
# Tokenize, embed, and index each document
|
|
68
|
+
embeddings = embedding_model.encode(batch_docs)
|
|
69
|
+
|
|
70
|
+
# Create a PointStruct for each document
|
|
71
|
+
points = [
|
|
72
|
+
PointStruct(id=uuid.uuid4().hex, vector=embedding.tolist(), payload={**metadata, "text": doc})
|
|
73
|
+
for doc, embedding, metadata in zip(batch_docs, embeddings, batch_metadatas)
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
# Check if collection exists
|
|
77
|
+
if collection_name not in self.get_collections():
|
|
78
|
+
self.create_collection(
|
|
79
|
+
collection_name=collection_name,
|
|
80
|
+
vectors_config=VectorParams(size=len(embeddings[0]), distance=Distance.COSINE),
|
|
81
|
+
)
|
|
82
|
+
# Call the existing upsert method with the new PointStruct
|
|
83
|
+
self.upsert(collection_name=collection_name, points=points, wait=wait, **kwargs)
|
|
84
|
+
|
|
85
|
+
def search_docs(
|
|
86
|
+
self,
|
|
87
|
+
collection_name: str,
|
|
88
|
+
query_texts: List[str],
|
|
89
|
+
n_results: int = 2,
|
|
90
|
+
batch_size: int = 512,
|
|
91
|
+
query_filter: Optional[Dict[str, Any]] = None,
|
|
92
|
+
search_params: SearchParams = SearchParams(hnsw_ef=128, exact=False),
|
|
93
|
+
embedding_model: Embedding = DefaultEmbedding(),
|
|
94
|
+
**kwargs,
|
|
95
|
+
) -> List[QueryResponse]:
|
|
96
|
+
"""
|
|
97
|
+
Search for documents in a collection.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
collection_name (str): _description_
|
|
101
|
+
query_texts (List[str]): _description_
|
|
102
|
+
n_results (int, optional): _description_. Defaults to 2.
|
|
103
|
+
query_filter (Optional[Dict[str, Any]], optional): _description_. Defaults to None.
|
|
104
|
+
search_params (SearchParams, optional): _description_. Defaults to SearchParams(hnsw_ef=128, exact=False).
|
|
105
|
+
embedding_model (Embedding, optional): _description_. Defaults to SentenceTransformersEmbedding().
|
|
106
|
+
batch_size (int, optional): _description_. Defaults to 512.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
List[QueryResponse]: _description_
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
query_responses = []
|
|
113
|
+
|
|
114
|
+
# Perform the search for each batch of query texts
|
|
115
|
+
for query_texts_batch in self.batch_iterable(query_texts, batch_size):
|
|
116
|
+
query_vectors = embedding_model.encode(query_texts_batch)
|
|
117
|
+
|
|
118
|
+
for _, query_vector in zip(query_texts_batch, query_vectors):
|
|
119
|
+
search_result = self.search(
|
|
120
|
+
collection_name=collection_name,
|
|
121
|
+
query_filter=query_filter,
|
|
122
|
+
search_params=search_params,
|
|
123
|
+
query_vector=query_vector.tolist(),
|
|
124
|
+
limit=n_results,
|
|
125
|
+
with_payload=True,
|
|
126
|
+
**kwargs,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
ids, embeddings, metadatas, distances = [], [], [], []
|
|
130
|
+
for scored_point in search_result:
|
|
131
|
+
ids.append(scored_point.id)
|
|
132
|
+
if scored_point.vector:
|
|
133
|
+
embeddings.append(scored_point.vector)
|
|
134
|
+
metadatas.append(scored_point.payload)
|
|
135
|
+
distances.append(scored_point.score)
|
|
136
|
+
|
|
137
|
+
query_responses.append(
|
|
138
|
+
QueryResponse(
|
|
139
|
+
ids=ids,
|
|
140
|
+
embeddings=embeddings,
|
|
141
|
+
metadatas=metadatas,
|
|
142
|
+
distances=distances,
|
|
143
|
+
)
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
return query_responses
|
|
147
|
+
|
|
148
|
+
# Define aliases for the methods
|
|
149
|
+
add = upsert_docs
|
|
150
|
+
query = search_docs
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "fastembed"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
description = "Fast Embedding Creation and Simpler API for Qdrant"
|
|
5
|
+
authors = ["NirantK <nirant.bits@gmail.com>"]
|
|
6
|
+
license = "Apache License"
|
|
7
|
+
readme = "README.md"
|
|
8
|
+
packages = [{include = "fastembed"}]
|
|
9
|
+
homepage = "https://github.com/qdrant/fastembed"
|
|
10
|
+
repository = "https://github.com/qdrant/fastembed"
|
|
11
|
+
keywords = ["vector", "embedding", "neural", "search", "qdrant", "sentence-transformers"]
|
|
12
|
+
|
|
13
|
+
[tool.poetry.dependencies]
|
|
14
|
+
python = ">=3.8.0,<3.12"
|
|
15
|
+
onnxruntime = "^1.15.1"
|
|
16
|
+
sentence-transformers = "^2.2.2"
|
|
17
|
+
tqdm = "^4.65.0"
|
|
18
|
+
requests = "^2.31.0"
|
|
19
|
+
tokenizers = "^0.13.3"
|
|
20
|
+
|
|
21
|
+
[tool.poetry.dev-dependencies]
|
|
22
|
+
ruff = "^0.0.277"
|
|
23
|
+
isort = "^5.12.0"
|
|
24
|
+
black = "^23.7.0"
|
|
25
|
+
pre-commit = "^3.3.3"
|
|
26
|
+
|
|
27
|
+
[tool.poetry.dependencies.onnxruntime-silicon]
|
|
28
|
+
version = "^1.15.0"
|
|
29
|
+
markers = "sys_platform == 'darwin'" # This makes it macOS specific
|
|
30
|
+
|
|
31
|
+
[build-system]
|
|
32
|
+
requires = ["poetry-core"]
|
|
33
|
+
build-backend = "poetry.core.masonry.api"
|
|
34
|
+
|
|
35
|
+
[tool.black]
|
|
36
|
+
line-length = 120
|
|
37
|
+
|
|
38
|
+
[tool.isort]
|
|
39
|
+
profile = "black"
|
|
40
|
+
|
|
41
|
+
[tool.ruff]
|
|
42
|
+
line-length = 120
|