-
Notifications
You must be signed in to change notification settings - Fork 0
/
EmbeddingDatabase.cpp
273 lines (231 loc) · 8.02 KB
/
EmbeddingDatabase.cpp
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/* MIT License
*
* Copyright (c) 2024 CURTLab, Fabian Hauser
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "EmbeddingDatabase.h"
EmbeddingDatabase::EmbeddingDatabase(QObject *parent)
: QObject(parent)
{
if (!createConnection()) {
return;
}
createTables();
}
void EmbeddingDatabase::addCollection(const QString &collection)
{
QSqlQuery query;
query.prepare("INSERT INTO collections (id, name, topic) VALUES (:id, :name, :topic)");
query.bindValue(":id", QUuid::createUuid().toString());
query.bindValue(":name", collection);
query.bindValue(":topic", collection);
if (!query.exec()) {
emit error("Error inserting collection: " + query.lastError().text());
}
}
bool EmbeddingDatabase::hasCollection(const QString &collection)
{
QSqlQuery query;
query.prepare("SELECT id FROM collections WHERE name = :name");
query.bindValue(":name", collection);
if (!query.exec()) {
emit error("Error selecting collection: " + query.lastError().text());
return false;
}
return query.next();
}
QStringList EmbeddingDatabase::collections()
{
QSqlQuery query;
query.prepare("SELECT name FROM collections");
if (!query.exec()) {
emit error("Error selecting collections: " + query.lastError().text());
return {};
}
QStringList collectionNames;
while (query.next()) {
collectionNames.append(query.value("name").toString());
}
return collectionNames;
}
QString EmbeddingDatabase::collectionByIndex(int index)
{
QSqlQuery query;
query.prepare("SELECT name FROM collections WHERE rowid = :index");
query.bindValue(":index", index + 1);
if (!query.exec()) {
emit error("Error selecting collection: " + query.lastError().text());
return {};
}
return query.next() ? query.value("name").toString() : "";
}
void EmbeddingDatabase::addDocument(const QString &id, const QString &topic, const QVector<double> &embedding)
{
QByteArray embeddingsData(reinterpret_cast<const char*>(embedding.data()), embedding.size() * sizeof(double));
// check if embedding already exists in the database
QSqlQuery checkQuery;
checkQuery.prepare("SELECT id FROM embeddings_queue WHERE id = :id OR vector = :vector");
checkQuery.bindValue(":id", id);
checkQuery.bindValue(":vector", embeddingsData);
if (checkQuery.exec() && checkQuery.next()) {
qDebug() << "Document already exists in the database";
return;
}
QSqlQuery query;
query.prepare("INSERT INTO embeddings_queue (operation, topic, id, vector) VALUES (:operation, :topic, :id, :vector)");
query.bindValue(":operation", 1);
query.bindValue(":topic", topic);
query.bindValue(":id", id);
query.bindValue(":vector", embeddingsData);
if (!query.exec()) {
emit error("Error inserting document: " + query.lastError().text());
}
}
bool EmbeddingDatabase::removeDocument(const QString &id)
{
QSqlQuery deleteQuery;
deleteQuery.prepare("DELETE FROM embeddings_queue WHERE id = :id");
deleteQuery.bindValue(":id", id);
if (!deleteQuery.exec()) {
emit error("Error deleting document: " + deleteQuery.lastError().text());
return false;
}
return true;
}
QVector<Document> EmbeddingDatabase::findDocuments(const QVector<double> &targetEmbedding, int topk)
{
QSqlQuery query;
query.prepare("SELECT id, vector FROM embeddings_queue WHERE operation = 1");
if (!query.exec()) {
emit error("Error selecting documents: " + query.lastError().text());
return {};
}
QVector<Document> closestDocuments;
while (query.next()) {
QString id = query.value("id").toString();
const QByteArray vectorData = query.value("vector").toByteArray();
if (vectorData.isEmpty()) {
qWarning() << "Empty embedding for document with id" << id << query.lastError().text();
continue;
}
QVector<double> embedding;
embedding.resize(vectorData.size() / sizeof(double));
std::memcpy(embedding.data(), vectorData.constData(), vectorData.size());
const double similarity = calculateSimilarity(targetEmbedding, embedding);
closestDocuments.append({id, "", -1, similarity});
}
// Sort documents by similarity and return the top k
std::sort(closestDocuments.begin(), closestDocuments.end(), [](const Document& a, const Document& b) {
return a.value > b.value;
});
closestDocuments = closestDocuments.mid(0, topk);
// Populate text and other metadata
for (Document& doc : closestDocuments) {
QSqlQuery metadataQuery;
metadataQuery.prepare("SELECT seq_id, topic FROM embeddings_queue WHERE id = :id");
metadataQuery.bindValue(":id", doc.id);
if (!metadataQuery.exec()) {
emit error("Error selecting metadata: " + metadataQuery.lastError().text());
continue;
}
if (metadataQuery.next()) {
doc.text = metadataQuery.value("topic").toString();
doc.index = metadataQuery.value("seq_id").toInt();
}
}
return closestDocuments;
}
std::optional<Document> EmbeddingDatabase::documentByIndex(int index)
{
QSqlQuery query;
query.prepare("SELECT id, topic FROM embeddings_queue WHERE seq_id = :index");
query.bindValue(":index", index);
if (!query.exec()) {
emit error("Error selecting document: " + query.lastError().text());
return {};
}
if (query.next()) {
Document doc;
doc.id = query.value("id").toString();
doc.text = query.value("topic").toString();
doc.index = index;
return doc;
}
return {};
}
double EmbeddingDatabase::calculateSimilarity(const QVector<double> &embedding1, const QVector<double> &embedding2)
{
// Calculate cosine similarity
// Dot product
double dotProduct = 0.0;
for (int i = 0; i < embedding1.size(); ++i) {
dotProduct += embedding1[i] * embedding2[i];
}
// Magnitudes
double magnitude1 = 0.0, magnitude2 = 0.0;
for (int i = 0; i < embedding1.size(); ++i) {
magnitude1 += embedding1[i] * embedding1[i];
magnitude2 += embedding2[i] * embedding2[i];
}
magnitude1 = std::sqrt(magnitude1);
magnitude2 = std::sqrt(magnitude2);
// Cosine similarity
return dotProduct / (magnitude1 * magnitude2);
}
bool EmbeddingDatabase::createConnection()
{
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName("embeddings.db");
if (!m_db.open()) {
emit error("Error opening database: " + m_db.lastError().text());
return false;
}
return true;
}
void EmbeddingDatabase::createTables()
{
// check if tables already exist
QSqlQuery checkQuery;
checkQuery.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name IN ('embeddings_queue', 'collections', 'collection_metadata')");
if (checkQuery.exec() && checkQuery.next()) {
return;
}
QSqlQuery query;
// Create embeddings_queue table
if (!query.exec("CREATE TABLE embeddings_queue ("
"seq_id INTEGER PRIMARY KEY, "
"created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"operation INTEGER NOT NULL, "
"topic TEXT NOT NULL, "
"id TEXT NOT NULL, "
"vector BLOB, "
"encoding TEXT, "
"metadata TEXT)")) {
emit error("Error creating embeddings_queue table: " + query.lastError().text());
}
// Create collections table
if (!query.exec("CREATE TABLE collections ("
"id TEXT PRIMARY KEY, "
"name TEXT NOT NULL, "
"topic TEXT NOT NULL, "
"UNIQUE (name))")) {
emit error("Error creating collections table: " + query.lastError().text());
}
}