How to use node-nlp - 8 common examples

To help you get started, we’ve selected a few node-nlp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ndabAP / vue-sails-example / backend / api / controllers / help / HelpController.js View on Github external
postHelp: (req, res) => {
    const {message} = req.allParams()

    const manager = new NlpManager({languages: ['en']})

    let timeout = 3000
    if (fs.existsSync('./.tmp/model.nlp')) {
      manager.load('./.tmp/model.nlp')
    } else {
      timeout = 0
      // Adds the utterances and intents for the NLP
      manager.addDocument('en', 'Say about you', 'agent.acquaintance')
      manager.addDocument('en', 'Why are you here', 'agent.acquaintance')
      manager.addDocument('en', 'What is your personality',
        'agent.acquaintance')
      manager.addDocument('en', 'Describe yourself', 'agent.acquaintance')
      manager.addDocument('en', 'Tell me about yourself', 'agent.acquaintance')
      manager.addDocument('en', 'Tell me about you', 'agent.acquaintance')
      manager.addDocument('en', 'What are you', 'agent.acquaintance')
      manager.addDocument('en', 'Who are you', 'agent.acquaintance')
github brian-ai / core / src / services / natural / index.js View on Github external
/* eslint-disable no-unused-expressions */
import { BayesClassifier } from 'natural'
import { NlpManager, NluManager } from 'node-nlp'
import logger from 'hoopa-logger'
import baseKnowledge from '../../brain/knowledge'

const LanguageProcessor = new NlpManager({ languages: 'en' })
const UnderstandingProcessor = new NluManager({ languages: 'en' })

const NLP = {
	Bayes: new BayesClassifier(),
	LanguageProcessor,
	UnderstandingProcessor,
	trainModel: (newKnowledge = null, bayes, manager) => {
		logger.info('Cognitive analysis (NLP & NLU), basic training...')
		const trainingContext = baseKnowledge.natural

		if (newKnowledge) {
			newKnowledge.map(token => trainingContext.push(token))
		}

		trainingContext.map(token => {
			UnderstandingProcessor.addDocument('en', token.input, token.class)
github brian-ai / core / src / brain / reactions / queue-channels / conversation.js View on Github external
const conversationHandler = async ({ content }, LanguageProcessor) => {
	const context = new ConversationContext()
	const { data: sentence } = JSON.parse(content)
	logger.info(`Conversation control: received ${content}`)
	// Local NLP analysis
	logger.info(`NLP Analysis locally for ${content}`)
	const localProcessedSentence = await LanguageProcessor.process(
		'en',
		sentence,
		context
	)
	const { answer, classifications } = localProcessedSentence
	const suggestedClassification = extractClassification(classifications)
	// Trigger intents
	if (suggestedClassification && suggestedClassification !== 'None') {
		processIntentType(suggestedClassification, sentence)

		if (answer) {
github leon-ai / leon / server / src / core / ner.js View on Github external
return new Promise(async (resolve, reject) => {
      log.title('NER')
      log.info('Searching for entities...')

      // Need to instanciate on the fly to flush entities
      this.nerManager = new NerManager()

      const { entities, classification } = obj
      // Remove end-punctuation and add an end-whitespace
      const query = `${string.removeEndPunctuation(obj.query)} `
      const expressionsObj = JSON.parse(fs.readFileSync(expressionsFilePath, 'utf8'))
      const { module, action } = classification
      const promises = []

      // Verify the action has entities
      if (typeof expressionsObj[module][action].entities !== 'undefined') {
        const actionEntities = expressionsObj[module][action].entities

        /**
         * Browse action entities
         * Dynamic injection of the action entities depending of the entity type
         */
github brian-ai / core / src / services / natural / index.js View on Github external
/* eslint-disable no-unused-expressions */
import { BayesClassifier } from 'natural'
import { NlpManager, NluManager } from 'node-nlp'
import logger from 'hoopa-logger'
import baseKnowledge from '../../brain/knowledge'

const LanguageProcessor = new NlpManager({ languages: 'en' })
const UnderstandingProcessor = new NluManager({ languages: 'en' })

const NLP = {
	Bayes: new BayesClassifier(),
	LanguageProcessor,
	UnderstandingProcessor,
	trainModel: (newKnowledge = null, bayes, manager) => {
		logger.info('Cognitive analysis (NLP & NLU), basic training...')
		const trainingContext = baseKnowledge.natural

		if (newKnowledge) {
			newKnowledge.map(token => trainingContext.push(token))
		}

		trainingContext.map(token => {
			UnderstandingProcessor.addDocument('en', token.input, token.class)
			manager.addDocument('en', token.input, token.class)
github leon-ai / leon / scripts / train.js View on Github external
export default () => new Promise(async (resolve, reject) => {
  const { argv } = process
  const packagesDir = 'packages'
  const expressionsClassifier = 'server/src/data/expressions/classifier.json'
  let type = (argv[2]) ? argv[2].toLowerCase() : 'expressions'
  let lang = ''

  if (type.indexOf(':') !== -1) {
    [type, lang] = type.split(':')
  } else {
    lang = langs[process.env.LEON_LANG].short.toLowerCase().substr(0, 2)
  }

  try {
    if (type === 'expressions') {
      let manager = new NlpManager({ languages: ['en'] })

      if (lang !== 'en') {
        manager = new NlpManager({ languages: lang })
      }
      const packages = fs.readdirSync(packagesDir)
        .filter(entity =>
          fs.statSync(path.join(packagesDir, entity)).isDirectory())
      let expressionsObj = { }

      for (let i = 0; i < packages.length; i += 1) {
        log.info(`Training "${string.ucfirst(packages[i])}" package modules expressions...`)

        expressionsObj = JSON.parse(fs.readFileSync(`${packagesDir}/${packages[i]}/data/expressions/${lang}.json`, 'utf8'))

        const modules = Object.keys(expressionsObj)
        for (let j = 0; j < modules.length; j += 1) {
github leon-ai / leon / scripts / train.js View on Github external
const expressionsClassifier = 'server/src/data/expressions/classifier.json'
  let type = (argv[2]) ? argv[2].toLowerCase() : 'expressions'
  let lang = ''

  if (type.indexOf(':') !== -1) {
    [type, lang] = type.split(':')
  } else {
    lang = langs[process.env.LEON_LANG].short.toLowerCase().substr(0, 2)
  }

  try {
    if (type === 'expressions') {
      let manager = new NlpManager({ languages: ['en'] })

      if (lang !== 'en') {
        manager = new NlpManager({ languages: lang })
      }
      const packages = fs.readdirSync(packagesDir)
        .filter(entity =>
          fs.statSync(path.join(packagesDir, entity)).isDirectory())
      let expressionsObj = { }

      for (let i = 0; i < packages.length; i += 1) {
        log.info(`Training "${string.ucfirst(packages[i])}" package modules expressions...`)

        expressionsObj = JSON.parse(fs.readFileSync(`${packagesDir}/${packages[i]}/data/expressions/${lang}.json`, 'utf8'))

        const modules = Object.keys(expressionsObj)
        for (let j = 0; j < modules.length; j += 1) {
          const module = modules[j]
          const actions = Object.keys(expressionsObj[module])
github leon-ai / leon / server / src / core / nlu.js View on Github external
return new Promise((resolve, reject) => {
      if (!fs.existsSync(classifierFile)) {
        log.title('NLU')
        reject({ type: 'warning', obj: new Error('The expressions classifier does not exist, please run: npm run train expressions') })
      } else {
        log.title('NLU')

        try {
          const data = fs.readFileSync(classifierFile, 'utf8')
          const nlpManager = new NlpManager()

          nlpManager.import(data)
          this.classifier = nlpManager

          log.success('Classifier loaded')
          resolve()
        } catch (err) {
          this.brain.talk(`${this.brain.wernicke('random_errors')}! ${this.brain.wernicke('errors', 'nlu', { '%error%': err.message })}.`)
          this.brain.socket.emit('is-typing', false)

          reject({ type: 'error', obj: err })
        }
      }
    })
  }

node-nlp

Library for NLU (Natural Language Understanding) done in Node.js

MIT
Latest version published 3 days ago

Package Health Score

74 / 100
Full package analysis