-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathQdrantRag.py
213 lines (194 loc) · 7.93 KB
/
QdrantRag.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
from qdrant_client import QdrantClient, models
from sentence_transformers import SentenceTransformer
from transformers import AutoModel, AutoImageProcessor
import torch
import os
from datasets import load_dataset
from dotenv import load_dotenv
import numpy as np
import uuid
from PIL import Image
from fastembed import SparseTextEmbedding
import cohere
load_dotenv()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
encoder = SentenceTransformer("sentence-transformers/LaBSE").to(device)
processor = AutoImageProcessor.from_pretrained('facebook/dinov2-large')
image_encoder = AutoModel.from_pretrained("facebook/dinov2-large").to(device)
qdrant_client = QdrantClient("http://localhost:6333")
sparse_encoder = SparseTextEmbedding(model_name="prithivida/Splade_PP_en_v1")
co = cohere.ClientV2(os.getenv("cohere_api_key"))
dataset = load_dataset("Karbo31881/Pokemon_images")
ds = dataset["train"]
labels = ds["text"]
def get_sparse_embedding(text: str, model: SparseTextEmbedding):
embeddings = list(model.embed(text))
vector = {f"sparse-text": models.SparseVector(indices=embeddings[0].indices, values=embeddings[0].values)}
return vector
def get_query_sparse_embedding(text: str, model: SparseTextEmbedding):
embeddings = list(model.embed(text))
query_vector = models.NamedSparseVector(
name="sparse-text",
vector=models.SparseVector(
indices=embeddings[0].indices,
values=embeddings[0].values,
),
)
return query_vector
def upload_text_to_qdrant(client: QdrantClient, collection_name: str, encoder: SentenceTransformer, text: str, point_id_dense: int, point_id_sparse: int):
try:
docs = {"text": text}
client.upsert(
collection_name=collection_name,
points=[
models.PointStruct(
id=point_id_dense,
vector={f"dense-text": encoder.encode(docs["text"]).tolist()},
payload=docs,
)
],
)
client.upsert(
collection_name=collection_name,
points=[
models.PointStruct(
id=point_id_sparse,
vector=get_sparse_embedding(docs["text"], sparse_encoder),
payload=docs,
)
],
)
return True
except Exception as e:
return False
def upload_images_to_qdrant(client: QdrantClient, collection_name: str, vectorsfile: str, labelslist: list):
try:
vectors = np.load(vectorsfile)
docs = []
for label in labelslist:
docs.append({"label": label})
client.upload_points(
collection_name=collection_name,
points=[
models.PointStruct(
id=idx,
vector=vectors[idx].tolist(),
payload=doc,
)
for idx, doc in enumerate(docs)
],
)
return True
except Exception as e:
return False
class SemanticCache:
def __init__(self, client: QdrantClient, text_encoder: SentenceTransformer, collection_name: str, threshold: float = 0.75):
self.client = client
self.text_encoder = text_encoder
self.collection_name = collection_name
self.threshold = threshold
def upload_to_cache(self, question: str, answer: str):
docs = {"question": question, "answer": answer}
point_id = str(uuid.uuid4())
self.client.upsert(
collection_name=self.collection_name,
points=[
models.PointStruct(
id=point_id,
vector=self.text_encoder.encode(docs["question"]).tolist(),
payload=docs,
)
],
)
def search_cache(self, question: str, limit: int = 5):
vector = self.text_encoder.encode(question).tolist()
search_result = self.client.search(
collection_name=self.collection_name,
query_vector=vector,
query_filter=None,
limit=limit,
)
payloads = [hit.payload["answer"] for hit in search_result if hit.score > self.threshold]
if len(payloads) > 0:
return payloads[0]
else:
return ""
class NeuralSearcher:
def __init__(self, text_collection_name: str, image_collection_name: str, client: QdrantClient, text_encoder: SentenceTransformer , image_encoder: AutoModel, image_processor: AutoImageProcessor, sparse_encoder: SparseTextEmbedding):
self.text_collection_name = text_collection_name
self.image_collection_name = image_collection_name
self.text_encoder = text_encoder
self.image_encoder = image_encoder
self.image_processor = image_processor
self.qdrant_client = client
self.sparse_encoder = sparse_encoder
def search_text(self, text: str, limit: int = 5):
vector = self.text_encoder.encode(text).tolist()
search_result_dense = self.qdrant_client.search(
collection_name=self.text_collection_name,
query_vector=models.NamedVector(name="dense-text", vector=vector),
query_filter=None,
limit=limit,
)
search_result_sparse = self.qdrant_client.search(
collection_name=self.text_collection_name,
query_vector=get_query_sparse_embedding(text, self.sparse_encoder),
query_filter=None,
limit=limit,
)
payloads = [hit.payload["text"] for hit in search_result_dense]
payloads += [hit.payload["text"] for hit in search_result_sparse]
return payloads
def reranking(self, text: str, search_result: list):
results = co.rerank(model="rerank-v3.5", query=text, documents=search_result, top_n = 3)
ranked_results = [search_result[results.results[i].index] for i in range(3)]
return ranked_results
def search_image(self, image: str, limit: int = 5):
img = Image.open(image)
inputs = self.image_processor(images=img, return_tensors="pt").to(device)
with torch.no_grad():
outputs = self.image_encoder(**inputs).last_hidden_state.mean(dim=1).cpu().numpy()
search_result = self.qdrant_client.search(
collection_name=self.image_collection_name,
query_vector=outputs[0].tolist(),
query_filter=None,
limit=limit,
)
payloads = [f"- {hit.payload['label']} with score {hit.score}" for hit in search_result]
return payloads
qdrant_client.recreate_collection(
collection_name="pokemon_texts",
vectors_config={"dense-text": models.VectorParams(
size=768, # Vector size is defined by used model
distance=models.Distance.COSINE,
)},
sparse_vectors_config={"sparse-text": models.SparseVectorParams(
index=models.SparseIndexParams(
on_disk=False
)
)}
)
textdata = load_dataset("wanghaofan/pokemon-wiki-captions")
names = textdata["train"]["name_en"]
texts = textdata["train"]["text_en"]
c = 0
for j in range(len(texts)):
txt = names[j].upper() + "\n\n" + texts[j]
l = c+1
upload_text_to_qdrant(qdrant_client, "pokemon_texts", encoder, txt, c, l)
c = l+1
qdrant_client.recreate_collection(
collection_name="pokemon_images",
vectors_config=models.VectorParams(
size=1024, # Vector size is defined by used model
distance=models.Distance.COSINE,
),
)
upload_images_to_qdrant(qdrant_client, "pokemon_images", "data/vector_pokemon.npy", labels)
qdrant_client.recreate_collection(
collection_name="semantic_cache",
vectors_config=models.VectorParams(
size=768, # Vector size is defined by used model
distance=models.Distance.COSINE,
),
)