-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeduplicate.js
More file actions
172 lines (141 loc) · 4.86 KB
/
deduplicate.js
File metadata and controls
172 lines (141 loc) · 4.86 KB
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
const fs = require('fs').promises;
const OpenAI = require('openai');
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
function cosineSimilarity(vecA, vecB) {
let dotProduct = 0;
let normA = 0;
let normB = 0;
for (let i = 0; i < vecA.length; i++) {
dotProduct += vecA[i] * vecB[i];
normA += vecA[i] * vecA[i];
normB += vecB[i] * vecB[i];
}
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}
async function findDuplicatesWithEmbeddings() {
// Load your questions
const questions = JSON.parse(
await fs.readFile('extracted_questions.json', 'utf8')
);
console.log(`Processing ${questions.length} questions...`);
// Step 1: Generate embeddings in batches (API allows up to 2048 inputs per request)
const embeddings = [];
const batchSize = 100; // Conservative batch size
for (let i = 0; i < questions.length; i += batchSize) {
const batch = questions.slice(i, Math.min(i + batchSize, questions.length));
console.log(`Getting embeddings for questions ${i}-${i + batch.length}...`);
try {
const response = await openai.embeddings.create({
model: 'text-embedding-3-small', // Cheaper and faster, still very good
input: batch.map(q => q.question),
encoding_format: 'float' // Default, returns as array of numbers
});
embeddings.push(...response.data.map(d => d.embedding));
} catch (error) {
console.error(`Error in batch ${i}:`, error);
// Add retry logic here if needed
}
// Rate limiting
await new Promise(resolve => setTimeout(resolve, 200));
}
// Step 2: Calculate similarity matrix and group similar questions
const duplicateGroups = [];
const processed = new Set();
const SIMILARITY_THRESHOLD = 0.85; // Adjust based on your needs
for (let i = 0; i < questions.length; i++) {
if (processed.has(i)) continue;
const group = {
canonical: questions[i],
duplicates: [],
similarities: []
};
// Find all similar questions
for (let j = i + 1; j < questions.length; j++) {
if (processed.has(j)) continue;
const similarity = cosineSimilarity(embeddings[i], embeddings[j]);
if (similarity >= SIMILARITY_THRESHOLD) {
group.duplicates.push(questions[j]);
group.similarities.push({
question: questions[j],
similarity: similarity
});
processed.add(j);
}
}
// Only add groups that have duplicates
if (group.duplicates.length > 0) {
processed.add(i);
duplicateGroups.push(group);
}
}
// Step 3: Optional - Have GPT confirm edge cases (0.85-0.90 similarity)
const edgeCases = [];
for (const group of duplicateGroups) {
const uncertainDuplicates = group.similarities.filter(
s => s.similarity >= 0.85 && s.similarity < 0.90
);
if (uncertainDuplicates.length > 0) {
edgeCases.push({
canonical: group.canonical,
uncertain: uncertainDuplicates
});
}
}
// Verify edge cases with GPT
if (edgeCases.length > 0) {
console.log(`\nVerifying ${edgeCases.length} edge cases with GPT...`);
for (const edgeCase of edgeCases) {
const response = await openai.chat.completions.parse({
model: 'gpt-4o-mini',
messages: [{
role: 'user',
content: `Are these questions asking about the same thing?
Main question: "${edgeCase.canonical.question}"
Potential duplicates:
${edgeCase.uncertain.map((u, i) => `${i+1}. "${u.question.question}" (similarity: ${u.similarity.toFixed(3)})`).join('\n')}`
}],
response_format: {
type: 'json_schema',
json_schema: {
name: 'verification',
strict: true,
schema: {
type: 'object',
properties: {
confirmed_duplicates: {
type: 'array',
items: { type: 'integer' }
}
},
required: ['confirmed_duplicates']
}
}
}
});
// Update groups based on GPT confirmation
const confirmed = response.choices[0].message.parsed.confirmed_duplicates;
// ... handle the confirmed duplicates
}
}
// Step 4: Save results
const output = {
total_questions: questions.length,
duplicate_groups: duplicateGroups.length,
groups: duplicateGroups.map(g => ({
canonical: g.canonical,
duplicates: g.duplicates,
all_ids: [g.canonical.message_id, ...g.duplicates.map(d => d.message_id)]
}))
};
await fs.writeFile(
'deduplicated_questions.json',
JSON.stringify(output, null, 2)
);
console.log(`\nFound ${duplicateGroups.length} groups of duplicates`);
console.log(`Reduced ${questions.length} questions to ${questions.length - processed.size} unique questions`);
return output;
}
// Run it
findDuplicatesWithEmbeddings().catch(console.error);