All files / lib/util similar-search.js

100% Statements 181/181
100% Branches 98/98
100% Functions 10/10
100% Lines 158/158

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 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                                              42x                     249x 249x     249x     249x       249x                     34907x   33130x       33130x           34907x 52x   34855x 34855x 34855x 34844x 34843x 34843x 34843x       34843x 1x 13x 13x     34842x 270144x 270144x     34843x     34843x 608501x 608501x 5498409x 5498409x 156x   5498253x   5498409x 5498409x 5498409x 255369x   5498409x 5498409x 2067531x   5498409x   608501x   34843x                 25361x                     1102x 1102x 25339x   1102x 1102x 1102x 1102x 1102x 1102x 25339x 4832x 3768x         3768x   20507x 6309x 1951x         1951x 1951x   4358x 4358x     25339x   1102x 590x           1102x                             3x 3x 3x 1x           1x 1x   2x 2x 2x             2x 52x 702x       702x 702x 10x 10x 10x 10x       2x 2x                         2052x 2052x 2052x 2052x 12x 12x 12x 1x               12x   2040x 2040x 2040x 9827x 34172x       34172x 34172x 34172x 99x                   2040x       2145x 2970x 2970x 2438x 3130x 3130x 2946x 1538x 53x 1485x 2x 1483x           479x 1004x           596x             2145x 2145x 2970x 1942x     2145x                     389x 389x     389x 389x 1x   388x 388x 1295x 1295x 1295x 2047x           2047x 94x 94x 94x 94x 94x 94x       388x                       3x 3x 3x 3x 6x 6x 5x               5x 4x 4x       3x       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 { Language } = require('../language');
 
/**
 * Class for checking similarity between strings, or search the more similar
 * substring inside an string.
 */
class SimilarSearch {
  /**
   * Constructor of the class. Does the basic initializations.
   */
  constructor(settings) {
    this.settings = settings || {};
    this.alphanumeric =
      this.settings.alphanumeric ||
      new RegExp(/[\u00C0-\u1FFF\u2C00-\uD7FF\w]/);
    this.collator =
      this.settings.collator ||
      Intl.Collator('generic', { sensitivity: 'base' });
    this.useCollator =
      this.settings.useCollator === undefined
        ? false
        : this.settings.useCollator;
    this.normalize =
      this.settings.normalize === undefined ? false : this.settings.normalize;
  }
 
  /**
   * Calculates the levenshtein distance between two strings.
   * @param {String} str1 First String.
   * @param {String} str2 Second String.
   * @returns {Number} Levenshtein distance.
   */
  getSimilarity(str1, str2) {
    if (this.normalize) {
      /* eslint-disable */
      str1 = str1
        .normalize("NFD")
        .replace(/[\u0300-\u036f]/g, "")
        .toLowerCase();
      str2 = str2
        .normalize("NFD")
        .replace(/[\u0300-\u036f]/g, "")
        .toLowerCase();
      /* eslint-enable */
    }
    if (str1 === str2) {
      return 0;
    }
    const str1len = str1.length;
    const str2len = str2.length;
    if (str1len === 0) return str2len;
    if (str2len === 0) return str1len;
    const prevRow = [];
    const str2Char = [];
    const str2CharAt = [];
    let curCol;
    let nextCol;
    let tmp;
    if (this.useCollator) {
      for (let i = 0; i < str2len; i += 1) {
        prevRow[i] = i;
        str2CharAt[i] = str2.charAt(i);
      }
    } else {
      for (let i = 0; i < str2len; i += 1) {
        prevRow[i] = i;
        str2Char[i] = str2.charCodeAt(i);
      }
    }
    prevRow[str2len] = str2len;
    let strCmp;
    let j;
    for (let i = 0; i < str1len; i += 1) {
      nextCol = i + 1;
      for (j = 0; j < str2len; j += 1) {
        curCol = nextCol;
        if (this.useCollator) {
          strCmp = this.collator.compare(str1.charAt(i), str2CharAt[j]) === 0;
        } else {
          strCmp = str1.charCodeAt(i) === str2Char[j];
        }
        nextCol = prevRow[j] + (strCmp ? 0 : 1);
        tmp = curCol + 1;
        if (nextCol > tmp) {
          nextCol = tmp;
        }
        tmp = prevRow[j + 1] + 1;
        if (nextCol > tmp) {
          nextCol = tmp;
        }
        prevRow[j] = curCol;
      }
      prevRow[j] = nextCol;
    }
    return nextCol;
  }
 
