├── ulis ├── tools │ ├── data │ │ ├── hebrew.out.csv │ │ └── hebrew.csv │ ├── config │ │ ├── dev.private.json │ │ └── index.js │ ├── test.js │ ├── bulkTranslateAndTrain.js │ └── translateAndTrainBot.js ├── index.js ├── lib │ ├── luisScorer.js │ └── ulis.js └── package.json ├── .gitignore ├── LICENSE └── README.md /ulis/tools/data/hebrew.out.csv: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ulis/index.js: -------------------------------------------------------------------------------- 1 | module.exports.ulis = require('./lib/ulis'); -------------------------------------------------------------------------------- /ulis/tools/config/dev.private.json: -------------------------------------------------------------------------------- 1 | { 2 | "TRANSLATE_CLIENT_ID":"HebrewBot", 3 | "TRANSLATE_CLIENT_SECRET":"WNWSX9uWuY+BLUNdhZsrYHgZQ+UsawuhkNCeO1ZO5Nc=", 4 | "TRANSLATE_CLIENT_API_KEY":"", 5 | "LUIS_ENDPOINT":"https://api.projectoxford.ai/luis/v1/application?id=eee512ef-0e31-45ac-bd61-c5b97c71ae38&subscription-key=c80cd9f24783494ea76a5ab9378f340f&q=" 6 | } -------------------------------------------------------------------------------- /ulis/tools/test.js: -------------------------------------------------------------------------------- 1 | var ulis = require('../lib/ulis'); 2 | var config = require('./config'); 3 | 4 | //setup ulisClient 5 | var ulisClient = new ulis.getClient({ 6 | lang:'he', 7 | bingTranslate_clientId: config.get('TRANSLATE_CLIENT_ID'), 8 | bingTranslate_secret: config.get('TRANSLATE_CLIENT_SECRET'), 9 | luisURL: config.get('LUIS_ENDPOINT') 10 | }); 11 | 12 | ulisClient.query('אפשר לקבוע תור למחר', (err, ulisRes) => { 13 | if (err) return console.log(err.message); 14 | console.log(`Translated As: " ${ulisRes.translatedText} "\n\nLUIS Intent: " ${ulisRes.intent} " \n\nLUIS Entities \n\n" ${JSON.stringify(ulisRes.entities)}`); 15 | }); 16 | -------------------------------------------------------------------------------- /ulis/tools/config/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Please refer to the dev.sample.json file. 3 | * Copy this file and create a new file named "dev.private.json". 4 | * Fill in the details for the features you'de like to support. 5 | * You don't have to fill in all settings, but leave those you're not using blank. 6 | */ 7 | 8 | var nconf = require('nconf'); 9 | var path = require('path'); 10 | 11 | var envFile = ''; 12 | if (process.env.NODE_ENV == 'test') { 13 | envFile = path.join(__dirname, 'test.private.json'); 14 | } else { 15 | envFile = path.join(__dirname, 'dev.private.json'); 16 | } 17 | 18 | var config = nconf.env().file({ file: envFile }); 19 | 20 | module.exports = config; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | -------------------------------------------------------------------------------- /ulis/lib/luisScorer.js: -------------------------------------------------------------------------------- 1 | var _ = require('underscore'); 2 | var request = require('request-promise'); 3 | var Promise = require('promise'); 4 | 5 | // Retreive the first intent from a LUIS api 6 | function scoreIntent(modelUrl, text, threshold) { 7 | 8 | threshold = threshold || 0; 9 | return new Promise((resolve, reject) => { 10 | request(modelUrl + encodeURIComponent(text),{ json: true}) 11 | .then((result)=> { 12 | var json = result; 13 | 14 | if (!json || !json.intents || !json.intents.length) return resolve(); 15 | 16 | // In case when minumum score is required, enforce minimum score 17 | if (json.intents[0].score < threshold) return resolve(); 18 | 19 | var intent = json.intents[0]; 20 | intent.entities = json.entities; 21 | return resolve(intent); 22 | }) 23 | .catch(reject); 24 | }); 25 | } 26 | 27 | module.exports = { 28 | scoreIntent: scoreIntent 29 | }; -------------------------------------------------------------------------------- /ulis/tools/bulkTranslateAndTrain.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs'); 2 | var path = require('path'); 3 | var lineReader = require('line-reader'); 4 | 5 | var filepath = path.join(__dirname, 'hebrew.csv'); 6 | var output = path.join(__dirname, 'hebrew.out.csv'); 7 | 8 | var outStream = fs.createWriteStream(output); 9 | 10 | var ulis = require('../lib/ulis'); 11 | var config = require('./config'); 12 | 13 | //setup ulisClient 14 | var ulisClient = new ulis.getClient({ 15 | lang:'he', 16 | bingTranslate_clientId: config.get('TRANSLATE_CLIENT_ID'), 17 | bingTranslate_secret: config.get('TRANSLATE_CLIENT_SECRET'), 18 | luisURL: config.get('LUIS_ENDPOINT') 19 | }); 20 | 21 | lineReader.eachLine(filepath,(line, last, cb) => { 22 | 23 | ulisClient.query(line, (err, ulisResponse) => { 24 | if (err) { 25 | console.error(`error translating: ${err.message}`); 26 | return cb(err); 27 | } 28 | 29 | outStream.write(`${line}, ${ulisResponse.translatedText}\n`, () => { 30 | if (last) { 31 | outStream.close(); 32 | console.log('done'); 33 | } 34 | else return cb(); 35 | }); 36 | }); 37 | }); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Microsoft Partner Catalyst Team 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ulis/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ulis", 3 | "version": "1.0.0", 4 | "description": "A wrapper for the microsoft luis cognitive that provides universal language support (after training) using the bing translate api", 5 | "main": "ulis.js", 6 | "scripts": { 7 | "test": "node tools/test.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/CatalystCode/Universal-Language-Intelligence-Service.git" 12 | }, 13 | "keywords": [ 14 | "luis", 15 | "nlp", 16 | "entity", 17 | "extraction", 18 | "intent", 19 | "recognition" 20 | ], 21 | "readme": "../README.md", 22 | "author": "Ari Bornstein", 23 | "license": "MIT", 24 | "bugs": { 25 | "url": "https://github.com/CatalystCode/Universal-Language-Intelligence-Service/issues" 26 | }, 27 | "dependencies": { 28 | "botbuilder": "3.4.4", 29 | "chai": "^3.5.0", 30 | "express": "^4.14.0", 31 | "extend": "^3.0.0", 32 | "franc": "^2.0.0", 33 | "jsep": "^0.3.0", 34 | "langs": "^1.0.2", 35 | "line-reader": "^0.4.0", 36 | "mocha": "^3.2.0", 37 | "moment": "^2.17.0", 38 | "moments": "0.0.2", 39 | "mstranslator": "^2.1.0", 40 | "nconf": "^0.8.4", 41 | "promise": "^7.1.1", 42 | "request": "^2.74.0", 43 | "request-promise": "^4.1.1", 44 | "restify": "^4.3.0", 45 | "strformat": "0.0.7", 46 | "superagent": "^3.1.0", 47 | "underscore": "^1.8.3", 48 | "uuid": "^3.0.0" 49 | }, 50 | "homepage": "https://github.com/CatalystCode/Universal-Language-Intelligence-Service#readme" 51 | } 52 | -------------------------------------------------------------------------------- /ulis/tools/translateAndTrainBot.js: -------------------------------------------------------------------------------- 1 | var restify = require('restify'); 2 | var builder = require('botbuilder'); 3 | var ulis = require('../lib/ulis'); 4 | var config = require('./config'); 5 | 6 | //========================================================= 7 | // Bot Setup 8 | //========================================================= 9 | 10 | //setup ulisClient 11 | var ulisClient = new ulis.getClient({ 12 | lang:'he', 13 | bingTranslate_clientId: config.get('TRANSLATE_CLIENT_ID'), 14 | bingTranslate_secret: config.get('TRANSLATE_CLIENT_SECRET'), 15 | luisURL: config.get('LUIS_ENDPOINT') 16 | }); 17 | 18 | // Setup Restify Server 19 | var server = restify.createServer(); 20 | server.listen(process.env.port || process.env.PORT || 3978, () => { 21 | console.log('%s listening to %s', server.name, server.url); 22 | }); 23 | 24 | // Create chat bot 25 | var connector = new builder.ChatConnector({ 26 | appId: process.env.MICROSOFT_APP_ID, 27 | appPassword: process.env.MICROSOFT_APP_PASSWORD 28 | }); 29 | var bot = new builder.UniversalBot(connector); 30 | server.post('/api/messages', connector.listen()); 31 | 32 | //========================================================= 33 | // Bots Dialogs 34 | //========================================================= 35 | 36 | bot.dialog('/', [ 37 | (session) => { 38 | builder.Prompts.text(session, 'שלום איך אני יכול לעזור?'); 39 | }, 40 | //translate 41 | (session, results) => { 42 | ulisClient.query(results.response, (err, ulisRes) => { 43 | if (err) { 44 | session.send(err.message); 45 | return session.endDialog(); 46 | } 47 | session.send(`Translated As: " ${ulisRes.translatedText} "\n\nLUIS Intent: " ${ulisRes.intent} " \n\nLUIS Entities \n\n" ${JSON.stringify(ulisRes.entities)}`); 48 | session.endDialog(); 49 | }); 50 | } 51 | 52 | ]); -------------------------------------------------------------------------------- /ulis/tools/data/hebrew.csv: -------------------------------------------------------------------------------- 1 | אני רוצה לקבוע פגישה 2 | אני רוצה לקבוע נסיעת מבחן 3 | אני רוצה לקבוע נסיעת מבחן למחר 4 | אפשר לקבוע נסיעת מבחן למחר? 5 | מתי אפשר לקבוע נסיעת מבחן? 6 | מתי אפשר לקבוע פגישה? 7 | אני מעוניין לתאם נסיעת מבחן לסיאט ליאונה 8 | האם אפשר לתאם נסיעת מבחן / פגישה לשבוע הבא? 9 | מבקש לקבוע פגישה לשבוע הבא בשעות הערב / בוקר / צהריים 10 | אפשר לקבוע נסיעת מבחן בשבוע הבא באזור תל אביב? 11 | באיזה שעות אפשר לקבוע פגישה / נסיעת מבחן? 12 | האם אפשר לקבוע נסיעת מבחן למחר ב18:00? 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 | באיזה עיר הפגישה שלי -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Universal Language Intelligence Service 2 | A wrapper for the Microsoft LUIS cognitive that provides universal language support (after training) using the bing translate api 3 | 4 | The .NET port can be found here: [ULIS.NET](https://github.com/peterbozso/ULIS.NET) 5 | 6 | ## Pre-Requisites 7 | - LUIS Account 8 | - Bing Translate Key 9 | - Add keys to the configuration file 10 | 11 | ## Installation 12 | 13 | $ npm install ulis 14 | 15 | ## To Train Language Model (See Provided Hebrew Example) 16 | 17 | 1. Upload natural language samples to LUIS using either the testTrainBot or the Batch insertion tool 18 | 2. Tag translation intents and entities 19 | 20 | ## To Use 21 | ```js 22 | var ulis = require('ulis'); 23 | 24 | //Setup ulisClient using client id and secret 25 | var ulisClient = new ulis.getClient({ 26 | lang:'he', 27 | bingTranslate_clientId: 'TRANSLATE_CLIENT_ID', 28 | bingTranslate_secret: 'TRANSLATE_CLIENT_SECRET', 29 | luisURL: 'LUIS_ENDPOINT' 30 | }); 31 | 32 | //Or setup ulisClient using translate api_key from azure portal 33 | var ulisClient = new ulis.getClient({ 34 | lang:'he', 35 | bingTranslate_api_key:'TRANSLATE_API_KEY', 36 | luisURL: 'LUIS_ENDPOINT' 37 | }); 38 | 39 | //Make a query 40 | ulisClient.query('אפשר לקבוע תור למחר', (err, ulisRes) => { 41 | if (err) return console.log(err.message); 42 | console.log(`Translated As: " ${ulisRes.translatedText} "\n\nLUIS Intent: " ${ulisRes.intent} " \n\nLUIS Entities \n\n" ${JSON.stringify(ulisRes.entities)}`); 43 | }); 44 | 45 | ``` 46 | 47 | Optionally, you can specify the format of the text being translated. The supported formats are `text/plain` (default) and `text/html`. 48 | It is also possible to execute a function on the translated text before it is sent to LUIS. This is especially helpful if you want to exclude content from translation, see http://docs.microsofttranslator.com/text-translate.html#excluding-content-from-translation. 49 | 50 | Example: 51 | 52 | ```js 53 | var ulisClient = new ulis.getClient({ 54 | lang:'he', 55 | bingTranslate_api_key:'TRANSLATE_API_KEY', 56 | luisURL: 'LUIS_ENDPOINT', 57 | 58 | // set the format 59 | contentType: 'text/html', 60 | 61 | // pass a function that is applied to the translated text and removes the HTML 62 | // from text enclosed with
text<\/div> 63 | replaceInTranslation: text => text.replace(/
(.*?)<\/div>/g, ' $1') 64 | }); 65 | 66 | ``` 67 | -------------------------------------------------------------------------------- /ulis/lib/ulis.js: -------------------------------------------------------------------------------- 1 | //ulis is the Universal Langauge Intent Service wrapper for microsoft luis using the bing translate api to use see online documentation 2 | 3 | var MsTranslator = require('mstranslator'); 4 | var luisScorer = require('./luisScorer') 5 | var franc = require('franc'); 6 | var langs = require('langs'); 7 | 8 | function getClient(opts) { 9 | 10 | var lang = opts.lang; 11 | if (!lang) throw new Error('Please provide a model language such as he'); 12 | 13 | var translateClient; 14 | 15 | if (opts.bingTranslate_api_key){ 16 | translateClient = new MsTranslator({ 17 | api_key: opts.bingTranslate_api_key // use this for the new token API. 18 | }, true); 19 | } 20 | else if (!opts.bingTranslate_clientId || !opts.bingTranslate_secret) throw new Error('Please provide bing translate clientId and secret or api_key') 21 | else { 22 | translateClient = new MsTranslator({ 23 | client_id: opts.bingTranslate_clientId, 24 | client_secret: opts.bingTranslate_secret 25 | }, true); 26 | } 27 | var luisURL = opts.luisURL; 28 | if (!luisURL) throw new Error('Please provide a LUIS model optimized for the provided language'); 29 | 30 | 31 | function query(text, cb) { 32 | 33 | if (!cb) return new Error('Please provide a callback to process the returned response'); 34 | if (!text) return cb(new Error('Please provide a text')); 35 | 36 | //confirm language: requires conversion between iso-639-3 (lang3) and iso-639-1 37 | var lang3 = langs.where("1", lang)['3']; 38 | var detectedLang = franc.all(text,{'whitelist' : ['eng',lang3], 'minLength': 3})[0][0]; 39 | console.log(`${detectedLang} detected`); 40 | if (detectedLang != lang3 ){ 41 | if ( detectedLang != 'eng'){ 42 | return cb(new Error('Sorry we don\'t support that language at the moment.')); 43 | } 44 | } 45 | 46 | translate(text, (err, translatedText) => { 47 | if (err) return cb(err); 48 | sendToLuis(translatedText, (err, luisResponse) => { 49 | if (err) return cb(err); 50 | luisResponse.translatedText = translatedText; 51 | return cb(null, luisResponse); 52 | }); 53 | }); 54 | } 55 | 56 | function translate(text, cb) { 57 | 58 | var params = { 59 | text: text, 60 | from: lang, 61 | to: 'en', 62 | contentType: opts.contentType ? opts.contentType : 'text/plain', 63 | }; 64 | 65 | console.log(`Translating: ${text}`); 66 | 67 | translateClient.translate(params, (err, translation) => { 68 | if (err) { 69 | console.error(`Error translating: ${err.message}`); 70 | return cb(err); 71 | } 72 | 73 | if (opts.replaceInTranslation) { 74 | translation = opts.replaceInTranslation(translation); 75 | } 76 | 77 | //write textToTranslate and translation to csv 78 | console.log(`Translating completed: ${text}:${translation}`); 79 | return cb(null, translation); 80 | }); 81 | 82 | } 83 | 84 | function sendToLuis(text, cb) { 85 | console.log(`Sending to Luis: ${text}`); 86 | 87 | luisScorer.scoreIntent(luisURL,text) 88 | .then((luisResponse) => { 89 | console.log(`Sending to Luis completed: ${text}`); 90 | return cb(null, luisResponse); 91 | }) 92 | .catch(err => { 93 | console.error(`Error sending to LUIS: ${err.message}`); 94 | return cb(err) 95 | }); 96 | } 97 | 98 | return { 99 | query 100 | } 101 | 102 | } 103 | 104 | module.exports = { 105 | getClient 106 | }; 107 | --------------------------------------------------------------------------------