NLP.js

An NLP library for building bots, with entity extraction, sentiment analysi...

README

NLPjs logo

NLP.js

Build Status Coverage Status NPM version NPM downloads Sonarcloud Status Maintainability Rating Reliability Rating Security Rating

If you're looking for the version 3 docs, you can find them here Version 3

"NLP.js" is a general natural language utility for nodejs. Currently supporting:

- Guess the language of a phrase
- Fast _Levenshtein_ distance of two strings
- Search the best substring of a string with less _Levenshtein_ distance to a given pattern.
- Get stemmers and tokenizers for several languages.
- Sentiment Analysis for phrases (with negation support).
- Named Entity Recognition and management, multi-language support, and acceptance of similar strings, so the introduced text does not need to be exact.
- Natural Language Processing Classifier, to classify an utterance into intents.
- NLP Manager: a tool able to manage several languages, the Named Entities for each language, the utterances, and intents for the training of the classifier, and for a given utterance return the entity extraction, the intent classification and the sentiment analysis. Also, it is able to maintain a Natural Language Generation Manager for the answers.
- 40 languages natively supported, 104 languages supported with BERT integration
- Any other language is supported through tokenization, even fantasy languages

Hybrid bot

New in version 4!


Version 4 is very different from previous versions. Before this version, NLP.js was a monolithic library. The big changes:

- Now the library is split into small independent packages.
- So every language has its own package
- It provides a plugin system, so you can provide your own plugins or replace the existing ones.
- It provides a container system for the plugins, settings for the plugins and also pipelines
- A pipeline is code defining how the plugins interact. Usually it is linear: there is an input into the plugin, and this generates the input for the next one. As an example, the preparation of a utterance (the process to convert the utterance to a hashmap of stemmed features) is now a pipeline like this: normalize -> tokenize -> removeStopwords -> stem -> arrToObj
- There is a simple compiler for the pipelines, but they can also be built using a modified version of javascript and python (compilers are also included as plugins, so other languages can be added as a plugin).
- NLP.js now includes connectors, a connector is understood to be something that has at least 2 methods: hear and say. Examples of connectors included: Console Connector, Microsoft Bot Framework Connector and a Direct Line Offline Connector (this one allows you to build a web chatbot using the Microsoft Webchat, but without having to deploy anything in Azure).
- Some plugins can be registered by language, so for different languages different plugins will be used. Also some plugins, like NLU, can be registered not only by language but also by domain (a functional set of intents that can be trained separately)
- As an example of per-language/domain plugins, a Microsoft LUIS NLU plugin is provided. You can configure your chatbot to use the NLU from NLP.js for some languages/domains, and LUIS for other languages/domains.
- Having plugins and pipelines makes it possible to write chatbots by only modifying the configuration and the pipelines file, without modifying the code.

TABLE OF CONTENTS



- QnA
  - Options
  - leven
  - NluNeural
- NLU
  - Brain NLU
  - Bayes NLU
  - Load/Save
  - Context
- Languages
  - English
  - Italian
  - Spanish

Installation


If you're looking to use NLP.js in your Node application, you can install via NPM like so:

  1. ``` sh
  2.     npm install node-nlp
  3. ```

React Native


There is a version of NLP.js that works in React Native, so you can build chatbots that can be trained and executed on the mobile even without the internet. You can install it via NPM:

  1. ``` sh
  2.     npm install node-nlp-rn
  3. ```

Some limitations:

- No Chinese
- The Japanese stemmer is not the complete one
- No Excel import
- No loading from a file, or saving to a file, but it can still import from JSON and export to JSON.

Example of use


