All files / lib/sentiment sentiment-analyzer.js

100% Statements 54/54
89.19% Branches 33/37
100% Functions 5/5
100% Lines 54/54
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                                              31x                             101x 101x 4x   101x 101x   101x 99x   45x 45x   12x 12x   1x 1x   9x 9x   1x 1x   3x 3x   28x     101x 5x   101x             101x     101x     101x   101x   28x   101x       15x 15x         15x 15x 238514x           101x   101x   38x                 315x     315x 124x                 191x 191x 191x 191x 1021x 1021x 3x 3x 1018x 76x 76x     191x                     31x  
/*
 * 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 NlpUtil = require('../nlp/nlp-util');
 
/**
 * Class for a Sentiment Analyzer.
 * Sentiment analysis can use 3 different type of files:
 * - AFINN
 * - Senticon
 * - Pattern
 */
class SentimentAnalyzer {
  /**
   * Constructor of the class.
   * @param {Object} settings Settings to initialize the instance.
   */
  constructor(settings) {
    this.settings = settings || {};
    if (!this.settings.language) {
      this.settings.language = 'en';
    }
    Eif (!this.settings.tokenizer) {
      this.settings.tokenizer = NlpUtil.getTokenizer(this.settings.language);
    }
    if (!this.settings.type) {
      switch (this.settings.language) {
        case 'en':
          this.settings.type = 'senticon';
          break;
        case 'es':
          this.settings.type = 'senticon';
          break;
        case 'it':
          this.settings.type = 'pattern';
          break;
        case 'fr':
          this.settings.type = 'pattern';
          break;
        case 'nl':
          this.settings.type = 'pattern';
          break;
        case 'de':
          this.settings.type = 'senticon';
          break;
        default:
          this.settings.type = 'senticon';
      }
    }
    if (!SentimentAnalyzer.loadedFiles) {
      SentimentAnalyzer.loadedFiles = {};
    }
    this.loadVocabulary();
  }
 
  /**
   * Load the vocabulary and negation files based on the type of files and language.
   */
  loadVocabulary() {
    this.vocabularyFileName = `./languages/${this.settings.language}/${
      this.settings.type
    }_${this.settings.language}.json`;
    this.negationFileName = `./languages/${this.settings.language}/negations_${
      this.settings.language
    }.json`;
    try {
      // eslint-disable-next-line
      this.vocabulary = require(this.vocabularyFileName);
    } catch (ex) {
      this.vocabulary = undefined;
    }
    if (
      this.vocabulary &&
      !SentimentAnalyzer.loadedFiles[this.vocabularyFileName]
    ) {
      SentimentAnalyzer.loadedFiles[this.vocabularyFileName] = true;
      Eif (
        this.settings.type === 'senticon' ||
        this.settings.type === 'pattern'
      ) {
        const propertyName =
          this.settings.type === 'senticon' ? 'pol' : 'polarity';
        Object.keys(this.vocabulary).forEach(word => {
          this.vocabulary[word] = Number.parseFloat(
            this.vocabulary[word][propertyName]
          );
        });
      }
    }
    try {
      // eslint-disable-next-line
      this.negations = require(this.negationFileName).words || [];
    } catch (ex) {
      this.negations = [];
    }
  }
 
  /**
   * Given an utterance, return the sentiment analysis of the utterance.
   * @param {String} utterance Utterance to be analyzed.
   */
  getSentiment(utterance) {
    const words = Array.isArray(utterance)
      ? utterance
      : this.settings.tokenizer.tokenize(utterance);
    if (!this.vocabulary) {
      return {
        score: 0,
        numWords: words.length,
        numHits: 0,
        comparative: 0,
        type: this.settings.type,
        language: this.settings.language,
      };
    }
    let score = 0;
    let negator = 1;
    let nrHits = 0;
    words.forEach(token => {
      const lowerCased = token.toLowerCase();
      if (this.negations.indexOf(lowerCased) !== -1) {
        negator = -1;
        nrHits += 1;
      } else if (this.vocabulary[lowerCased] !== undefined) {
        score += negator * this.vocabulary[lowerCased];
        nrHits += 1;
      }
    });
    return {
      score,
      numWords: words.length,
      numHits: nrHits,
      comparative: score / words.length,
      type: this.settings.type,
      language: this.settings.language,
    };
  }
}
 
module.exports = SentimentAnalyzer;