  /**
   * Indicates if a character is alphanumeric.
   * @param {Character} c Character.
   * @returns {Boolean} True if the character is alphanumeric, false otherwise.
   */
  isAlphanumeric(c) {
    return this.alphanumeric.test(c) && c !== '_';
  }
 
  /**
   * Given an string, iterates over it and return the start position, end position
   * and length of each of the words, without tokenizing the string.
   * @param {String} str String to be processed.
   * @returns {Object[]} Array of positions of the words, with the start index,
   *                     end index, and length.
   */
  getWordPositions(str) {
    const scripts = [];
    for (let i = 0; i < str.length; i += 1) {
      scripts.push(Language.getTopScript(str.substr(i, 1)));
    }
    const strlen = str.length;
    const result = [];
    let lastIndex = 0;
    let currentIndex = 0;
    let atWhiteSpace = true;
    while (currentIndex < strlen) {
      if (!this.isAlphanumeric(str.charAt(currentIndex))) {
        if (!atWhiteSpace) {
          result.push({
            start: lastIndex,
            end: currentIndex - 1,
            len: currentIndex - lastIndex,
          });
          atWhiteSpace = true;
        }
      } else if (atWhiteSpace) {
        if (scripts[currentIndex][0] === 'cmn') {
          result.push({
            start: currentIndex,
            end: currentIndex,
            len: 1,
          });
          lastIndex = currentIndex;
          atWhiteSpace = true;
        } else {
          lastIndex = currentIndex;
          atWhiteSpace = false;
        }
      }
      currentIndex += 1;
    }
    if (!atWhiteSpace) {
      result.push({
        start: lastIndex,
        end: currentIndex - 1,
        len: currentIndex - lastIndex,
      });
    }
    return result;
  }
 
  /**
   * Given two strings, search best occurence of the second inside the first,
   * that is, the consecutive words of the first string that have less
   * levenshtein distance with the second one.
   * @param {String} str1 First string.
   * @param {String} str2 Second string.
   * @param {Object[]} words1 Array of positions of the words of the first string.
   *                          If not provided this will be built.
   * @returns {Object} Best occurence, expressed as the index of the first character,
   *                   index of the last character, levenshtein distance and accuracy.
   */
  getBestSubstring(str1, str2, words1) {
    const str1len = str1.length;
    const str2len = str2.length;
    if (str1len <= str2len) {
      const result = {
        start: 0,
        end: str1len - 1,
        len: str1len,
        levenshtein: this.getSimilarity(str1, str2),
      };
      result.accuracy = (str2len - result.levenshtein) / str2len;
      return result;
    }
    const wordPositions = words1 || this.getWordPositions(str1);
    const wordPositionsLen = wordPositions.length;
    const best = {
      start: 0,
      end: 0,
      len: 0,
      levenshtein: undefined,
      accuracy: 0,
    };
    for (let i = 0; i < wordPositionsLen; i += 1) {
      for (let j = i; j < wordPositionsLen; j += 1) {
        const str3 = str1.substring(
          wordPositions[i].start,
          wordPositions[j].end + 1
        );
        const levenshtein = this.getSimilarity(str3, str2);
        if (best.levenshtein === undefined || levenshtein < best.levenshtein) {
          best.levenshtein = levenshtein;
          best.start = wordPositions[i].start;
          best.end = wordPositions[j].end;
          best.len = best.end - best.start + 1;
        }
      }
    }
    best.accuracy = (str2len - best.levenshtein) / str2len;
    return best;
  }
 
