forked from explosion/displacy-ent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
displacy-ent.js
81 lines (62 loc) · 3.04 KB
/
displacy-ent.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
//- ----------------------------------
//- 💥 DISPLACY ENT
//- ----------------------------------
'use strict';
class displaCyENT {
constructor (api, options) {
this.api = api;
this.container = document.querySelector(options.container || '#displacy');
this.defaultText = options.defaultText || 'When Sebastian Thrun started working on self-driving cars at Google in 2007, few people outside of the company took him seriously.';
this.defaultModel = options.defaultModel || 'en';
this.defaultEnts = options.defaultEnts || ['person', 'org', 'gpe', 'loc', 'product'];
this.onStart = options.onStart || false;
this.onSuccess = options.onSuccess || false;
this.onError = options.onError || false;
this.onRender = options.onRender || false;
}
parse(text = this.defaultText, model = this.defaultModel, ents = this.defaultEnts) {
if(typeof this.onStart === 'function') this.onStart();
let xhr = new XMLHttpRequest();
xhr.open('POST', this.api, true);
xhr.setRequestHeader('Content-type', 'text/plain');
xhr.onreadystatechange = () => {
if(xhr.readyState === 4 && xhr.status === 200) {
if(typeof this.onSuccess === 'function') this.onSuccess();
this.render(text, JSON.parse(xhr.responseText), ents);
}
else if(xhr.status !== 200) {
if(typeof this.onError === 'function') this.onError(xhr.statusText);
}
}
xhr.onerror = () => {
xhr.abort();
if(typeof this.onError === 'function') this.onError();
}
xhr.send(JSON.stringify({ text, model }));
}
render(text, spans, ents) {
this.container.innerHTML = '';
let offset = 0;
spans.forEach(({ type, start, end }) => {
const entity = text.slice(start, end);
const fragments = text.slice(offset, start).split('\n');
fragments.forEach((fragment, i) => {
this.container.appendChild(document.createTextNode(fragment));
if(fragments.length > 1 && i != fragments.length - 1) this.container.appendChild(document.createElement('br'));
});
if(ents.includes(type.toLowerCase())) {
const mark = document.createElement('mark');
mark.setAttribute('data-entity', type.toLowerCase());
mark.appendChild(document.createTextNode(entity));
this.container.appendChild(mark);
}
else {
this.container.appendChild(document.createTextNode(entity));
}
offset = end;
});
this.container.appendChild(document.createTextNode(text.slice(offset, text.length)));
console.log(`%c💥 HTML markup\n%c<div class="entities">${this.container.innerHTML}</div>`, 'font: bold 16px/2 arial, sans-serif', 'font: 13px/1.5 Consolas, "Andale Mono", Menlo, Monaco, Courier, monospace');
if(typeof this.onRender === 'function') this.onRender();
}
}