File size: 3,748 Bytes
cdb5c98
 
e7ec62f
 
cdb5c98
 
 
 
e7ec62f
 
 
 
 
cdb5c98
 
 
 
e7ec62f
 
 
 
c2bd4e0
e7ec62f
 
 
 
c2bd4e0
 
 
 
e7ec62f
 
 
 
 
cdb5c98
e7ec62f
c2bd4e0
e7ec62f
 
 
 
 
 
 
cdb5c98
 
c2bd4e0
 
 
 
cdb5c98
 
 
 
 
e7ec62f
 
 
 
 
 
cdb5c98
 
 
c2bd4e0
e7ec62f
cdb5c98
 
 
 
 
 
 
 
 
 
 
 
e7ec62f
 
 
 
c2bd4e0
 
 
 
e7ec62f
 
 
 
 
 
 
 
 
cdb5c98
 
 
 
 
 
e7ec62f
 
 
 
 
cdb5c98
 
 
 
 
 
c2bd4e0
cdb5c98
 
e7ec62f
 
 
 
cdb5c98
e7ec62f
 
cdb5c98
 
c2bd4e0
cdb5c98
 
 
e7ec62f
 
 
 
c2bd4e0
 
 
 
e7ec62f
 
 
c2bd4e0
 
e7ec62f
 
 
c2bd4e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7ec62f
 
 
 
 
 
 
c2bd4e0
 
e7ec62f
 
 
 
 
 
 
 
 
 
 
 
c2bd4e0
 
 
 
e7ec62f
 
 
c2bd4e0
e7ec62f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import faiss
import numpy as np
import pickle
import os


class VectorStore:

    def __init__(
        self,
        index_path="data/vector.index",
        docs_path="data/documents.pkl"
    ):

        self.index = None
        self.documents = []

        self.index_path = index_path
        self.docs_path = docs_path


        # Load existing database
        self.load()



    # =====================================================
    # BUILD VECTOR DATABASE
    # =====================================================

    def build(
        self,
        embeddings,
        documents
    ):

        """
        Create FAISS vector database.

        embeddings:
            SentenceTransformer embeddings

        documents:
            text chunks
        """


        if len(embeddings) == 0:
            return


        embeddings = np.array(
            embeddings
        ).astype("float32")


        # Normalize for cosine similarity
        faiss.normalize_L2(
            embeddings
        )


        dimension = embeddings.shape[1]


        # Cosine similarity search
        self.index = faiss.IndexFlatIP(
            dimension
        )


        self.index.add(
            embeddings
        )


        self.documents = documents


        self.save()



    # =====================================================
    # SEARCH
    # =====================================================

    def search(
        self,
        query_embedding,
        k=5
    ):

        if self.index is None:
            return []


        query_embedding = np.array(
            [query_embedding]
        ).astype("float32")


        faiss.normalize_L2(
            query_embedding
        )


        distances, indices = self.index.search(
            query_embedding,
            k
        )


        results = []


        for score, idx in zip(
            distances[0],
            indices[0]
        ):


            if idx != -1:

                results.append(
                    self.documents[idx]
                )


        return results



    # =====================================================
    # SAVE DATABASE
    # =====================================================

    def save(self):

        """
        Save FAISS index + documents.
        Creates folders automatically.
        """


        # Create directories if missing

        index_dir = os.path.dirname(
            self.index_path
        )

        docs_dir = os.path.dirname(
            self.docs_path
        )


        if index_dir:

            os.makedirs(
                index_dir,
                exist_ok=True
            )


        if docs_dir:

            os.makedirs(
                docs_dir,
                exist_ok=True
            )


        # Save FAISS index

        if self.index is not None:

            faiss.write_index(
                self.index,
                self.index_path
            )


        # Save documents

        with open(
            self.docs_path,
            "wb"
        ) as f:

            pickle.dump(
                self.documents,
                f
            )



    # =====================================================
    # LOAD DATABASE
    # =====================================================

    def load(self):

        """
        Load FAISS database if available.
        """


        if os.path.exists(
            self.index_path
        ):

            self.index = faiss.read_index(
                self.index_path
            )


        if os.path.exists(
            self.docs_path
        ):

            with open(
                self.docs_path,
                "rb"
            ) as f:

                self.documents = pickle.load(f)