-
Notifications
You must be signed in to change notification settings - Fork 0
/
hive.js
306 lines (270 loc) · 9.54 KB
/
hive.js
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
const fs = require("fs");
const path = require("path");
const reader = require("any-text");
/**
* The Hive class is a database management system that provides a simple and efficient way to store and retrieve data.
* It uses a file-based storage system and supports various operations such as creating collections, inserting data, and querying the database.
* The class also includes functionality for loading and saving the database to disk, as well as integrating with natural language processing models for feature extraction.
*/
function Hive(){ }
Hive.init = async function (dbName = "Documents", filePath, pathToDocs = false) {
Hive.dbName = dbName;
Hive.filePath = filePath || `./${Hive.dbName}/${Hive.dbName}.json`; // Default file path for saving/loading
Hive.collections = new Map();
Hive.createCollection(Hive.dbName);
Hive.TransOptions = { pooling: "mean", normalize: false };
Hive.loadToMemory(); // Load to memory automatically
await Hive.initTransformers();
if (pathToDocs && fs.existsSync(pathToDocs) && Hive.databaseExists()===false) {
await Hive.pullDocuments(pathToDocs);
}
}
Hive.databaseExists = function () {
if (fs.existsSync(Hive.filePath) && fs.statSync(Hive.filePath).size > 200) {
console.log(`Database exists ${Hive.filePath}`);
return true;
}else{
console.log(`Database does not exist ${Hive.filePath}`);
return false;
}
}
// Initialize transformers
Hive.initTransformers = async function (){
if(!Hive.pipeline){
const transformersModule = await import("@xenova/transformers");
Hive.pipeline = transformersModule.pipeline;
// Define getVector as a function that takes text input and uses the pipeline
Hive.getVector = await Hive.transInit();
}else{
console.log(`Transformers already initialized`);
}
}
Hive.transInit = async function (){
return await Hive.pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2");
}
// Create a collection
// Create a collection
Hive.createCollection = function () {
if (!Hive.collections.has(Hive.dbName)) {
Hive.collections.set(Hive.dbName, []);
// console.log(`Collection ${Hive.dbName} created in memory.`);
} else {
console.log(`Collection ${Hive.dbName} already exists.`);
}
};
// Insert one object into a specific collection
Hive.insertOne = function (entry) {
if (Hive.collections.has(Hive.dbName)) {
const { vector, meta } = entry;
const magnitude = Hive.normalize(vector);
Hive.collections.get(Hive.dbName).push({
vector,
magnitude, // Precompute and store the magnitude
meta,
});
}
};
// Insert many entries into a collection
Hive.insertMany = function (entries) {
if (Hive.collections.has(Hive.dbName)) {
const collection = Hive.collections.get(Hive.dbName);
for (let i = 0; i < entries.length; i++) {
const { vector, meta } = entries[i];
collection.push({
vector: vector,
meta,
magnitude: Hive.normalize(vector),
});
}
Hive.saveToDisk(); // Auto-save after bulk insertion
} else {
console.log(`Collection ${Hive.dbName} does not exist.`);
}
};
Hive.ensureDirectoryExists = function (filePath) {
const dir = path.dirname(filePath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
};
// Save the database to disk
Hive.saveToDisk = function () {
const data = {};
const collectionsKeys = Array.from(Hive.collections.keys());
for (let i = 0; i < collectionsKeys.length; i++) {
const key = collectionsKeys[i];
const value = Hive.collections.get(key);
data[key] = [];
for (let j = 0; j < value.length; j++) {
const entry = value[j];
data[key].push({
vector: Array.from(entry.vector), // Convert Float32Array back to Array for JSON
meta: entry.meta,
magnitude: entry.magnitude,
});
}
}
Hive.ensureDirectoryExists(Hive.filePath);
fs.writeFileSync(Hive.filePath, JSON.stringify(data), "utf8");
console.log(`Database saved to ${Hive.filePath}`);
};
// Load the database into memory from disk
Hive.loadToMemory = async function () {
if (fs.existsSync(Hive.filePath)) {
const rawData = fs.readFileSync(Hive.filePath, "utf8");
const data = JSON.parse(rawData);
Hive.collections.clear(); // Clear existing collections
for (const [dbName, entries] of Object.entries(data)) {
Hive.createCollection(dbName); // Recreate collections
const collection = Hive.collections.get(dbName);
console.log("Number of Entries", entries.length);
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
collection.push({
vector: new Float32Array(entry.vector),
meta: entry.meta,
magnitude: entry.magnitude,
});
}
}
console.log(`Database loaded into memory from ${Hive.filePath}`);
} else {
console.log(`File ${Hive.filePath} does not exist.`);
}
};
// Find vectors similar to the query vector
Hive.find = async function (queryVector, topK = 5) {
const queryVectorMag = Hive.normalize(queryVector);
const collection = Hive.collections.get(Hive.dbName) || [];
const results = [];
for (let i = 0; i < collection.length; i++) {
const item = collection[i];
const similarity = Hive.cosineSimilarity(queryVector, item.vector, queryVectorMag, item.magnitude);
results.push({ document: item, similarity });
}
results.sort((a, b) => b.similarity - a.similarity);
return results.slice(0, topK);
};
Hive.cosineSimilarity = function (queryVector, itemVector, queryVectorMag, itemVectorMag) {
let dotProduct = 0;
for (let i = 0; i < queryVector.length; i++) {
dotProduct += queryVector[i] * itemVector[i];
}
return dotProduct / (queryVectorMag * itemVectorMag);
};
Hive.normalize = function (vector) {
let sum = 0;
for (let i = 0; i < vector.length; i++) {
sum += vector[i] * vector[i];
}
return Math.sqrt(sum);
};
Hive.tokenCount = function (text) {
const tokens = text.match(/\b\w+\b/g) || [];
const tokensarr = [];
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (/\S/.test(token)) {
tokensarr.push(token);
}
}
return [tokensarr, tokensarr.length];
};
Hive.addItem = async function (text, filePath = "") {
try {
const vector = await Hive.getVector(text, Hive.TransOptions);
// Insert the item into the "Documents" collection
Hive.insertOne({
vector: Array.from(vector.data),
meta: {
content: Hive.escapeChars(text),
href:filePath,
title: Hive.escapeChars(text.slice(0, 20)),
},
});
} catch (error) {
console.error("Error adding item:", error);
}
};
// Read file and tokenize its content, splitting into slices for insertion
Hive.readFile = async function (filePath, dir) {
let text = await reader.getText(filePath); // Simulate reading file content
const [tokens, len] = Hive.tokenCount(text);
const sliceSize = 512;
let startIndex = 0;
while (startIndex < len) {
let endIndex = startIndex + sliceSize;
// Ensure we don't split a word
if (endIndex < len) {
while (endIndex > startIndex && tokens[endIndex] !== " ") {
endIndex--;
}
}
if (endIndex === startIndex) {
endIndex = Math.min(startIndex + sliceSize, len);
}
const slice = tokens.slice(startIndex, endIndex);
await Hive.addItem(slice.join(" "), filePath);
startIndex = endIndex + 1;
}
};
// Tokenize the text, cleaning it of non-alphanumeric characters
Hive.tokenize = function (text) {
const words = text.split(/\s+/);
let result = "";
for (let i = 0; i < words.length; i++) {
const word = words[i];
if (word.length > 0 && !word.match(/[^a-zA-Z0-9]/)) {
if (result.length > 0) {
result += " ";
}
result += word;
}
}
return result;
};
// Pull documents recursively from a directory and process them
Hive.pullDocuments = async function (dir) {
const files = await fs.promises.readdir(dir, { withFileTypes: true });
for (const file of files) {
const fullPath = path.join(dir, file.name);
if (file.isDirectory()) {
await Hive.pullDocuments(fullPath);
} else if (file.isFile() && [".txt", ".doc", ".docx", ".pdf"].includes(path.extname(file.name))) {
await Hive.readFile(fullPath, dir);
console.log(`Processed file: ${fullPath}`);
}
}
Hive.saveToDisk();
};
Hive.escapeChars = function (text) {
// Function to escape special characters and remove repeated single-letter characters
return (
text
// Escape special characters
.replace(/[&<>"'\\\/]/g, (match) => {
const escapeChars = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"\\": "\\\\",
"/": "\\/",
};
return escapeChars[match];
})
// Remove non-alphanumeric characters except spaces, letters, and digits
.replace(/[^A-Za-z0-9\s]/g, "")
// Collapse multiple spaces into one
.replace(/\s+/g, " ")
// Remove repeated single-letter words (e.g., R, A)
.replace(/\b([A-Za-z])\b(\s+\1)+/g, "")
// Remove any isolated single letters
.replace(/\b[A-Za-z]\b/g, "")
// Trim spaces at the beginning and end of the text
.trim()
);
};
// Hive.init();
module.exports = Hive;