-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathencoder.py
237 lines (216 loc) · 8.49 KB
/
encoder.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import os
import logging
import chromadb
import pandas as pd
from typing import List
from chromadb.utils import embedding_functions
from chromadb.api.models.Collection import Collection
from chromadb.api.types import Documents, EmbeddingFunction, Embeddings
from beir.retrieval import models
from conferenceqa import ConferenceQA
from utils.gpt import OpenaiAda002, get_api_key
logger = logging.getLogger(__name__)
class NewEmbeddingFunction(EmbeddingFunction):
def __init__(self, encoder) -> None:
super().__init__()
self.encoder = encoder
def __call__(self, texts: Documents) -> Embeddings:
# embed the documents somehow
embeddings = self.encoder.encode_queries(texts)
return embeddings
class Encoder:
def __init__(self, encoder_name: str) -> None:
self.encoder_name = encoder_name
if encoder_name == "text-embedding-002":
self.encoder = OpenaiAda002()
self.ef = embedding_functions.OpenAIEmbeddingFunction(
api_key="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",
model_name="text-embedding-ada-002",
)
elif encoder_name == "SentenceBERT":
self.encoder = models.SentenceBERT("msmarco-distilbert-base-tas-b")
self.ef = embedding_functions.SentenceTransformerEmbeddingFunction(
model_name="msmarco-distilbert-base-tas-b"
)
elif encoder_name == "ANCE":
self.encoder = models.SentenceBERT("msmarco-roberta-base-ance-firstp")
self.ef = NewEmbeddingFunction(self.encoder)
self.collection_descs: Collection = None
self.collection_values: Collection = None
self.collection_path_and_value: Collection = None
def _get_embedding_and_save_to_chroma(
self,
qa: ConferenceQA = None,
docs: List[str] = None,
kind: str = "descs",
similarity: str = "cosine",
batch_size: int = 16,
path: str = None,
):
name = "path" if kind == "descs" else kind
if not os.path.exists(path):
print(path)
chroma_client = chromadb.PersistentClient(path=path)
logger.info(f"start geting {kind} embeddings...")
embeddings = self.encoder.doc_model.encode(
docs, batch_size=batch_size, show_progress_bar=True
)
setattr(
self,
f"collection_{kind}",
chroma_client.create_collection(
name=name,
metadata={"hnsw:space": similarity},
embedding_function=self.ef,
),
)
if not isinstance(embeddings, list):
embeddings = embeddings.tolist()
collection = getattr(self, f"collection_{kind}")
collection.add(
embeddings=embeddings,
documents=docs,
metadatas=[
{"source": f"{qa.cfe_name.upper()}2023"} for i in range(len(docs))
],
ids=[str(i) for i in range(len(docs))],
)
else:
chroma_client = chromadb.PersistentClient(path=path)
setattr(
self,
f"collection_{kind}",
chroma_client.get_collection(
name=name,
embedding_function=self.ef,
),
)
def get_embedding(
self,
qa: ConferenceQA = None,
similarity: str = "cosine",
batch_size: int = 16,
persist_chroma_path: str = None,
persist_csv_path: str = None,
):
get_api_key(0)
self.cfe_name = qa.cfe_name
descs = qa.descs
values = qa.values
paths = qa.paths
entry_desc = [v for _, v in qa.entry2desc.items()]
desc_leaf = []
entry_desc_wo_pre = [v for _, v in qa.entry2desc_wo_pre.items()]
desc_and_path = [qa.path2desc[path] + f' And the value of this query path is {qa.path2value[path]}' for path in qa.paths]
path_and_value = [path + ">>" + qa.path2value[path] for path in qa.paths]
if persist_chroma_path is not None:
if not os.path.exists(persist_chroma_path):
os.mkdir(persist_chroma_path)
descs_path = os.path.join(
persist_chroma_path,
f"{self.cfe_name.upper()}2023_{self.encoder_name}_descs",
)
self._get_embedding_and_save_to_chroma(
qa=qa,
docs=descs,
kind="descs",
similarity=similarity,
batch_size=batch_size,
path=descs_path,
)
paths_path = os.path.join(
persist_chroma_path, f"{self.cfe_name.upper()}2023_{self.encoder_name}_paths"
)
# self._get_embedding_and_save_to_chroma(
# qa=qa,
# docs=paths,
# kind="paths",
# similarity=similarity,
# batch_size=batch_size,
# path=paths_path,
# )
desc_and_value_path = os.path.join(
persist_chroma_path, f"{self.cfe_name.upper()}2023_{self.encoder_name}_desc_and_value"
)
self._get_embedding_and_save_to_chroma(
qa=qa,
docs=desc_and_path,
kind="desc_and_value",
similarity=similarity,
batch_size=batch_size,
path=desc_and_value_path,
)
values_path = os.path.join(
persist_chroma_path, f"{self.cfe_name.upper()}2023_{self.encoder_name}_values"
)
self._get_embedding_and_save_to_chroma(
qa=qa,
docs=values,
kind="values",
similarity=similarity,
batch_size=batch_size,
path=values_path,
)
path_and_value_path = os.path.join(
persist_chroma_path,
f"{self.cfe_name.upper()}2023_{self.encoder_name}_path_and_value",
)
self._get_embedding_and_save_to_chroma(
qa=qa,
docs=path_and_value,
kind="path_and_value",
similarity=similarity,
batch_size=batch_size,
path=path_and_value_path,
)
desc_leaf_path = os.path.join(
persist_chroma_path,
f"{self.cfe_name.upper()}2023_{self.encoder_name}_desc_leaf",
)
self._get_embedding_and_save_to_chroma(
qa=qa,
docs=desc_leaf,
kind="desc_leaf",
similarity=similarity,
batch_size=batch_size,
path=desc_leaf_path,
)
entry_desc_path = os.path.join(
persist_chroma_path,
f"{self.cfe_name.upper()}2023_{self.encoder_name}_entry_desc",
)
self._get_embedding_and_save_to_chroma(
qa=qa,
docs=entry_desc,
kind="entry_desc",
similarity=similarity,
batch_size=batch_size,
path=entry_desc_path,
)
entry_desc_wo_pre_path = os.path.join(
persist_chroma_path,
f"{self.cfe_name.upper()}2023_{self.encoder_name}_entry_desc_wo_pre",
)
self._get_embedding_and_save_to_chroma(
qa=qa,
docs=entry_desc_wo_pre,
kind="entry_desc_wo_pre",
similarity=similarity,
batch_size=batch_size,
path=entry_desc_wo_pre_path,
)
if persist_csv_path is not None:
descs_path = os.path.join(
persist_csv_path,
f"{self.cfe_name.upper()}2023_{self.encoder_name}_descs.csv",
)
if not os.path.exists(descs_path):
df = pd.DataFrame({"text": descs, "embedding": self.embedding_descs})
df.to_csv(descs_path, index=False)
values_path = os.path.join(
persist_csv_path,
f"{self.cfe_name.upper()}2023_{self.encoder_name}_values.csv",
)
if not os.path.exists(descs_path):
df = pd.DataFrame({"text": values, "embedding": self.embedding_values})
df.to_csv(values_path, index=False)