All files / lib/nlu domain-manager.js

97.44% Statements 114/117
91.53% Branches 54/59
100% Functions 19/19
97.37% Lines 111/114

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                                              42x 42x 42x 42x                     278x 278x 278x 278x       278x       278x 278x       278x 278x 278x 278x 278x                       2384x                         2382x                         1775x 326x 1x   325x           1775x               2x                   1136x 1136x 1136x 1x 1x   1136x 1136x 338x 338x 338x 338x   798x 798x   1136x                   9x 9x 9x 9x 6x 6x 6x 6x   3x 3x               80x 10x 29x   10x 10x 27x 9x   1x       70x                   1239x 1239x 1237x 1237x 1237x       16x 16x       16x 428x 412x       412x       16x     1223x 612x 612x           612x   612x     612x   611x   7x 4x 4x 4x   6x   7x 7x       604x               14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 22x   14x               18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 36x               11x       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 BaseNLU = require('./base-nlu');
require('./brain-nlu');
const NlpUtil = require('../nlp/nlp-util');
const { removeEmojis } = require('../util/emoji');
 
/**
 * Manager for several domains, using the same language.
 */
class DomainManager {
  /**
   * Constructor of the class.
   * @param {Object} settings Settings for this instance.
   */
  constructor(settings) {
    this.settings = settings || {};
    this.language = this.settings.language || 'en';
    this.nluClassName = this.settings.nluClassName || 'BrainNLU';
    this.useMasterDomain =
      this.settings.useMasterDomain === undefined
        ? true
        : this.settings.useMasterDomain;
    this.trainByDomain =
      this.settings.trainByDomain === undefined
        ? false
        : this.settings.trainByDomain;
    this.stemmer = this.settings.stemmer || NlpUtil.getStemmer(this.language);
    this.keepStopwords =
      this.settings.keepStopwords === undefined
        ? true
        : this.settings.keepStopwords;
    this.domains = {};
    this.addDomain('master_domain');
    this.stemDict = {};
    this.intentDict = {};
    this.useStemDict =
      this.settings.useStemDict === undefined
        ? true
        : this.settings.useStemDict;
  }
 
  /**
   * 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;
  }
 
  /**
   * Generates an string representing the stems
   * @param {String[]} utterance Stemmed utterance.
   */
  generateStemKey(utterance) {
    return utterance
      .slice()
      .sort()
      .join();
  }
 
  /**
   * Adds a domain
   * @param {String} name Name of the domain.
   * @param {Object} nlu NLU instance or undefined to create a new one.
   * @returns {Object} Domain created or the existing one.
   */
  addDomain(name, nlu) {
    if (!this.domains[name]) {
      if (nlu) {
        this.domains[name] = nlu;
      } else {
        this.domains[name] = BaseNLU.createClass(
          this.nluClassName,
          this.settings
        );
      }
    }
    return this.domains[name];
  }
 
  /**
   * Remove a domain by name.
   * @param {String} name Name of the domain.
   */
  removeDomain(name) {
    delete this.domains[name];
  }
 
  /**
   * Adds a new utterance to an intent.
   * @param {String} domain Domain of the intent.
   * @param {String} utterance Utterance to be added.
   * @param {String} intent Intent for adding the utterance.
   */
  add(domain, utterance, intent) {
    const stems = this.tokenizeAndStem(utterance);
    const stemKey = this.generateStemKey(stems);
    if (this.stemDict[stemKey]) {
      const key = this.stemDict[stemKey];
      this.remove(key.domain, stems, key.intent);
    }
    this.stemDict[stemKey] = { domain, intent };
    if (this.trainByDomain) {
      const nlu = this.addDomain(domain);
      nlu.add(stems, intent);
      const master = this.addDomain('master_domain');
      master.add(stems, domain);
    } else {
      const nlu = this.addDomain('master_domain');
      nlu.add(stems, intent);
    }
    this.intentDict[intent] = domain;
  }
 
  /**
   * Remove an utterance from the nlu.
   * @Param {String} domain Domain of the intent
   * @param {String} utterance Utterance to be removed.
   * @param {String} intent Intent of the utterance, undefined to search all
   */
  remove(domain, utterance, intent) {
    const stems = this.tokenizeAndStem(utterance);
    const stemKey = this.generateStemKey(stems);
    delete this.stemDict[stemKey];
    if (this.trainByDomain) {
      const nlu = this.addDomain(domain);
      nlu.remove(stems, intent);
      const master = this.addDomain('master_domain');
      master.remove(stems, domain);
    } else {
      const nlu = this.addDomain('master_domain');
      nlu.remove(stems, intent);
    }
  }
 
