| 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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640 |
30x
30x
30x
30x
30x
30x
30x
30x
173x
173x
173x
173x
173x
173x
173x
173x
4152x
173x
173x
292x
154x
154x
138x
156x
90x
90x
86x
70x
111x
111x
17x
18x
76x
294x
183x
111x
111x
111x
256x
2x
238x
238x
5x
5x
4x
272x
272x
272x
325x
135x
272x
1936x
1936x
1258x
1258x
1258x
1258x
1258x
678x
137x
133x
99x
99x
99x
39x
39x
99x
34x
34x
34x
20x
20x
34x
14x
14x
34x
14x
14x
34x
20x
20x
34x
14x
14x
34x
14x
14x
34x
541x
8x
533x
292x
292x
292x
292x
156x
533x
292x
241x
622x
979x
979x
34x
103x
103x
12x
12x
12x
12x
12x
12x
12x
12x
622x
622x
1932x
1932x
1932x
3718x
3718x
3718x
576x
576x
2x
622x
622x
1932x
1930x
622x
622x
622x
622x
8330x
8330x
8328x
595x
8328x
1936x
1936x
1936x
1936x
291x
1936x
1936x
1936x
1936x
1936x
1932x
1924x
1932x
622x
468x
622x
622x
622x
622x
99x
99x
92x
92x
63x
622x
305x
305x
22x
283x
283x
283x
475x
475x
475x
475x
475x
283x
283x
283x
4x
4x
4x
4x
4x
4x
4x
13x
13x
13x
8x
5x
4x
4x
4x
4x
1x
1x
1x
1x
1x
1x
1x
1x
2x
2x
2x
2x
2x
1x
1x
1x
1x
2x
13x
4x
11x
11x
11x
11x
11x
7x
7x
7x
4x
3x
2x
2x
2x
1x
1x
1x
1x
1x
1x
1x
2x
2x
1x
1x
1x
1x
2x
30x
| /*
* Copyright (c) AXA Shared Services Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const Recognizers = require('@microsoft/recognizers-text-suite');
const { SimilarSearch } = require('../util');
const EnumNamedEntity = require('./enum-named-entity');
const NlpUtil = require('../nlp/nlp-util');
const RegexNamedEntity = require('./regex-named-entity');
const TrimNamedEntity = require('./trim-named-entity');
const BuiltinDictionary = require('./builtin-dictionary.json');
const BuiltinInverse = require('./builtin-inverse.json');
/**
* Class for a named entities manager, that can be recognized inside
* a string.
* Basically, a named entity is an enumerator that has a set of options,
* and each option can have several words to refer to this option.
* Example:
* We have the entity "Superhero". Inside "Superhero" we have different
* options:
* - Superman: Superman
* - Spiderman: Spiderman, Spider-man
* - Wolverine: Wolverine, Logan, Patch, Weapon X
*/
class NerManager {
/**
* Constructor of the class.
* @param {Object} settings Settings for initializing this instance.
*/
constructor(settings) {
this.settings = settings || {};
this.threshold = this.settings.threshold || 0.8;
this.namedEntities = {};
this.similar = new SimilarSearch({ normalize: true });
this.builtins = this.settings.builtins || [
'Number',
'Ordinal',
'Percentage',
'Age',
'Currency',
'Dimension',
'Temperature',
'DateTime',
'PhoneNumber',
'IpAddress',
'Boolean',
'Email',
'Hashtag',
'URL',
];
let list = this.settings.builtinWhitelist || [
'age',
'currency',
'dimension',
'temperature',
'number',
'numberrange',
'ordinal',
'percentage',
'email',
'hashtag',
'ip',
'mention',
'phonenumber',
'url',
'date',
'daterange',
'datetime',
'datetimealt',
'time',
'set',
'timerange',
'timezone',
'boolean',
'duration',
];
this.builtinWhitelist = {};
for (let i = 0; i < list.length; i += 1) {
this.builtinWhitelist[list[i]] = true;
}
list = this.settings.builtinBlacklist || [];
for (let i = 0; i < list.length; i += 1) {
delete this.builtinWhitelist[list[i]];
}
}
/**
* Given a resolution unit in source language, translate into default language.
* @param {string} str Resolution unit in source language.
* @param {string} locale Source language locale.
* @returns {string} Translation or source resolution unit.
*/
translate(str, locale) {
if (BuiltinDictionary[locale]) {
const translation = BuiltinDictionary[locale][str];
return translation !== '' ? translation : str;
}
return str;
}
/**
* Given a resolution unit in default language, translate into source language.
* @param {string} str Resolution unit in default language.
* @param {string} locale Source language locale.
* @returns {string} Translation or default resolution unit.
*/
inverseTranslate(str, locale) {
if (BuiltinInverse[locale]) {
const translation = BuiltinInverse[locale][str];
if (translation && translation.length > 0) {
return translation[0];
}
}
return str;
}
/**
* Creates a new instance of a named entity.
* @param {string} entityName Name of the entity
* @param {string} type Type of the entity
* @returns {NamedEntity} New named entity.
*/
newNamedEntity(entityName, type = 'enum') {
const options = { name: entityName };
switch (type.toLowerCase()) {
case 'regex':
return new RegexNamedEntity(options);
case 'trim':
return new TrimNamedEntity(options);
default:
return new EnumNamedEntity(options);
}
}
/**
* Adds a new entity to be managed by the NER. If the entity already exists,
* then returns the already existing one.
* @param {String} entityName Name of the entity.
* @param {String} type Type of the entity.
* @returns {Object} Already existing entity or the new one created.
*/
addNamedEntity(entityName, type) {
if (this.namedEntities[entityName]) {
return this.namedEntities[entityName];
}
const entity = this.newNamedEntity(entityName, type);
this.namedEntities[entityName] = entity;
return entity;
}
/**
* Get an entity given its name. If the entity does not exists and the
* force flag is on, then creates the entity.
* @param {String} entityName Name of the entity.
* @param {boolean} force Flag to create the entity when it does not exists.
* @returns {Object} The entity, or undefined if not found and not forced.
*/
getNamedEntity(entityName, force = false) {
return force
? this.addNamedEntity(entityName)
: this.namedEntities[entityName];
}
/**
* Removes an entity from the NER.
* @param {String} entityName Name of the entity.
*/
removeNamedEntity(entityName) {
delete this.namedEntities[entityName];
}
/**
* Add texts to the given languages of an option of an entity.
* @param {String} entityName Name of the entity.
* @param {String} optionName Name of the option.
* @param {String[]} srcLanguages Language or languages for adding the texts.
* @param {String[]} srcTexts Text or texts to be added.
*/
addNamedEntityText(entityName, optionName, srcLanguages, srcTexts) {
const entity = this.getNamedEntity(entityName, true);
entity.addText(optionName, srcLanguages, srcTexts);
}
/**
* Remove texts for the given languages of the option of an entity.
* @param {String} entityName Name of the entity.
* @param {String} optionName Name of the option.
* @param {String[]} srcLanguages Languages affected.
* @param {String[]} srcTexts Texts to be removed.
*/
removeNamedEntityText(entityName, optionName, srcLanguages, srcTexts) {
const entity = this.getNamedEntity(entityName);
if (entity) {
entity.removeText(optionName, srcLanguages, srcTexts);
}
}
/**
* Given an utterance, search for %entity% format inside it, in order to
* return the list of entities referenced by the utterance.
* @param {String} utterance Utterance for searching.
* @returns {String[]} List of entities.
*/
getEntitiesFromUtterance(utterance) {
const entityKeys = Object.keys(this.namedEntities);
const result = [];
entityKeys.forEach(entity => {
if (utterance.indexOf(`%${entity}%`) > -1) {
result.push(entity);
}
});
return result;
}
/**
* Given an entity and a locale, calculate the resolution.
* @param {Object} entity Entity instance with resolution.
* @param {string} locale Entity language locale.
* @returns {Object} Calculated resolution for the entity.
*/
calculateResolution(entity, locale) {
const { resolution } = entity;
if (['number', 'ordinal', 'percentage'].includes(entity.typeName)) {
let resValue = resolution.value;
Eif (resValue) {
resValue = resValue.replace(',', '.');
}
const value = Number.parseFloat(resValue);
return {
strValue: resValue,
value,
subtype: value % 1 === 0 ? 'integer' : 'float',
};
}
if (
entity.typeName === 'datetimeV2.date' ||
entity.typeName === 'datetimeV2.daterange'
) {
Eif (resolution.values) {
if (resolution.values.length === 1) {
const resValue = resolution.values[0];
const result = {
type: resValue.type,
timex: resValue.timex,
};
if (resValue.value) {
result.strValue = resValue.value;
result.date = new Date(resValue.value);
}
return result;
}
Eif (resolution.values.length === 2) {
const result = {
type: 'interval',
timex: resolution.values[0].timex,
};
if (resolution.values[0].value) {
result.strPastValue = resolution.values[0].value;
result.pastDate = new Date(result.strPastValue);
}
if (resolution.values[0].start) {
result.strPastStartValue = resolution.values[0].start;
result.pastStartDate = new Date(result.strPastStartValue);
}
if (resolution.values[0].end) {
result.strPastEndValue = resolution.values[0].end;
result.pastEndDate = new Date(result.strPastEndValue);
}
if (resolution.values[1].value) {
result.strFutureValue = resolution.values[1].value;
result.futureDate = new Date(result.strFutureValue);
}
if (resolution.values[1].start) {
result.strFutureStartValue = resolution.values[1].start;
result.futureStartDate = new Date(result.strFutureStartValue);
}
if (resolution.values[1].end) {
result.strFutureEndValue = resolution.values[1].end;
result.futureEndDate = new Date(result.strFutureEndValue);
}
return result;
}
}
}
if (!resolution) {
return undefined;
}
if (resolution.unit) {
const srcUnit = resolution.unit;
resolution.srcUnit = srcUnit;
resolution.unit = this.translate(srcUnit, locale);
if (resolution.srcUnit === resolution.unit) {
resolution.srcUnit = this.inverseTranslate(resolution.srcUnit, locale);
}
}
if (resolution.srcUnit) {
return {
strValue: resolution.value,
value: Number.parseFloat(resolution.value),
unit: resolution.unit,
localeUnit: resolution.srcUnit,
};
}
return resolution;
}
/**
* Given an array of edges, detect the trim edges and find overlaps with
* non trim edges. When an overlap is detected, reduce the trim edged to
* fit with the other edge.
* @param {Object[]} edges Edges to be splited
* @returns {Object[]} Splited edges.
*/
splitEdges(edges) {
for (let i = 0, l = edges.length; i < l; i += 1) {
const edge = edges[i];
if (
edge.type === 'between' ||
edge.type === 'after' ||
edge.type === 'afterLast' ||
edge.type === 'afterFirst' ||
edge.type === 'before' ||
edge.type === 'beforeFirst' ||
edge.type === 'beforeLast'
) {
for (let j = 0; j < edges.length; j += 1) {
const other = edges[j];
if (
i !== j &&
other.start >= edge.start &&
other.end <= edge.end &&
other.type !== 'between' &&
other.type !== 'after' &&
other.type !== 'afterLast' &&
other.type !== 'afterFirst' &&
other.type !== 'before' &&
other.type !== 'beforeFirst' &&
other.type !== 'beforeLast'
) {
const edgeLen = edge.end - edge.start;
const otherLen = other.end - other.start;
Eif (other.start - edge.start > edge.end - other.end) {
// is at the beginning
const text = edge.sourceText.substring(0, edgeLen - otherLen - 1);
edge.sourceText = text;
edge.utteranceText = text;
edge.end = other.start - 2;
edge.len = text.length;
} else {
const text = edge.sourceText.substring(edgeLen - otherLen + 2);
edge.sourceText = text;
edge.utteranceText = text;
edge.start = other.end + 2;
edge.len = text.length;
}
}
}
}
}
return edges;
}
/**
* Execute a pre-reduction of edges before running the final reduce edges.
* @param {Object[]} edges Array of edges.
* @returns {Object[]} Array of reduced edges.
*/
prereduceEdges(edges) {
for (let i = 0, l = edges.length; i < l; i += 1) {
const edge = edges[i];
Eif (!edge.discarded) {
for (let j = i + 1; j < l; j += 1) {
const other = edges[j];
Eif (!other.discarded) {
if (other.start === edge.start && other.end === edge.end) {
Iif (other.entity === 'number' && edge.entiy === 'ordinal') {
other.discarded = true;
} else if (
other.entity === 'ordinal' &&
edge.entity === 'number'
) {
edge.discarded = true;
}
}
}
}
}
}
const result = [];
for (let i = 0, l = edges.length; i < l; i += 1) {
if (!edges[i].discarded) {
result.push(edges[i]);
}
}
return result;
}
/**
* Extract built-in entities for the utterance given the language.
* @param {string} utterance Input utterance.
* @param {string} language Language locale.
* @returns {Object[]} Extracted entities as edges array.
*/
findBuiltinEntities(utterance, language) {
const result = [];
const culture = NlpUtil.getCulture(language);
this.builtins.forEach(name => {
try {
const entities = Recognizers[`recognize${name}`](utterance, culture);
if (name === 'Number') {
entities.push(
...Recognizers.recognizeNumber(utterance, NlpUtil.getCulture('en'))
);
}
for (let i = 0; i < entities.length; i += 1) {
const entity = entities[i];
let entityName = entity.typeName;
const index = entityName.lastIndexOf('.');
if (index !== -1) {
entityName = entityName.slice(index + 1);
}
Eif (this.builtinWhitelist[entityName]) {
const text = utterance.slice(entity.start, entity.end + 1);
const accuracy = 0.95;
const edge = {
start: entity.start,
end: entity.end,
len: entity.end - entity.start + 1,
accuracy,
sourceText: text,
utteranceText: text,
entity: entityName,
};
const resolution = this.calculateResolution(entity, language);
if (resolution) {
edge.resolution = resolution;
}
result.push(edge);
}
}
} catch (ex) {
//
}
});
return this.similar
.reduceEdges(this.prereduceEdges(result), false)
.sort((a, b) => a.start - b.start);
}
/**
* Find entities inside an utterance.
* @param {String} utterance Utterance for searching entities.
* @param {String} locale Locale of the language.
* @param {String[]} whitelist Whitelist of entity names.
* @returns {Promise.Object[]} Promise edges of entities found.
*/
async findEntities(utterance, language, whitelist) {
const entityNames = whitelist || Object.keys(this.namedEntities);
const wordPositions = this.similar.getWordPositions(utterance);
const edges = this.findBuiltinEntities(utterance, language);
entityNames.forEach(entityName => {
const entity = this.namedEntities[entityName];
if (entity) {
const newEdges = entity.extract(
utterance,
language,
this.similar,
wordPositions,
this.threshold
);
newEdges.forEach(edge => {
edges.push(edge);
});
}
});
return this.similar.reduceEdges(this.splitEdges(edges), false);
}
/**
* Find entities on utterance, and replace them by the entity name.
* @param {String} utterance Utterance to be processed.
* @param {String} locale Locale of the utterance.
* @returns {Promise.String} Promise utterance with entities replaced by entity name.
*/
async generateEntityUtterance(utterance, locale) {
const entities = await this.findEntities(utterance, locale);
if (entities.length === 0) {
return utterance;
}
let index = 0;
let result = '';
for (let i = 0; i < entities.length; i += 1) {
const entity = entities[i];
const left = utterance.slice(index, entity.start);
index = entity.end;
result += left;
result += `%${entity.entity}%`;
}
const right = utterance.slice(entities[entities.length - 1].end);
result += right;
return result;
}
/**
* Returns a clone object representing this, for saving.
* @returns {Object} Clone object.
*/
save() {
const result = {};
result.settings = this.settings;
result.threshold = this.threshold;
result.builtins = this.builtins;
result.namedEntities = {};
const keys = Object.keys(this.namedEntities);
for (let i = 0; i < keys.length; i += 1) {
const entity = this.namedEntities[keys[i]];
const clone = {
type: entity.type,
name: entity.name,
localeFallback: entity.localeFallback,
};
if (entity.type === 'enum') {
clone.locales = entity.locales;
} else if (entity.type === 'regex') {
clone.locales = {};
const localeKeys = Object.keys(entity.locales);
for (let j = 0; j < localeKeys.length; j += 1) {
clone.locales[localeKeys[j]] = {
regex: RegexNamedEntity.regex2str(
entity.locales[localeKeys[j]].regex
),
};
}
} else Eif (entity.type === 'trim') {
clone.locales = {};
const localeKeys = Object.keys(entity.locales);
for (let j = 0; j < localeKeys.length; j += 1) {
clone.locales[localeKeys[j]] = {
conditions: [],
};
const { conditions } = entity.locales[localeKeys[j]];
const cloneConditions = clone.locales[localeKeys[j]].conditions;
for (let k = 0; k < conditions.length; k += 1) {
const condition = conditions[k];
const cloneCondition = {};
cloneCondition.type = condition.type;
cloneCondition.options = condition.options;
if (condition.type === 'between') {
cloneCondition.leftWords = condition.leftWords;
cloneCondition.rightWords = condition.rightWords;
cloneCondition.regex = RegexNamedEntity.regex2str(
condition.regex
);
} else {
cloneCondition.words = condition.words;
}
cloneConditions.push(cloneCondition);
}
}
}
result.namedEntities[keys[i]] = clone;
}
return result;
}
/**
* Load this instance from an object.
* @param {Object} obj Object to load from.
*/
load(obj) {
this.settings = obj.settings;
this.threshold = obj.threshold;
this.builtins = obj.builtins || [];
const keys = Object.keys(obj.namedEntities);
for (let i = 0; i < keys.length; i += 1) {
const cloned = obj.namedEntities[keys[i]];
const entity = this.addNamedEntity(cloned.name, cloned.type);
if (cloned.type === 'enum') {
entity.locales = cloned.locales;
} else if (cloned.type === 'regex') {
const localeKeys = Object.keys(cloned.locales);
for (let j = 0; j < localeKeys.length; j += 1) {
entity.locales[localeKeys[j]] = {
regex: RegexNamedEntity.str2regex(
cloned.locales[localeKeys[j]].regex
),
};
}
} else Eif (cloned.type === 'trim') {
const localeKeys = Object.keys(cloned.locales);
for (let j = 0; j < localeKeys.length; j += 1) {
entity.locales[localeKeys[j]] = {
conditions: [],
};
const clonedConditions = cloned.locales[localeKeys[j]].conditions;
const { conditions } = entity.locales[localeKeys[j]];
for (let k = 0; k < clonedConditions.length; k += 1) {
const condition = {
type: clonedConditions[k].type,
options: clonedConditions[k].options,
};
if (condition.type === 'between') {
condition.leftWords = clonedConditions[k].leftWords;
condition.rightWords = clonedConditions[k].rightWords;
condition.regex = RegexNamedEntity.str2regex(
clonedConditions[k].regex
);
} else {
condition.words = clonedConditions[k].words;
}
conditions.push(condition);
}
}
}
}
}
}
module.exports = NerManager;
|