forked from Immortalise/SearchAnything
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanything.py
177 lines (123 loc) · 5.64 KB
/
anything.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
import os
from sentence_transformers import SentenceTransformer
from config import DATA_DIR, DB_PATH, TEXT_EMBEDDING_MODELS, IMAGE_EMBEDDING_MODELS
from database import Text_DB, Image_DB
from utils import encode_text, encode_image, list_files
from process import process_file
from index import SemanticIndex
class Anything(object):
def __init__(self, models=None):
if models is None:
default_models = ["sentence-transformers/all-mpnet-base-v2", "clip-ViT-B-32"]
if not os.path.exists(DATA_DIR):
os.makedirs(DATA_DIR)
self.dbs = self.load_dbs()
self.models = self.load_models(default_models)
self.index = self.load_index()
print("SearchAnything v1.0")
print("Type 'exit' to exit.\n\
Type 'insert' to parse file.\n\
Type 'search' to search file.\n\
Type 'delete' to delete file.")
def load_dbs(self):
return {"text": Text_DB(), "image": Image_DB()}
def load_index(self):
index = {"semantic": SemanticIndex(DB_PATH)}
return index
def load_models(self, model_names):
models = {}
for model_name in model_names:
if model_name in TEXT_EMBEDDING_MODELS:
print("Adding text embedding model")
models["text"] = SentenceTransformer(model_name)
elif model_name in IMAGE_EMBEDDING_MODELS:
print("Adding image embedding model")
models["image"] = SentenceTransformer(model_name)
else:
raise ValueError("Model name not supported.")
return models
def run(self):
while True:
input_text = input("Instruction: ")
if input_text == "exit":
self.close()
break
elif input_text == "insert":
path = input("File path: ")
self.insert(path)
elif input_text == "delete":
path = input("File path: ")
self.delete(path)
elif input_text == "search":
data_type = input("Search images or texts? Type 'image' or 'text': ")
input_text = input("Search text: ")
results = self.semantic_search(data_type, input_text)
print(results)
else:
print("Invalid instruction.")
def insert(self, path):
file_list = list_files(path)
for file in file_list:
file_path = file['path']
suffix = file['suffix']
data_type = file['type']
db = self.dbs[data_type]
if file_path not in db.get_existing_file_paths(data_type):
print("Processing file: ", file_path, suffix, self.models[data_type])
data_list = process_file(file_path, suffix, self.models[data_type])
db.insert_data(data_list, data_type)
def semantic_search(self, data_type, input_text):
if data_type == "text":
encode_func = encode_text
else:
encode_func = encode_image
query_embedding = encode_func(self.models[data_type], input_text)
results = self.index["semantic"].search_index(query_embedding, data_type)
return results
# data_idxs, distances = self.indices[data_type]["semantic"].search_index(query_embedding)
# column_names, results = self.dbs[data_type].retrieve_data(data_type, data_idxs)
# if data_type == "text":
# return self._process_text_results(distances, column_names, results)
# elif data_type == "image":
# return self._process_image_results(distances, column_names, results)
def _process_text_results(self, distances, column_names, raw_results):
dict_list = []
for distance, raw_result in zip(distances, raw_results):
d = {}
d['distance'] = distance
for column_name, result in zip(column_names, raw_result):
d[column_name] = result
dict_list.append(d)
combined_dict = {}
for d in dict_list:
file_path = d["file_path"]
if file_path not in combined_dict.keys():
combined_dict[file_path] = {
"min_distance": float("inf"),
"content": [],
"distance": [],
"page": [],
}
combined_dict[file_path]["min_distance"] = min(combined_dict[file_path]["min_distance"], d["distance"])
combined_dict[file_path]["content"].append(d["content"])
combined_dict[file_path]["page"].append(d["page"])
combined_dict[file_path]["distance"].append(d["distance"])
sorted_list = sorted(combined_dict.items(), key=lambda x: x[1]["min_distance"])
return sorted_list
def _process_image_results(self, distances, column_names, raw_results):
combined_dict = {}
for dist, raw_result in zip(distances, raw_results):
for d, column_name in zip(raw_result, column_names):
if column_name == "file_path":
combined_dict[d] = dist
sorted_list = sorted(combined_dict.items(), key=lambda x: x[1])
return sorted_list
def close(self):
for db in self.dbs.values():
db.close()
# for type_indices in self.indices.values():
# for index in type_indices.values():
# index.close()
if __name__ == "__main__":
Anything = Anything()
Anything.run()