  /**
   * Train the NLUs
   */
  async train() {
    if (this.trainByDomain) {
      const domainNames = Object.keys(this.domains).filter(
        x => x !== 'master_domain'
      );
      Eif (domainNames.length > 0) {
        if (domainNames.length > 1) {
          const promises = Object.values(this.domains).map(dom => dom.train());
          return Promise.all(promises);
        }
        return this.domains[domainNames[0]].train();
      }
      return true;
    }
    return this.domains.master_domain.train();
  }
 
  /**
   * Get all the labels and score for each label from this utterance.
   * @param {String} utterance Utterance to be classified.
   * @param {String} domainName Name of the domain, optional.
   * @returns {Object[]} Sorted array of classifications, with label and score.
   */
  getClassifications(utterance, domainName) {
    const stems = this.tokenizeAndStem(utterance);
    if (this.useStemDict) {
      const stemKey = this.generateStemKey(stems);
      const resolvedIntent = this.stemDict[stemKey];
      if (
        resolvedIntent &&
        (!domainName || resolvedIntent.domain === domainName)
      ) {
        const classifications = [];
        classifications.push({
          label: resolvedIntent.intent,
          value: 1,
        });
        Object.keys(this.intentDict).forEach(intent => {
          if (intent !== resolvedIntent.intent) {
            Eif (
              !this.trainByDomain ||
              resolvedIntent.domain === this.intentDict[intent]
            ) {
              classifications.push({ label: intent, value: 0 });
            }
          }
        });
        return { domain: resolvedIntent.domain, classifications };
      }
    }
    if (domainName) {
      const currentDomain = this.domains[domainName];
      Iif (!currentDomain) {
        return {
          domain: 'default',
          classifications: [{ label: 'None', value: 1 }],
        };
      }
      const classifications = currentDomain.getClassifications(stems);
      const finalDomain =
        domainName === 'master_domain'
          ? this.intentDict[classifications[0].label]
          : domainName;
      return { domain: finalDomain, classifications };
    }
    if (this.trainByDomain) {
      let domain;
      if (Object.keys(this.domains).length > 2) {
        const master = this.domains.master_domain;
        const domainClassifications = master.getClassifications(stems);
        domain = domainClassifications[0].label;
      } else {
        [domain] = Object.keys(this.domains).filter(x => x !== 'master_domain');
      }
      Eif (domain) {
        return this.getClassifications(stems, domain);
      }
      return { domain, classifications: [] };
    }
    return this.getClassifications(stems, 'master_domain');
  }
 
  /**
   * Exports object properties.
   * @returns {Object} Object properties.
   */
  toObj() {
    const result = {};
    result.settings = this.settings;
    result.language = this.language;
    result.nluClassName = this.nluClassName;
    result.useMasterDomain = this.useMasterDomain;
    result.trainByDomain = this.trainByDomain;
    result.keepStopwords = this.keepStopwords;
    result.stemDict = this.stemDict;
    result.intentDict = this.intentDict;
    result.useStemDict = this.useStemDict;
    result.domains = {};
    Object.keys(this.domains).forEach(domain => {
      result.domains[domain] = this.domains[domain].toObj();
    });
    return result;
  }
 
  /**
   * Import from object properties.
   * @param {Object} obj Object properties.
   */
  fromObj(obj) {
    this.settings = obj.settings;
    this.language = obj.language;
    this.nluClassName = obj.nluClassName;
    this.useMasterDomain = obj.useMasterDomain;
    this.trainByDomain = obj.trainByDomain;
    this.keepStopwords = obj.keepStopwords;
    this.stemDict = obj.stemDict;
    this.intentDict = obj.intentDict;
    this.domains = {};
    Object.keys(obj.domains).forEach(domain => {
      this.domains[domain] = BaseNLU.fromObj(obj.domains[domain]);
    });
  }
 
  /**
   * Begin edit in all NLUs
   */
  beginEdit() {
    Object.values(this.domains).forEach(domain => domain.beginEdit());
  }
}
 
module.exports = DomainManager;