Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -32,33 +32,35 @@ class DocumentSearch:
|
|
32 |
# loading faiss index
|
33 |
self.index = faiss.read_index(DocumentSearch.idx_path)
|
34 |
# loading sbert cross_encoder
|
35 |
-
|
36 |
|
37 |
-
def search(self, query, k
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
|
47 |
-
|
48 |
-
###return[{'doc': doc[0], 'url': doc[1], 'score': dist} for doc, dist in zip(res_docs, dists)][:k]
|
49 |
-
##### OLD VERSION WITH CROSS-ENCODER #####
|
50 |
# get answers by index
|
51 |
-
|
52 |
# prepare inputs for cross encoder
|
53 |
-
|
54 |
-
|
55 |
# get similarity score between query and documents
|
56 |
-
|
57 |
# compose results into list of dicts
|
58 |
-
|
59 |
|
60 |
# return results sorted by similarity scores
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
|
64 |
if __name__ == "__main__":
|
|
|
32 |
# loading faiss index
|
33 |
self.index = faiss.read_index(DocumentSearch.idx_path)
|
34 |
# loading sbert cross_encoder
|
35 |
+
self.cross_encoder = CrossEncoder(DocumentSearch.cross_enc_path)
|
36 |
|
37 |
+
def search(self, query: str, k: int) -> list:
|
38 |
+
# get vector representation of text query
|
39 |
+
query_vector = self.encoder.encode([query])
|
40 |
+
# perform search via faiss FlatIP index
|
41 |
+
distances, indeces = self.index.search(query_vector, k*10)
|
42 |
+
# get docs by index
|
43 |
+
res_docs = [self.docs[i] for i in indeces[0]]
|
44 |
+
# get scores by index
|
45 |
+
dists = [dist for dist in distances[0]]
|
46 |
|
|
|
|
|
|
|
47 |
# get answers by index
|
48 |
+
answers = [self.docs[i] for i in indeces[0]]
|
49 |
# prepare inputs for cross encoder
|
50 |
+
model_inputs = [[query, pairs[0]] for pairs in answers]
|
51 |
+
urls = [pairs[1] for pairs in answers]
|
52 |
# get similarity score between query and documents
|
53 |
+
scores = self.cross_encoder.predict(model_inputs, batch_size=1)
|
54 |
# compose results into list of dicts
|
55 |
+
results = [{'doc': doc[1], 'url': url, 'score': score} for doc, url, score in zip(model_inputs, urls, scores)]
|
56 |
|
57 |
# return results sorted by similarity scores
|
58 |
+
return sorted(results, key=lambda x: x['score'], reverse=True)[:k]
|
59 |
+
|
60 |
+
|
61 |
+
if __name__ == "__main__":
|
62 |
+
# get instance of DocumentSearch class
|
63 |
+
surfer = DocumentSearch()
|
64 |
|
65 |
|
66 |
if __name__ == "__main__":
|