-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisualize.html
600 lines (528 loc) · 20.2 KB
/
visualize.html
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
<!DOCTYPE html>
<html>
<head>
<title>Alignment Visualizer</title>
<style>
body {
font-family: sans-serif;
font-size: 20px;
margin: 0.5em;
}
body.dark {
background: #111;
color: #fff;
color-scheme: dark;
}
#form {
margin: 0 0 2em;
padding: 0;
border: none;
text-wrap: nowrap;
}
label, select, button, #form fieldset {
display: inline-block;
margin: 0.5em;
}
label select {
margin: 0;
}
#form fieldset {
padding: 0 0.5em 0.33em;
}
legend {
font-size: 0.75em;
opacity: 0.9;
}
input:not([type]) {
width: 500px;
}
input[type="number"] {
width: 55px;
}
input, select, button {
font-size: inherit;
}
#swapButton {
position: relative;
top: 1.25em;
margin-left: 0;
}
svg {
cursor: default;
}
#output:not(.loading) svg {
/* Firefox does not calculate the bounding box of tspan's correctly when the svg is scaled. */
width: 100%;
height: auto;
max-height: 50vh;
}
.loading {
opacity: 0;
}
#download {
display: inline-block;
margin-top: 2em;
}
label:has([name="wspSymmetricMode"]) {
label:has(#wspSymmetricCheckbox:not(:checked)) ~ & {
display: none;
}
& + & {
margin-left: 0;
}
}
</style>
</head>
<body>
<fieldset id="form">
<div>
<label>From text: <input id="fromTextInput" value="瑞鳳です。軽空母ですが、練度が上がれば、正規空母並の活躍をお見せできます。" /></label>
<button id="swapButton">⤪</button>
</div>
<div><label>To text: <input id="toTextInput" value="I'm Zuihou. Even though I'm a light carrier, I can show you that I'll be as good as standard carriers with some experience." /></label></div>
<div>
<fieldset>
<legend>WSP</legend>
<label>Threshold: <input id="wspThresholdInput" type="number" value="0.1" min="0" max="1" step="0.1" /></label>
<label><input id="wspSymmetricCheckbox" type="checkbox" /> <abbr title="Combines the results of reverse alignment.">Symmetric</abbr></label>
<label><input name="wspSymmetricMode" type="radio" value="AND" checked /> AND</label>
<label><input name="wspSymmetricMode" type="radio" value="OR" /> OR</label>
<button id="alignWspButton">Align</button>
</fieldset>
<fieldset>
<legend>Awesome</legend>
<label>
Model:
<select id="awesomeModelDropdown">
<option value="bert-base-multilingual-cased">bert base</option>
<option value="./models/model_with_co">model w/ co</option>
<option value="./models/model_without_co" selected>model w/o co</option>
</select>
</label>
<button id="alignAwesomeButton">Align</button>
</fieldset>
</div>
<div>
<label>Alignment result: <input id="alignmentResultInput" value="0,2,4,10,2,4,0,3,4,5,10,11,5,6,30,35,6,8,36,43,8,10,25,27,10,11,12,23,11,12,43,44,15,18,73,80,18,19,70,72,20,22,84,92,22,24,93,101,25,26,73,83,26,28,112,122,29,30,102,106,30,32,51,59,32,36,47,50,36,37,122,123" /></label>
<label><input id="darkMode" type="checkbox" checked /> Dark mode</label>
<select id="paletteDropdown">
<option value="material" selected>Material</option>
<option value="one">One Light/Dark</option>
</select>
</div>
</fieldset>
<div id="output"></div>
<a id="download" href="#" hidden>Download SVG</a>
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<script>
const EM = 30;
const TEXT_SPACING = 7 * EM;
const LINE_SPACING = 0.33 * EM;
// Offsets where the lines *appear* to start/end (or actually do, if
// LINE_SPACING is set to 0) to bring it closer to the actual text.
const LINE_ORIGIN_OFFSET = 0.3 * EM;
const FROM_TEXT_ID = 'fromText';
const TO_TEXT_ID = 'toText';
const form = document.getElementById('form');
const fromTextInput = document.getElementById('fromTextInput');
const toTextInput = document.getElementById('toTextInput');
const alignmentResultInput = document.getElementById('alignmentResultInput');
const darkMode = document.getElementById('darkMode');
const paletteDropdown = document.getElementById('paletteDropdown');
const outputEl = document.getElementById('output');
const dlLink = document.getElementById('download');
const alignWspButton = document.getElementById('alignWspButton');
const alignAwesomeButton = document.getElementById('alignAwesomeButton');
const awesomeModelDropdown = document.getElementById('awesomeModelDropdown');
const wspThresholdInput = document.getElementById('wspThresholdInput');
const wspSymmetricCheckbox = document.getElementById('wspSymmetricCheckbox');
const wspSymmetricModes = Array.from(document.getElementsByName('wspSymmetricMode'));
const swapButton = document.getElementById('swapButton');
let updatingHash = false;
const fontsPromise = new Promise(resolve => {
WebFont.load({
google: {
families: ['Noto Sans JP']
},
timeout: 10000,
active: resolve,
inactive: resolve
});
});
window.addEventListener('hashchange', loadFromHash);
loadFromHash(/* shouldRender = */ false);
fromTextInput.addEventListener('input', render);
toTextInput.addEventListener('input', render);
alignmentResultInput.addEventListener('input', render);
darkMode.addEventListener('change', render);
paletteDropdown.addEventListener('change', render);
render(/* shouldUpdateHash = */ false);
dlLink.addEventListener('click', () => {
const svg = document.querySelector('#output svg');
const blob = new Blob([createDownloadableSvg(svg)], { type: 'text/svg' });
dlLink.href = URL.createObjectURL(blob);
});
alignWspButton.addEventListener('click', () => align('wsp'));
alignAwesomeButton.addEventListener('click', () => align('awesome'));
swapButton.addEventListener('click', () => {
const fromText = fromTextInput.value;
fromTextInput.value = toTextInput.value;
toTextInput.value = fromText;
if (alignmentResultInput.value) {
const alignmentResult = parseAlignmentResult(alignmentResultInput.value);
let reversedNums = [];
for (const alignment of alignmentResult) {
reversedNums.push(alignment.toStart, alignment.toEnd, alignment.fromStart, alignment.fromEnd);
}
alignmentResultInput.value = reversedNums.join(',');
render();
}
});
form.addEventListener('submit', e => e.preventDefault());
function updateHash() {
const params = new URLSearchParams({
from: fromTextInput.value,
to: toTextInput.value,
result: alignmentResultInput.value,
wspThreshold: wspThresholdInput.value,
wspSymmetric: wspSymmetricCheckbox.checked,
wspSymmetricMode: wspSymmetricModes.find(el => el.checked).value,
awesomeModel: awesomeModelDropdown.value,
dark: darkMode.checked,
palette: paletteDropdown.value,
});
updatingHash = true;
console.log('Updating hash:', Object.fromEntries(params.entries()));
document.location.hash = '#' + params.toString();
}
function loadFromHash(shouldRender = true) {
const hash = document.location.hash.substr(1);
if (!hash || updatingHash) {
updatingHash = false;
return;
}
const params = new URLSearchParams(hash);
console.log('Loading from hash:', Object.fromEntries(params.entries()));
fromTextInput.value = params.get('from');
toTextInput.value = params.get('to');
alignmentResultInput.value = params.get('result');
wspThresholdInput.value = params.get('wspThreshold');
wspSymmetricCheckbox.checked = params.get('wspSymmetric') == 'true';
wspSymmetricModes.forEach(el => el.checked = el.value == params.get('wspSymmetricMode'));
awesomeModelDropdown.value = params.get('awesomeModel');
darkMode.checked = params.get('dark') == 'true';
paletteDropdown.value = params.get('palette');
if (shouldRender) {
render(/* shouldUpdateHash = */ false);
}
}
async function align(method) {
form.disabled = true;
alignmentResultInput.value = 'IMA FIRIN MAH LAZER!!!';
try {
const res = await fetch('/align', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
cache: 'no-cache',
body: JSON.stringify({
method,
fromLanguage: isJapanese(fromTextInput.value) ? 'ja' : 'en',
fromText: fromTextInput.value,
toLanguage: isJapanese(toTextInput.value) ? 'ja' : 'en',
toText: toTextInput.value,
awesomeModel: awesomeModelDropdown.value,
wspThreshold: wspThresholdInput.value,
wspSymmetric: wspSymmetricCheckbox.checked,
wspSymmetricMode: wspSymmetricModes.find(el => el.checked).value,
})
});
const json = await res.json();
alignmentResultInput.value = json.result;
form.disabled = false;
render();
} catch (e) {
console.error(e);
alignmentResultInput.value = 'ERROR';
form.disabled = false;
}
}
async function render(shouldUpdateHash = true) {
if (shouldUpdateHash) {
updateHash();
}
document.body.classList.toggle('dark', darkMode.checked);
const fromText = fromTextInput.value;
const toText = toTextInput.value;
let alignmentResult = parseAlignmentResult(alignmentResultInput.value);
alignmentResult = removePunctuationAlignments(alignmentResult, fromText, toText);
console.log('fromText =', fromText);
console.log('toText =', toText);
console.log('alignmentResult =', alignmentResult);
outputEl.innerHTML = '';
outputEl.classList.add('loading');
if (!fromText || !toText || !alignmentResult.length) {
return;
}
const palette = createPalette(paletteDropdown.value, darkMode.checked);
const svg = createSvgElement('svg');
svg.setAttribute('version', '1.1');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svg.setAttribute('viewBox', '0 0 10000 5000'); // For some reason Chrome doesn't calculate off-screen text's bbox correctly.
outputEl.appendChild(svg);
const style = createSvgElement('style');
const selectors = [];
style.innerHTML = `@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+JP&display=swap');
text {
font-family: 'Noto Sans JP', sans-serif;
font-size: ${EM}px;${darkMode.checked ? `
fill: #fff;` : ''}
}`;
svg.appendChild(style);
const fromTextEl = createTextElement(fromText, FROM_TEXT_ID, { x: 0, y: 0 });
const toTextEl = createTextElement(toText, TO_TEXT_ID, { x: 0, y: TEXT_SPACING });
svg.appendChild(fromTextEl);
svg.appendChild(toTextEl);
console.log('Waiting for fonts');
await fontsPromise;
setViewBox(svg);
setTimeout(() => setViewBox(svg), 10); // Hack
setTimeout(() => setViewBox(svg), 100); // Hack
setTimeout(() => setViewBox(svg), 1000); // Hackity hack
centerHorizontally(fromTextEl, toTextEl);
for (let i = 0; i < alignmentResult.length; i++) {
const { fromStart, fromEnd, toStart, toEnd } = alignmentResult[i];
const name = `a${i}`;
console.log(`Drawing alignment for ${fromText.substring(fromStart, fromEnd)} (${fromStart}) => ${toText.substring(toStart, toEnd)} (${toStart})`);
drawAlignment(svg, fromStart, fromEnd, toStart, toEnd, palette[i % palette.length], name);
selectors.push(`svg:has(.${name}:hover) .${name}`);
}
style.innerHTML += `
svg:has([class]:is(tspan, rect):hover) :is(tspan, rect, line):not(${selectors.join(', ')}) {
fill-opacity: 0.33;
stroke-opacity: 0.33;
}`;
outputEl.classList.remove('loading');
let filename = isJapanese(fromText) ? toText : fromText;
filename = filename.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
filename = filename.substr(0, 40).replace(/-[^-]*$/, '');
filename = `alignment_${filename}_${darkMode.checked ? 'dark' : 'light'}.svg`;
dlLink.setAttribute('download', filename);
dlLink.setAttribute('title', filename);
dlLink.removeAttribute('hidden');
}
/** @returns {SVGElement} */
function createSvgElement(tagName) {
return document.createElementNS('http://www.w3.org/2000/svg', tagName);
}
function parseAlignmentResult(alignmentResultStr) {
let numbers = [];
if (alignmentResultStr.includes(',')) {
numbers = alignmentResultStr.split(',').map(x => parseInt(x));
} else {
// Supports a separate project
console.log('Alignment result is not an array. Trying to decode base64-encoded ushort[]...');
try {
const bytes = Uint8Array.from(atob(alignmentResultStr), m => m.codePointAt(0));
numbers = new Uint16Array(bytes.buffer);
console.log('Decoded:', numbers.join(','));
} catch (e) {
console.error(e);
}
}
if (numbers.length % 4 != 0 || numbers.some(isNaN)) {
return [];
}
const result = [];
for (let i = 0; i < numbers.length; i += 4) {
result.push({
fromStart: numbers[i],
fromEnd: numbers[i + 1],
toStart: numbers[i + 2],
toEnd: numbers[i + 3],
});
}
return result;
}
function removePunctuationAlignments(result, fromText, toText) {
return result.filter(({ fromStart, fromEnd, toStart, toEnd }) => {
const from = fromText.substring(fromStart, fromEnd);
const to = toText.substring(toStart, toEnd);
if (!/[\p{L}\p{N}]/u.test(from) || !/[\p{L}\p{N}]/u.test(to)) {
console.log(`Skipping alignment of punctuation/symbol: ${from} (${fromStart}) => ${to} (${toStart})`);
return false;
}
return true;
});
}
function createTextElement(str, id, attrs = {}) {
const text = createSvgElement('text');
text.id = id;
text.setAttribute('text-anchor', 'start');
text.setAttribute('dominant-baseline', 'hanging');
for (let [attr, value] of Object.entries(attrs)) {
text.setAttribute(attr, value);
}
for (let i = 0; i < str.length; i++) {
const tspan = createSvgElement('tspan');
tspan.textContent = str[i];
tspan.id = id + i;
text.appendChild(tspan);
}
return text;
}
function centerHorizontally(el1, el2) {
const box1 = el1.getBBox();
const box2 = el2.getBBox();
if (box1.width > box2.width) {
el2.setAttribute('x', (box1.width - box2.width) / 2);
} else if (box2.width > box1.width) {
el1.setAttribute('x', (box2.width - box1.width) / 2);
}
}
function setViewBox(svg) {
const size = Array.from(svg.children).reduce((size, el) => {
if ('getBBox' in el) {
const bbox = el.getBBox();
size.width = Math.max(size.width, Math.ceil(bbox.x + bbox.width));
size.height = Math.max(size.height, Math.ceil(bbox.y + bbox.height));
}
return size;
}, { width: 0, height: 0 });
svg.setAttribute('viewBox', `0 0 ${size.width} ${size.height}`);
svg.setAttribute('width', size.width);
svg.setAttribute('height', size.height);
}
function getCharacterRangeRect(svg, textId, start, end) {
const startBox = svg.getElementById(textId + start)?.getBBox();
const endBox = svg.getElementById(textId + (end - 1))?.getBBox();
if (!startBox) {
console.error(`Missing element #${textId + start} (alignment doesn't match text?).`);
}
if (!endBox) {
console.error(`Missing element #${textId + (end - 1)} (alignment doesn't match text?).`);
}
return {
top: Math.min(startBox.y, endBox.y),
left: Math.min(startBox.x, endBox.x),
right: Math.max(startBox.x + startBox.width, endBox.x + endBox.width),
bottom: Math.max(startBox.y + startBox.height, endBox.y + endBox.height),
get width() {
return this.right - this.left;
},
get height() {
return this.bottom - this.top;
}
};
}
/**
* Because there's a gap between the text and the line (LINE_SPACING +/- the
* offsets), the x position of both ends of the line need to be offset, so
* as to "crop" the line and make it seem it continues to the correct spot
* in the text.
*
* Returns the offset for the top point. Invert for the bottom point.
*/
function calculateXOffset(x1, x2) {
const totalTextSpacing = TEXT_SPACING + (LINE_ORIGIN_OFFSET * 2)
return (LINE_SPACING / totalTextSpacing) * Math.abs(x1 - x2) * (x1 > x2 ? -1 : 1);
}
/** @param {SVGElement} svg */
function drawAlignment(svg, fromStart, fromEnd, toStart, toEnd, color, name) {
const fromRect = getCharacterRangeRect(svg, FROM_TEXT_ID, fromStart, fromEnd);
const toRect = getCharacterRangeRect(svg, TO_TEXT_ID, toStart, toEnd);
// Draw line
let x1 = fromRect.left + (fromRect.width / 2);
let x2 = toRect.left + (toRect.width / 2);
let xOffset = calculateXOffset(x1, x2);
x1 += xOffset;
x2 -= xOffset;
const line = createSvgElement('line');
line.setAttribute('x1', x1);
line.setAttribute('y1', fromRect.bottom + LINE_SPACING - LINE_ORIGIN_OFFSET);
line.setAttribute('x2', x2);
line.setAttribute('y2', toRect.top - LINE_SPACING + LINE_ORIGIN_OFFSET);
line.setAttribute('stroke', color);
line.setAttribute('stroke-width', '2');
line.classList.add(name);
svg.appendChild(line);
// Set text color
for (let i = fromStart; i < fromEnd; i++) {
const tspan = svg.getElementById(FROM_TEXT_ID + i);
tspan.setAttribute('fill', color);
tspan.classList.add(name);
}
for (let i = toStart; i < toEnd; i++) {
const tspan = svg.getElementById(TO_TEXT_ID + i);
tspan.setAttribute('fill', color);
tspan.classList.add(name);
}
// Draw highlight rectangles under text
const drawHighlight = (rect, offsetTop, offsetBottom) => {
const highlight = createSvgElement('rect');
highlight.setAttribute('x', rect.left);
highlight.setAttribute('y', rect.top + offsetTop);
highlight.setAttribute('width', rect.width);
highlight.setAttribute('height', rect.height - offsetTop - offsetBottom);
highlight.setAttribute('fill', color);
highlight.setAttribute('opacity', darkMode.checked ? '0.08' : '0.14');
highlight.classList.add(name);
svg.insertBefore(highlight, svg.querySelector('text'));
};
drawHighlight(fromRect, 0, 0.1 * EM);
drawHighlight(toRect, 0.1 * EM, 0);
}
function createDownloadableSvg(svg) {
svg = svg.cloneNode(true);
for (let el of svg.querySelectorAll('[id]')) {
el.removeAttribute('id');
}
return '<?xml version="1.0" standalone="yes"?>\n' + svg.outerHTML;
}
function isJapanese(text) {
return /[一-龠ぁ-ゔァ-ヴー]/.test(text);
}
function createPalette(name, dark) {
switch (name) {
case 'material':
return dark ? [
'#e57373', // Red 300
'#ba68c8', // Purple 300
'#7986cb', // Indigo 300
'#4fc3f7', // Light Blue 300
'#aed581', // Light Green 300
'#ffd54f', // Amber 300
] : [
'#c62828', // Red 800
'#6a1b9a', // Purple 800
'#283593', // Indigo 800
'#0277bd', // Light Blue 800
'#558b2f', // Light Green 800
'#ff8f00', // Amber 800
];
case 'one':
return dark ? [
'#be5046', // Red
'#e06c75', // Light red
'#d19a66', // Orange
'#e5c07b', // Yellow
'#98c379', // Green
'#61afef', // Blue
'#56b6c2', // Cyan
'#c678dd', // Purple
] : [
'#ca1243', // Red
'#e45649', // Light red
'#986801', // Orange
'#c18401', // Yellow
'#50a14f', // Green
'#4078f2', // Blue
'#0184bc', // Cyan
'#a626a4', // Purple
];
}
}
</script>
</body>
</html>