All files / lib/nlu base-nlu.js

100% Statements 143/143
100% Branches 75/75
100% Functions 25/25
100% Lines 136/136

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                              42x 42x 42x   42x                             518x 518x 518x 518x       518x 518x 518x                   1986x 1986x 1986x 20011x 20011x       123x     1863x                   15x                 1938x 10x   1928x 10x   1918x 1918x 5x   1913x 1913x 70x 5x   65x 64x   65x   1843x 1843x 5x   1843x 1843x 7318x                   48x 5x   43x 43x 5x   38x       38x 28x 3x 1x 2x 1x     25x 25x 65x 65x 64x                         6120x                 1129x 3499x 374x     755x       623x 623x 1129x 374x     623x                 8x               27x 27x 27x 27x 27x 27x 356x         27x 27x 27x               41x 41x 41x 41x 41x 41x 6789x   41x 41x                 634x 634x 832x   634x 633x 633x 830x         633x   1x               41x 41x 41x                 325x               34x 33x 33x 122x 122x                         13x 13x 13x 13x 72x 72x 8x   72x 63x 63x 63x 247x       13x 13x 13x                       2064x 2064x 2064x 2064x 8954x 6062x 2892x 2134x     2064x             27x 27x 27x 27x               41x 41x       42x   42x  
/*
 * Copyright (c) AXA Group Operations 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 NlpUtil = require('../nlp/nlp-util');
const Classifier = require('../classifiers/classifier');
const { removeEmojis } = require('../util/emoji');
 
const status = {
  CREATE: 'create',
  UNTOUCH: 'untouch',
  DELETE: 'delete',
};
 
/**
 * Base class for NLU
 */
class BaseNLU {
  /**
   * Constructor of the class.
   * @param {Object} settings Settings for this instance
   */
  constructor(settings) {
    this.settings = settings || {};
    this.language = this.settings.language || 'en';
    this.stemmer = this.settings.stemmer || NlpUtil.getStemmer(this.language);
    this.keepStopwords =
      this.settings.keepStopwords === undefined
        ? true
        : this.settings.keepStopwords;
    this.docs = [];
    this.features = {};
    this.isEditing = false;
  }
 
  /**
   * Gets the position of a utterance for an intent.
   * @param {Object} utterance Utterance to be found.
   * @param {Object} intent Intent of the utterance.
   * @returns {Number} Position of the utterance, -1 if not found.
   */
  posUtterance(utterance, intent) {
    const tokens = this.tokenizeAndStem(utterance);
    const tokenStr = tokens.join(' ');
    for (let i = 0; i < this.docs.length; i += 1) {
      const doc = this.docs[i];
      if (
        doc.tokens.join(' ') === tokenStr &&
        (!intent || doc.intent === intent)
      ) {
        return i;
      }
    }
    return -1;
  }
 
  /**
   * Indicates if an utterance already exists, at the given intent or globally.
   * @param {String} utterance Utterance to be checked.
   * @param {String} intent Intent to check, undefined to search globally.
   * @returns {boolean} True if the intent exists, false otherwise.
   */
  existsUtterance(utterance, intent) {
    return this.posUtterance(utterance, intent) !== -1;
  }
 
  /**
   * Adds a new utterance to an intent.
   * @param {String} utterance Utterance to be added.
   * @param {String} intent Intent for adding the utterance.
   */
  add(utterance, intent) {
    if (typeof utterance !== 'string' && !Array.isArray(utterance)) {
      throw new Error('Utterance must be an string');
    }
    if (typeof intent !== 'string') {
      throw new Error('Intent must be an string');
    }
    const tokens = this.tokenizeAndStem(utterance);
    if (tokens.length === 0) {
      return;
    }
    const pos = this.posUtterance(tokens, intent);
    if (pos !== -1) {
      if (!this.isEditing) {
        return;
      }
      if (this.docs[pos].status !== status.CREATE) {
        this.docs[pos].status = status.UNTOUCH;
      }
      return;
    }
    const doc = { intent: intent.trim(), utterance, tokens };
    if (this.isEditing) {
      doc.status = status.CREATE;
    }
    this.docs.push(doc);
    tokens.forEach(token => {
      this.features[token] = (this.features[token] || 0) + 1;
    });
  }
 
  /**
   * Remove an utterance from the classifier.
   * @param {String} utterance Utterance to be removed.
   * @param {String} intent Intent of the utterance, undefined to search all
   */
  remove(utterance, intent) {
    if (typeof utterance !== 'string' && !Array.isArray(utterance)) {
      throw new Error('Utterance must be an string');
    }
    const tokens = this.tokenizeAndStem(utterance);
    if (tokens.length === 0) {
      return;
    }
    const pos = this.posUtterance(
      utterance,
      intent ? intent.trim() : undefined
    );
    if (pos !== -1) {
      if (this.isEditing) {
        if (this.docs[pos].status === status.CREATE) {
          this.docs.splice(pos, 1);
        } else if (this.docs[pos].status === status.UNTOUCH) {
          this.docs[pos].status = status.DELETE;
        }
      } else {
        this.docs.splice(pos, 1);
        tokens.forEach(token => {
          this.features[token] = this.features[token] - 1;
          if (this.features[token] <= 0) {
            delete this.features[token];
          }
        });
      }
    }
  }
 
