-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.html
More file actions
449 lines (389 loc) · 15.6 KB
/
Copy pathindex.html
File metadata and controls
449 lines (389 loc) · 15.6 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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Polarized Words</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 16px;
}
.input-container {
margin-bottom: 20px;
display: flex;
gap: 8px;
flex-wrap: wrap;
}
#wordInput {
padding: 12px;
font-size: 16px;
flex: 1;
min-width: 200px;
border: 1px solid #ccc;
border-radius: 4px;
}
#addButton {
padding: 12px 24px;
font-size: 16px;
cursor: pointer;
border: none;
background: #4A4A4A;
color: white;
border-radius: 4px;
}
#clearButton {
padding: 12px 24px;
font-size: 16px;
cursor: pointer;
background: #ffffff;
color: black;
border-radius: 4px;
}
.axis-container {
position: relative;
min-height: 100px;
margin: 60px 20px 20px;
border-bottom: 2px solid #ccc;
}
.word-box {
position: absolute;
padding: 8px 16px;
border-radius: 4px;
background: #f0f0f0;
transform: translateX(-50%);
bottom: 20px;
font-size: 14px;
white-space: nowrap;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
#evil-box {
left: 0;
top:5px;
background: #ff9999;
}
#good-box {
right: 0;
top:5px;
transform: translateX(50%);
background: #99ff99;
}
@media (max-width: 480px) {
body {
padding: 12px;
}
.input-container {
flex-direction: column;
}
#wordInput {
width: 100%;
min-width: unset;
}
#addButton {
width: 100%;
}
.word-box {
padding: 6px 12px;
font-size: 13px;
}
}
</style>
</head>
<body>
<h1>
Polarized Words
</h1>
<p>
Enter 2 or more words to see their <span style="text-decoration: underline; font-weight: 700;">relative</span> distances to the concepts of "good" and "evil". This is based on language model embeddings which capture the semantics associated with the words in humanity's collective consciousness.
</p>
<p>
Source code / about this project: <a href="https://github.com/DefenderOfBasic/good-and-evil-concepts">github.com/DefenderOfBasic/good-and-evil-concepts</a>
</p>
<div id="status"></div>
<div id="content-container" style="display: none;">
<div class="input-container">
<input type="text" id="wordInput" placeholder="Enter a word">
<button id="addButton">Add Word</button>
<button id="clearButton">Clear all</button>
</div>
<div class="axis-container" id="axis">
<div class="word-box" id="evil-box">Evil</div>
<div class="word-box" id="good-box">Good</div>
</div>
</div>
<h2>⚙️ Settings</h2>
<label>North pole</label>
<input id="north-pole" value="good"></input>
<label>South pole</label>
<input id="south-pole" value="evil"></input>
<br/><br/>
<label>
Embedding model:
</label>
<input id="model" value="nomic-ai/nomic-embed-text-v1.5" style="width: 400px;"></input>
<br/>
<label>
OpenAI key:
</label>
<input id="openai-key" value="" style="width: 400px;"></input>
<br/>
<label>
Voyage API key:
</label>
<input id="voyage-key" value="" style="width: 400px;"></input>
<br/>
<label>
Google API key:
</label>
<input id="google-key" value="" style="width: 400px;"></input>
<br/>
<p style="color:gray">
(from <a style="color: gray;" href="https://huggingface.co/models?other=feature-extraction">Hugging Face</a>, must support ONNX. Refresh page to reload model)
</p>
<button id="reset">
Reset settings
</button>
<script type="module">
const modelInput = document.querySelector("#model")
const openaiKey = document.querySelector("#openai-key")
const voyageAIKey = document.querySelector("#voyage-key")
const googleKey = document.querySelector("#google-key")
const northPoleInput = document.querySelector("#north-pole")
const southPoleInput = document.querySelector("#south-pole")
modelInput.oninput = () => {
localStorage.setItem("model", modelInput.value)
}
openaiKey.oninput = () => {
localStorage.setItem("openai-key", openaiKey.value)
}
voyageAIKey.oninput = () => {
localStorage.setItem("voyage-key", voyageAIKey.value)
}
googleKey.oninput = () => {
localStorage.setItem("google-key", googleKey.value)
}
import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.3.2';
// Since we will download the model from the Hugging Face Hub, we can skip the local model check
env.allowLocalModels = false;
// Reference the elements that we will need
const status = document.getElementById('status');
// Create a new object detection pipeline
status.textContent = 'Loading model...';
if (localStorage.getItem('words') == null) {
localStorage.setItem('words', JSON.stringify([]))
}
if (localStorage.getItem('model')) {
modelInput.value = localStorage.getItem('model')
}
if (localStorage.getItem('north')) northPoleInput.value = localStorage.getItem('north')
if (localStorage.getItem('south')) southPoleInput.value = localStorage.getItem('south')
if (localStorage.getItem('openai-key')) openaiKey.value = localStorage.getItem('openai-key')
if (localStorage.getItem('voyage-key')) voyageAIKey.value = localStorage.getItem('voyage-key')
if (localStorage.getItem('google-key')) googleKey.value = localStorage.getItem('google-key')
const model_name = modelInput.value
let embedder = null
if (openaiKey.value == "" && googleKey.value == "") {
embedder = await pipeline('feature-extraction', model_name,
{
quantized: true,
progress_callback: data => {
const { progress, loaded, total } = data
if (progress) {
const totalMB = Math.round(total / (1024 * 1024))
const loadedMB = Math.round(loaded / (1024 * 1024))
status.textContent = `${Math.round(progress)}% (${loadedMB}/${totalMB} mb)`;
}
}
});
}
let southPole = southPoleInput.value
let northPole = northPoleInput.value
document.querySelector("#evil-box").innerHTML = southPole
document.querySelector("#good-box").innerHTML = northPole
status.textContent = 'Embedding poles';
async function embedWord(word) {
const openaiKey = document.querySelector("#openai-key").value
const voyageKey = document.querySelector("#voyage-key").value
const googleKey = document.querySelector("#google-key").value
if (openaiKey == "" && voyageKey == "" && googleKey == "") {
return (await embedder(word, {pooling: 'mean', normalize: true})).data
}
if (googleKey != "") {
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent?key=${googleKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'content': {
'parts': [{
'text': word
}]
},
'task_type': 'SEMANTIC_SIMILARITY'
})
});
const data = await response.json();
return data.embedding.values;
}
if (voyageKey != "") {
const response = await fetch('https://api.voyageai.com/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + voyageKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({
'input': word,
'model': 'voyage-3-large',
'input_type': 'document'
})
});
const data = await response.json();
console.log(data)
return data.data[0].embedding;
}
if (openaiKey != "") {
const response = await fetch('https://api.openai.com/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + openaiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({
'input': word,
'model': 'text-embedding-3-large',
'encoding_format': 'float'
})
});
const data = await response.json();
return data.data[0].embedding;
}
}
let southVector = await embedWord(southPole)
let northVector = await embedWord(northPole)
northPoleInput.onchange = () => {
updatePoles()
}
southPoleInput.onchange = () => {
updatePoles()
}
async function updatePoles() {
southPole = southPoleInput.value
northPole = northPoleInput.value
document.querySelector("#evil-box").innerHTML = southPole
document.querySelector("#good-box").innerHTML = northPole
localStorage.setItem("north", northPoleInput.value)
localStorage.setItem("south", southPoleInput.value)
southVector = await embedWord(southPole)
northVector = await embedWord(northPole)
reComputeAllWords()
}
status.textContent = 'Ready';
status.style.display = 'none'
document.querySelector("#content-container").style.display = 'block'
const wordInput = document.getElementById('wordInput');
const addButton = document.getElementById('addButton');
const axis = document.getElementById('axis');
let wordsComputed = []
async function reComputeAllWords() {
clearAllWords()
const oldWords = wordsComputed.map(item => item.word)
wordsComputed = []
for (let oldWord of oldWords) {
await addWord(oldWord)
}
}
async function addWord(overrideWord = null) {
let word = wordInput.value.trim();
if (overrideWord) word = overrideWord
if (word) {
wordInput.value = '';
wordInput.focus();
const embeddingVector = await embedWord(word)
const southDistance = cosineSimilarity(embeddingVector, southVector)
const northDistance = cosineSimilarity(embeddingVector, northVector)
wordsComputed.push({ word, southDistance, northDistance })
localStorage.setItem('words',
JSON.stringify(wordsComputed.map(item => item.word))
)
}
// Add all words
clearAllWords()
const positions = wordsComputed.map(d => d.northDistance / (d.southDistance + d.northDistance));
const minPos = Math.min(...positions);
const maxPos = Math.max(...positions);
for (let { word, southDistance, northDistance } of wordsComputed) {
const rawPosition = (northDistance / (southDistance + northDistance))
const normalizedPosition = ((rawPosition - minPos) / (maxPos - minPos) * 100);
const wordElement = document.createElement('div');
wordElement.className = 'word-box';
wordElement.textContent = word;
wordElement.style.left = `${normalizedPosition}%`;
axis.appendChild(wordElement);
wordElement.onclick = (e) => {
wordsComputed = wordsComputed.filter(item => item.word !== e.target.textContent);
e.target.parentNode.removeChild(e.target);
addWord()
}
}
}
function clearAllWords() {
axis.replaceChildren(document.getElementById('evil-box'), document.getElementById('good-box'));
}
document.querySelector("#clearButton").onclick = () => {
clearAllWords()
wordsComputed = []
}
addButton.addEventListener('click', () => {
addWord()
});
wordInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
addWord();
}
});
/// Helpers
document.querySelector("#reset").onclick = () => {
modelInput.value = "nomic-ai/nomic-embed-text-v1.5"
northPoleInput.value = "good"
southPoleInput.value = "evil"
modelInput.dispatchEvent(new Event('input', { bubbles: true }));
northPoleInput.dispatchEvent(new Event('change', { bubbles: true }));
southPoleInput.dispatchEvent(new Event('change', { bubbles: true }));
}
// Calculate dot product of two vectors
const dotProduct = (vecA, vecB) => {
if (vecA.length !== vecB.length) {
throw new Error('Vectors must have the same length');
}
return vecA.reduce((sum, a, i) => sum + a * vecB[i], 0);
};
// Calculate magnitude (length) of a vector
const magnitude = (vec) => {
return Math.sqrt(vec.reduce((sum, val) => sum + val * val, 0));
};
// Calculate cosine similarity between two vectors
const cosineSimilarity = (vecA, vecB) => {
if (vecA.length !== vecB.length) {
throw new Error('Vectors must have the same length');
}
const dot = dotProduct(vecA, vecB);
const magA = magnitude(vecA);
const magB = magnitude(vecB);
if (magA === 0 || magB === 0) {
throw new Error('Cannot calculate cosine similarity for zero vector');
}
return dot / (magA * magB);
};
// preload saved words
if (localStorage.getItem('words')) {
const array = JSON.parse(localStorage.getItem('words'))
for (let word of array) {
await addWord(word)
}
}
</script>
</body>
</html>