  /**
   * Given two strings, search all the occurences of the second inside the first,
   * where the accuracy is at least as good as the threshold.
   * @param {String} str1 First string.
   * @param {String} str2 Second string.
   * @param {Object[]} words1 Array of positions of the words of the first string.
   *                          If not provided this will be built.
   * @returns {Object[]} List of occurences.
   */
  getBestSubstringList(str1, str2, words1, threshold = 1) {
    const str1len = str1.length;
    const str2len = str2.length;
    const result = [];
    if (str1len <= str2len) {
      const levenshtein = this.getSimilarity(str1, str2);
      const accuracy = (str2len - levenshtein) / str2len;
      if (accuracy >= threshold) {
        result.push({
          start: 0,
          end: str1len - 1,
          len: str1len,
          levenshtein,
          accuracy,
        });
      }
      return result;
    }
    const wordPositions = words1 || this.getWordPositions(str1);
    const wordPositionsLen = wordPositions.length;
    for (let i = 0; i < wordPositionsLen; i += 1) {
      for (let j = i; j < wordPositionsLen; j += 1) {
        const str3 = str1.substring(
          wordPositions[i].start,
          wordPositions[j].end + 1
        );
        const levenshtein = this.getSimilarity(str3, str2);
        const accuracy = (str2len - levenshtein) / str2len;
        if (accuracy >= threshold) {
          result.push({
            start: wordPositions[i].start,
            end: wordPositions[j].end,
            len: wordPositions[j].end - wordPositions[i].start + 1,
            levenshtein,
            accuracy,
          });
        }
      }
    }
    return result;
  }
 
  reduceEdges(edges, useMaxLength = true) {
    for (let i = 0, l = edges.length; i < l; i += 1) {
      const edge = edges[i];
      if (!edge.discarded) {
        for (let j = i + 1; j < l; j += 1) {
          const other = edges[j];
          if (!other.discarded) {
            if (other.start <= edge.end && other.end >= edge.start) {
              if (other.accuracy < edge.accuracy) {
                other.discarded = true;
              } else if (other.accuracy > edge.accuracy) {
                edge.discarded = true;
              } else if (
                (useMaxLength ||
                  other.entity === edge.entity ||
                  other.entity === 'number') &&
                other.len <= edge.len
              ) {
                other.discarded = true;
              } else if (
                (useMaxLength ||
                  other.entity === edge.entity ||
                  edge.entity === 'number') &&
                other.len > edge.len
              ) {
                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;
  }
 
  getEdgesFromEntity(
    str,
    entity,
    language,
    entityName,
    threshold = 1,
    srcWordPositions
  ) {
    const wordPositions = srcWordPositions || this.getWordPositions(str);
    const locale = entity.getLocaleRules
      ? entity.getLocaleRules(language)
      : entity[language];
    const result = [];
    if (!locale) {
      return result;
    }
    const optionKeys = Object.keys(locale);
    for (let i = 0, li = optionKeys.length; i < li; i += 1) {
      const optionName = optionKeys[i];
      const texts = locale[optionName];
      for (let j = 0, lj = texts.length; j < lj; j += 1) {
        const current = this.getBestSubstringList(
          str,
          texts[j],
          wordPositions,
          threshold
        );
        for (let k = 0, lk = current.length; k < lk; k += 1) {
          const item = current[k];
          item.option = optionName;
          item.sourceText = texts[j];
          item.entity = entityName || entity.name;
          item.utteranceText = str.substring(item.start, item.end + 1);
          result.push(item);
        }
      }
    }
    return this.reduceEdges(result);
  }
 
  /**
   * Given an utterance and an array of entities with options, search the
   * best option for each entity and return the results.
   * @param {String} str Utterance to retrieve entities.
   * @param {Object[]} entities Entities Array.
   * @param {String} locale Locale for the search.
   * @param {String[]} whitelist Whitelist of entity names for the search.
   */
  getEdgesFromEntities(str, entities, language, whitelist, threshold = 1) {
    const result = [];
    const wordPositions = this.getWordPositions(str);
    const entityKeys = Object.keys(entities);
    for (let i = 0, l = entityKeys.length; i < l; i += 1) {
      const entityName = entityKeys[i];
      if (!whitelist || whitelist.indexOf(entityName) !== -1) {
        const edges = this.getEdgesFromEntity(
          str,
          entities[entityName],
          language,
          entityName,
          threshold,
          wordPositions
        );
        edges.forEach(srcEdge => {
          const edge = srcEdge;
          result.push(edge);
        });
      }
    }
    return this.reduceEdges(result);
  }
}
 
module.exports = SimilarSearch;