  /**
   * Generate the vector of features.
   * @param {String} utterance Input utterance.
   * @returns {String[]} Vector of features.
   */
  tokenizeAndStem(utterance) {
    return typeof utterance === 'string'
      ? this.stemmer.tokenizeAndStem(
          removeEmojis(utterance),
          this.keepStopwords
        )
      : utterance;
  }
 
  someSimilar(tokensA, tokensB) {
    for (let i = 0; i < tokensB.length; i += 1) {
      if (tokensA[tokensB[i]]) {
        return true;
      }
    }
    return false;
  }
 
  getWhitelist(tokens) {
    const result = {};
    for (let i = 0; i < this.docs.length; i += 1) {
      if (this.someSimilar(tokens, this.docs[i].tokens)) {
        result[this.docs[i].intent] = 1;
      }
    }
    return Object.keys(result);
  }
 
  /**
   * Given an utterance, get the label and score of the best classification.
   * @param {String} utterance Utterance to be classified.
   * @returns {Object} Best classification of the observation.
   */
  getBestClassification(utterance) {
    return this.getClassifications(utterance)[0];
  }
 
  /**
   * Exports properties to an object
   * @returns {Object} Object properties
   */
  baseToObj() {
    const result = {};
    result.settings = this.settings;
    result.language = this.language;
    result.keepStopwords = this.keepStopwords;
    result.docs = [];
    for (let i = 0; i < this.docs.length; i += 1) {
      result.docs.push({
        intent: this.docs[i].intent,
        tokens: this.docs[i].tokens,
      });
    }
    result.features = this.features;
    result.isEditing = this.isEditing;
    return result;
  }
 
  /**
   * Import instance properties from an object
   * @param {Object} obj Object properties
   */
  baseFromObj(obj) {
    this.settings = obj.settings;
    this.language = obj.language;
    this.keepStopwords = obj.language;
    this.stemmer = this.settings.stemmer || NlpUtil.getStemmer(this.language);
    this.docs = obj.docs;
    for (let i = 0; i < this.docs.length; i += 1) {
      this.docs[i].utterance = this.docs[i].tokens;
    }
    this.features = obj.features;
    this.isEditing = obj.isEditing;
  }
 
  /**
   * Normalize the neural network results
   * @param {Object[]} classifications Input classifications
   * @returns {Object[]} Normalized classifications
   */
  normalizeNeural(classifications) {
    let total = 0;
    for (let i = 0; i < classifications.length; i += 1) {
      total += classifications[i].value ** 2;
    }
    if (total > 0) {
      const result = [];
      for (let i = 0; i < classifications.length; i += 1) {
        result.push({
          label: classifications[i].label,
          value: classifications[i].value ** 2 / total,
        });
      }
      return result;
    }
    return classifications;
  }
 
  /**
   * Factory to create instance given an object properties.
   * @param {Object} obj Object properties
   */
  static fromObj(obj) {
    const instance = new BaseNLU.classes[obj.className]();
    instance.fromObj(obj);
    return instance;
  }
 
  /**
   * Factory to create new class given class name and settings.
   * @param {String} className Class name
   * @param {*} settings Settings for the instance
   */
  static createClass(className, settings) {
    return new BaseNLU.classes[className](settings);
  }
 
  /**
   * Enter edit mode.
   * - By default, starts marking all docs status as delete
   */
  beginEdit() {
    if (!this.isEditing) {
      this.isEditing = true;
      this.docs.forEach(srcDoc => {
        const doc = srcDoc;
        doc.status = status.DELETE;
      });
    }
  }
 
  /**
   * Ends edit mode:
   * - Remove docs marked as delete
   * - Calculates if NLU should be retrained
   * - Recalculate features
   * @returns {boolean} True if should be retrained, false otherwise.
   */
  endEdit() {
    let result = false;
    const finalDocs = [];
    this.features = {};
    this.docs.forEach(srcDoc => {
      const doc = srcDoc;
      if (!result && doc.status !== status.UNTOUCH) {
        result = true;
      }
      if (doc.status !== status.DELETE) {
        delete doc.status;
        finalDocs.push(doc);
        doc.tokens.forEach(token => {
          this.features[token] = (this.features[token] || 0) + 1;
        });
      }
    });
    this.docs = finalDocs;
    this.isEditing = false;
    return result;
  }
 
  /**
   * Given an utterance, tokenize and steam the utterance and convert it
   * to a vector of binary values, where each position is a feature (a word
   * stemmed) and the value means if the utterance has this feature.
   * The input utterance can be an string or an array of tokens.
   * @param {String} utterance Utterance to be converted to features vector.
   * @returns {Number[]} Features vector of the utterance.
   */
  textToFeatures(utterance) {
    const tokens = this.tokenizeAndStem(utterance);
    const nonedelta = 1 / (tokens.length * 4);
    const result = {};
    tokens.forEach(key => {
      if (this.features[key] > 0) {
        result[key] = 1;
      } else if (this.settings.useNoneFeature) {
        result.nonefeature = (result.nonefeature || 0) + nonedelta;
      }
    });
    return result;
  }
 
  /**
   * Export as object
   */
  toObj() {
    const result = this.baseToObj();
    result.className = this.constructor.name;
    result.classifier = this.classifier.toObj();
    return result;
  }
 
  /**
   * Import from object
   * @param {Object} obj Source object
   */
  fromObj(obj) {
    this.baseFromObj(obj);
    this.classifier = Classifier.fromObj(obj.classifier);
  }
}
 
BaseNLU.classes = {};
 
module.exports = BaseNLU;