You can see a great example of use in the folder [/examples/02-qna-classic](https://github.com/axa-group/nlp.js/tree/master/examples/02-qna-classic). This example is able to train the bot and save the model to a file, so when the bot is started again, the model is loaded instead of being trained again.

You can start to build your NLP from scratch with a few lines:

  1. ``` js
  2. const { NlpManager } = require('node-nlp');

  3. const manager = new NlpManager({ languages: ['en'], forceNER: true });
  4. // Adds the utterances and intents for the NLP
  5. manager.addDocument('en', 'goodbye for now', 'greetings.bye');
  6. manager.addDocument('en', 'bye bye take care', 'greetings.bye');
  7. manager.addDocument('en', 'okay see you later', 'greetings.bye');
  8. manager.addDocument('en', 'bye for now', 'greetings.bye');
  9. manager.addDocument('en', 'i must go', 'greetings.bye');
  10. manager.addDocument('en', 'hello', 'greetings.hello');
  11. manager.addDocument('en', 'hi', 'greetings.hello');
  12. manager.addDocument('en', 'howdy', 'greetings.hello');

  13. // Train also the NLG
  14. manager.addAnswer('en', 'greetings.bye', 'Till next time');
  15. manager.addAnswer('en', 'greetings.bye', 'see you soon!');
  16. manager.addAnswer('en', 'greetings.hello', 'Hey there!');
  17. manager.addAnswer('en', 'greetings.hello', 'Greetings!');

  18. // Train and save the model.
  19. (async() => {
  20.     await manager.train();
  21.     manager.save();
  22.     const response = await manager.process('en', 'I should go now');
  23.     console.log(response);
  24. })();
  25. ```

This produces the following result in a console:

  1. ``` sh
  2. { utterance: 'I should go now',
  3.   locale: 'en',
  4.   languageGuessed: false,
  5.   localeIso2: 'en',
  6.   language: 'English',
  7.   domain: 'default',
  8.   classifications:
  9.    [ { label: 'greetings.bye', value: 0.698219120207268 },
  10.      { label: 'None', value: 0.30178087979273216 },
  11.      { label: 'greetings.hello', value: 0 } ],
  12.   intent: 'greetings.bye',
  13.   score: 0.698219120207268,
  14.   entities:
  15.    [ { start: 12,
  16.        end: 14,
  17.        len: 3,
  18.        accuracy: 0.95,
  19.        sourceText: 'now',
  20.        utteranceText: 'now',
  21.        entity: 'datetime',
  22.        resolution: [Object] } ],
  23.   sentiment:
  24.    { score: 1,
  25.      comparative: 0.25,
  26.      vote: 'positive',
  27.      numWords: 4,
  28.      numHits: 2,
  29.      type: 'senticon',
  30.      language: 'en' },
  31.   actions: [],
  32.   srcAnswer: 'Till next time',
  33.   answer: 'Till next time' }
  34. ```

False Positives


By default, the neural network tries to avoid false positives. To achieve that, one of the internal processes is that words never seen by the network are represented as a feature that gives some weight to the None intent. So, if you try the previous example with "_I have to go_" it will return the None intent because 2 of the 4 words have never been seen while training.
If you don't want to avoid those false positives, and you feel more comfortable with classifications into the intents that you declare, then you can disable this behavior by setting the useNoneFeature to false:

  1. ``` js
  2. const manager = new NlpManager({ languages: ['en'], nlu: { useNoneFeature: false } });
  3. ```

Log Training Progress


You can also add a log progress, so you can trace what is happening during the training.
You can log the progress to the console:

  1. ``` js
  2. const nlpManager = new NlpManager({ languages: ['en'], nlu: { log: true } });
  3. ```

Or you can provide your own log function:

  1. ``` js
  2. const logfn = (status, time) => console.log(status, time);
  3. const nlpManager = new NlpManager({ languages: ['en'], nlu: { log: logfn } });
  4. ```

Contributing


You can read the guide for how to contribute at Contributing.

Contributors

Contributors

Made with contributors-img.

Code of Conduct


You can read the Code of Conduct at Code of Conduct.

Who is behind it?


This project is developed by AXA Group Operations Spain S.A.

If you need to contact us, you can do it at the email opensource@axa.com

License


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.