-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun-demo.js
343 lines (287 loc) · 14 KB
/
run-demo.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// -------------
// -- imports --
// -------------
import { prefixConfig, generateEmbeddings } from "./modules/embedding.js";
import { cosineSimilarity } from "./modules/similarity.js";
import { parseSentences } from 'sentence-parse';
import fs from 'fs';
import readline from 'readline';
import chalk from 'chalk';
import path from 'path';
// Create readline interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Parse command line arguments
const args = parseCommandLineArgs();
// Load or create config
let config = { lastTestMessage: 1, verboseLogs: true, showMatches: true };
const configPath = './run-demo-config.json';
try {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
} catch {
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
}
// Apply command line arguments to config
if (args.verbose !== undefined) config.verboseLogs = true;
if (args.quiet !== undefined) config.verboseLogs = false;
if (args.showMatches !== undefined) config.showMatches = true;
if (args.hideMatches !== undefined) config.showMatches = false;
// Load topic embeddings from `data/topic_embeddings` folder
const topicEmbeddingsDir = 'data/topic_embeddings';
const topicEmbeddingFiles = fs.readdirSync(topicEmbeddingsDir).filter(file => file.endsWith('.json'));
// Group embeddings by topic
const topicEmbeddings = {};
topicEmbeddingFiles.forEach(file => {
const filePath = path.join(topicEmbeddingsDir, file);
const embeddingData = JSON.parse(fs.readFileSync(filePath, 'utf8'));
const topicName = embeddingData.topic;
if (!topicEmbeddings[topicName]) {
topicEmbeddings[topicName] = [];
}
topicEmbeddings[topicName].push({
clusterIndex: embeddingData.clusterIndex,
totalClusters: embeddingData.totalClusters,
clusterSize: embeddingData.clusterSize,
clusterCoverage: embeddingData.clusterCoverage,
cohesion: embeddingData.cohesion || "N/A",
threshold: embeddingData.threshold,
embedding: embeddingData.embedding
});
});
// Log topic embedding information
console.log(chalk.blue('\nLoaded topic embeddings:'));
Object.keys(topicEmbeddings).forEach(topicName => {
console.log(chalk.green(` - ${topicName}: ${topicEmbeddings[topicName].length} clusters`));
});
// Load test message files
const testMessageFiles = fs.readdirSync('test-messages')
.sort((a, b) => {
const numA = parseInt(a.match(/\d+/)[0]);
const numB = parseInt(b.match(/\d+/)[0]);
return numA - numB;
});
// Initialize sentence matches variable
let sentenceMatches = [];
// Initialize total comparisons variable
let totalComparisons = 0;
// Initialize total sentences variable
let totalSentences = 0;
// -------------------------------------------
// -- Test similarity for each test message --
// -------------------------------------------
async function testSimilarity(testMessage) {
console.log(chalk.blue('\n-----------------------------------------------------\n'));
const sentences = await parseSentences(testMessage);
totalSentences += sentences.length;
let sentencesWithEmbeddings = await generateEmbeddings(sentences, {
prefix: prefixConfig.queryPrefix,
returnPhrases: true,
logging: false,
});
for (const { phrase, embedding } of sentencesWithEmbeddings) {
let matchFound = false;
let bestMatch = { topicName: null, similarity: 0, clusterIndex: null };
if (config.verboseLogs) {
console.log(`\nSentence: ${phrase}`);
}
// Compare with all topic embeddings
for (const topicName in topicEmbeddings) {
const topicClusters = topicEmbeddings[topicName];
const threshold = topicClusters[0].threshold; // All clusters for a topic have the same threshold
// Compare with each cluster for this topic
for (const cluster of topicClusters) {
totalComparisons++;
const similarity = cosineSimilarity(embedding, cluster.embedding);
// Track best match across all topics and clusters
if (similarity > bestMatch.similarity) {
bestMatch = {
topicName,
similarity,
clusterIndex: cluster.clusterIndex,
totalClusters: cluster.totalClusters,
cohesion: cluster.cohesion,
threshold
};
}
if (similarity >= threshold) {
matchFound = true;
// Clean phrase by removing prefixConfig.queryPrefix from phrase
const cleanedPhrase = (phrase.startsWith(prefixConfig.queryPrefix) && prefixConfig.queryPrefix !== '')
? phrase.slice(prefixConfig.queryPrefix.length)
: phrase;
sentenceMatches.push({
topicName,
cleanedPhrase,
clusterIndex: cluster.clusterIndex,
totalClusters: cluster.totalClusters,
cohesion: cluster.cohesion
});
if (config.verboseLogs) {
console.log(chalk.red(`Topic: ${topicName} (Cluster ${cluster.clusterIndex + 1}/${cluster.totalClusters}, Cohesion: ${cluster.cohesion}) ⇢ Similarity Score: ${similarity.toFixed(4)}`));
} else if(!config.verboseLogs && config.showMatches) {
console.log(chalk.red(`Topic: ${topicName} (Cluster ${cluster.clusterIndex + 1}/${cluster.totalClusters}, Cohesion: ${cluster.cohesion}) ⇢ Similarity Score: ${similarity.toFixed(4)} ⇠ ${cleanedPhrase}`));
}
// We found a match for this topic, no need to check other clusters
break;
} else if (config.verboseLogs) {
console.log(chalk.green(`Topic: ${topicName} (Cluster ${cluster.clusterIndex + 1}/${cluster.totalClusters}, Cohesion: ${cluster.cohesion}) ⇢ Similarity Score: ${similarity.toFixed(4)}`));
}
}
}
// If no match was found but we want to show the best match anyway
if (!matchFound && config.verboseLogs && bestMatch.topicName) {
console.log(chalk.yellow(`Best match (below threshold): ${bestMatch.topicName} (Cluster ${bestMatch.clusterIndex + 1}/${bestMatch.totalClusters}, Cohesion: ${bestMatch.cohesion}) ⇢ Score: ${bestMatch.similarity.toFixed(4)} (Threshold: ${bestMatch.threshold})`));
}
}
}
// ------------------------------
// -- Prompt user and run test --
// ------------------------------
const [yOption, nOption] = config.verboseLogs ? ['Y', 'n'] : ['y', 'N'];
rl.question(`\nDisplay verbose logs? (${yOption}/${nOption}): `, async (answer) => {
const verboseAnswer = answer.trim().toLowerCase();
if (verboseAnswer === 'y') {
config.verboseLogs = true;
} else if (verboseAnswer === 'n') {
config.verboseLogs = false;
}
const [showOption, hideOption] = config.showMatches ? ['Y', 'n'] : ['y', 'N'];
rl.question(`Show matched sentences? (${showOption}/${hideOption}): `, async (answer) => {
const showAnswer = answer.trim().toLowerCase();
if (showAnswer === 'y') {
config.showMatches = true;
} else if (showAnswer === 'n') {
config.showMatches = false;
}
// Save config
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
// Determine which test message to use
let testMessagePath;
if (args.file) {
if (isNaN(args.file)) {
// If it's not a number, treat it as a filename
testMessagePath = args.file;
if (!fs.existsSync(testMessagePath)) {
testMessagePath = `test-messages/${args.file}`;
}
} else {
// If it's a number, treat it as an index
const messageIndex = parseInt(args.file);
if (messageIndex > 0 && messageIndex <= testMessageFiles.length) {
testMessagePath = `test-messages/${testMessageFiles[messageIndex - 1]}`;
config.lastTestMessage = messageIndex;
} else {
console.log(chalk.red(`Invalid test message number. Please choose between 1 and ${testMessageFiles.length}.`));
rl.close();
return;
}
}
} else {
rl.question(`Which test message? (1-${testMessageFiles.length}) [${config.lastTestMessage}]: `, async (answer) => {
let messageIndex = config.lastTestMessage;
if (answer.trim() !== '') {
messageIndex = parseInt(answer.trim());
if (isNaN(messageIndex) || messageIndex < 1 || messageIndex > testMessageFiles.length) {
console.log(chalk.red(`Invalid test message number. Using default: ${config.lastTestMessage}`));
messageIndex = config.lastTestMessage;
}
}
config.lastTestMessage = messageIndex;
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
const testMessagePath = `test-messages/${testMessageFiles[messageIndex - 1]}`;
const testMessage = fs.readFileSync(testMessagePath, 'utf8');
console.log(chalk.blue(`\nAnalyzing test message ${messageIndex}: ${testMessageFiles[messageIndex - 1]}`));
const startTime = Date.now();
await testSimilarity(testMessage);
const endTime = Date.now();
// Print summary
console.log(chalk.blue('\n-----------------------------------------------------\n'));
console.log(chalk.yellow(`Analysis completed in ${(endTime - startTime) / 1000} seconds`));
console.log(chalk.yellow(`Total sentences analyzed: ${totalSentences}`));
console.log(chalk.yellow(`Total comparisons performed: ${totalComparisons}`));
console.log(chalk.yellow(`Total matches found: ${sentenceMatches.length}`));
if (sentenceMatches.length > 0 && config.showMatches) {
console.log(chalk.blue('\nMatched Sentences:'));
sentenceMatches.forEach(match => {
console.log(chalk.green(` - ${match.topicName} (Cluster ${match.clusterIndex + 1}/${match.totalClusters}, Cohesion: ${match.cohesion}): ${match.cleanedPhrase}`));
});
}
rl.close();
});
return;
}
// If we have a direct file path, process it
if (testMessagePath) {
if (!fs.existsSync(testMessagePath)) {
console.log(chalk.red(`Test message file not found: ${testMessagePath}`));
rl.close();
return;
}
const testMessage = fs.readFileSync(testMessagePath, 'utf8');
console.log(chalk.blue(`\nAnalyzing test message: ${path.basename(testMessagePath)}`));
const startTime = Date.now();
await testSimilarity(testMessage);
const endTime = Date.now();
// Print summary
console.log(chalk.blue('\n-----------------------------------------------------\n'));
console.log(chalk.yellow(`Analysis completed in ${(endTime - startTime) / 1000} seconds`));
console.log(chalk.yellow(`Total sentences analyzed: ${totalSentences}`));
console.log(chalk.yellow(`Total comparisons performed: ${totalComparisons}`));
console.log(chalk.yellow(`Total matches found: ${sentenceMatches.length}`));
if (sentenceMatches.length > 0 && config.showMatches) {
console.log(chalk.blue('\nMatched Sentences:'));
sentenceMatches.forEach(match => {
console.log(chalk.green(` - ${match.topicName} (Cluster ${match.clusterIndex + 1}/${match.totalClusters}, Cohesion: ${match.cohesion}): ${match.cleanedPhrase}`));
});
}
rl.close();
}
});
});
// ----------------------------------
// -- Parse command line arguments --
// ----------------------------------
function parseCommandLineArgs() {
const args = {};
const argv = process.argv.slice(2);
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--verbose' || arg === '-v') {
args.verbose = true;
} else if (arg === '--quiet' || arg === '-q') {
args.quiet = true;
} else if (arg === '--show-matches' || arg === '-s') {
args.showMatches = true;
} else if (arg === '--hide-matches' || arg === '-h') {
args.hideMatches = true;
} else if (arg === '--help') {
printHelp();
process.exit(0);
} else if (!arg.startsWith('-')) {
args.file = arg;
}
}
return args;
}
// -----------------------
// -- Print help message --
// -----------------------
function printHelp() {
console.log(`
Usage: node run-demo.js [options] [file]
Options:
--verbose, -v Enable verbose logging
--quiet, -q Disable verbose logging
--show-matches, -s Show matched sentences
--hide-matches, -h Hide matched sentences
--help Show this help message
Arguments:
file Test message file to analyze (number or filename)
Examples:
node run-demo.js 2
node run-demo.js message-1.txt
node run-demo.js --quiet --show-matches
`);
}