diff --git a/packages/lu-cli/src/commands/luis/build.ts b/packages/lu-cli/src/commands/luis/build.ts index d92e1af13..2883b996c 100644 --- a/packages/lu-cli/src/commands/luis/build.ts +++ b/packages/lu-cli/src/commands/luis/build.ts @@ -3,19 +3,17 @@ * Licensed under the MIT License. */ -/* eslint-disable no-multiple-empty-lines, node/no-missing-require, complexity, prefer-const, new-cap, unicorn/prefer-spread, no-lonely-if, comma-dangle, no-else-return */ -import {Command, flags, CLIError} from '@microsoft/bf-cli-command' -import {LuBuildCore} from './../../../node_modules/@microsoft/bf-lu/src/parser/lubuild/core' -import {Settings} from './../../../node_modules/@microsoft/bf-lu/src/parser/lubuild/settings' -import {MultiLanguageRecognizer} from './../../../node_modules/@microsoft/bf-lu/src/parser/lubuild/multi-language-recognizer' -import {Recognizer} from './../../../node_modules/@microsoft/bf-lu/src/parser/lubuild/recognizer' +import {Command, flags} from '@microsoft/bf-cli-command' +import * as file from './../../utils/filehelper' + const path = require('path') const fs = require('fs-extra') -const delay = require('delay') -const fileHelper = require('./../../utils/filehelper') -const fileExtEnum = require('./../../../node_modules/@microsoft/bf-lu/src/parser/utils/helpers').FileExtTypeEnum -const LuisBuilder = require('./../../../node_modules/@microsoft/bf-lu/src/parser/luis/luisBuilder') -const Content = require('./../../../node_modules/@microsoft/bf-lu/src/parser/lu/lu') +const fileExtEnum = require('./../../../node_modules/@microsoft/bf-lu/lib/parser/utils/helpers').FileExtTypeEnum +const Content = require('./../../../node_modules/@microsoft/bf-lu/lib/parser/lu/lu') +const Settings = require('./../../../node_modules/@microsoft/bf-lu/lib/parser/lubuild/settings') +const MultiLanguageRecognizer = require('./../../../node_modules/@microsoft/bf-lu/lib/parser/lubuild/multi-language-recognizer') +const Recognizer = require('./../../../node_modules/@microsoft/bf-lu/lib/parser/lubuild/recognizer') +const Builder = require('./../../../node_modules/@microsoft/bf-lu/lib/parser/lubuild/builder').Builder export default class LuisBuild extends Command { static description = 'Build lu files to train and publish luis applications' @@ -28,279 +26,106 @@ export default class LuisBuild extends Command { help: flags.help({char: 'h'}), in: flags.string({char: 'i', description: 'Lu file or folder'}), authoringKey: flags.string({description: 'LUIS authoring key', required: true}), - botName: flags.string({description: 'Bot name', required: true}), + botName: flags.string({description: 'Bot name'}), out: flags.string({description: 'Output location'}), - culture: flags.string({description: 'Culture code for the content. Infer from .lu if available. Defaults to en-us'}), + defaultCulture: flags.string({description: 'Culture code for the content. Infer from .lu if available. Defaults to en-us'}), region: flags.string({description: 'LUIS authoring region'}), suffix: flags.string({description: 'Environment name as a suffix identifier to include in LUIS app name'}), force: flags.boolean({char: 'f', description: 'Force write dialog and settings files', default: false}), dialog: flags.boolean({description: 'Write out .dialog files', default: false}), fallbackLocale: flags.string({description: 'Locale to be used at the fallback if no locale specific recognizer is found. Only valid if --dialog is set'}), + luConfig: flags.string({description: 'Path to config for lu build'}), + log: flags.boolean({description: 'write out log messages to console', default: false}), } async run() { const {flags} = this.parse(LuisBuild) - // Check stdin or in parameter - const stdin = await this.readStdin() - if (!stdin && !flags.in) { - throw new CLIError('Missing input. Please use stdin or pass a file or folder location with --in flag') + flags.stdin = await this.readStdin() + + let files: string[] = [] + if (flags.luConfig) { + const configFilePath = path.resolve(flags.luConfig) + if (fs.existsSync(configFilePath)) { + const configObj = JSON.parse(await file.getContentFromFile(configFilePath)) + if (configObj.name && configObj.name !== '') flags.botName = configObj.name + if (configObj.defaultLanguage && configObj.defaultLanguage !== '') flags.defaultCulture = configObj.defaultLanguage + if (configObj.deleteOldVersion) flags.deleteOldVersion = true + if (configObj.out && configObj.out !== '') flags.out = configObj.out + if (configObj.writeDialogFiles) flags.dialog = true + if (configObj.models && configObj.models.length > 0) { + files = configObj.models.map((m: string) => path.resolve(m)) + } + } + } + + if (!flags.stdin && !flags.in && files.length === 0) { + throw new Error('Missing input. Please use stdin or pass a file or folder location with --in flag') + } + + if (!flags.botName) { + throw new Error('Missing bot name. Please pass bot name with --botName flag') } - flags.culture = flags.culture && flags.culture !== '' ? flags.culture : 'en-us' + flags.defaultCulture = flags.defaultCulture && flags.defaultCulture !== '' ? flags.defaultCulture : 'en-us' flags.region = flags.region && flags.region !== '' ? flags.region : 'westus' flags.suffix = flags.suffix && flags.suffix !== '' ? flags.suffix : 'development' flags.fallbackLocale = flags.fallbackLocale && flags.fallbackLocale !== '' ? flags.fallbackLocale : 'en-us' - const multiRecognizers = new Map() - let settings: Settings - const recognizers: Recognizer[] = [] - const luContents: Array = [] - let dialogFilePath = process.cwd() - - // luis api TPS which means 5 concurrent transactions to luis api in 1 second - // can set to other value if switched to a higher TPS(transaction per second) key - const luisApiTps = 5 + // create builder class + const builder = new Builder((input: string) => { + if (flags.log) this.log(input) + }) - // set luis call delay duration to 1100 millisecond because 1000 can hit corner case of rate limit - const delayDuration = 1100 + let luContents: any[] = [] + let recognizers = new Map() + let multiRecognizers = new Map() + let settings = new Map() - if (stdin && stdin !== '') { + if (flags.stdin && flags.stdin !== '') { + // load lu content from stdin and create default recognizer, multiRecognier and settings this.log('Load lu content from stdin') - luContents.push(new Content(stdin, 'stdin', true, flags.culture, path.join(process.cwd(), 'stdin'))) + const content = new Content(flags.stdin, 'stdin', true, flags.defaultCulture, path.join(process.cwd(), 'stdin')) + luContents.push(content) multiRecognizers.set('stdin', new MultiLanguageRecognizer(path.join(process.cwd(), 'stdin.lu.dialog'), {})) - settings = new Settings(path.join(process.cwd(), `luis.settings.${flags.suffix}.${flags.region}.json`), {}) + settings.set('stdin', new Settings(path.join(process.cwd(), `luis.settings.${flags.suffix}.${flags.region}.json`), {})) + const recognizer = Recognizer.load(content.path, content.name, path.join(process.cwd(), `${content.name}.dialog`), settings.get('stdin'), {}) + recognizers.set(content.name, recognizer) } else { - this.log('Start to load lu files\n') - dialogFilePath = flags.in.endsWith(fileExtEnum.LUFile) ? path.dirname(path.resolve(flags.in)) : path.resolve(flags.in) - const files = await fileHelper.getLuFiles(flags.in, true, fileExtEnum.LUFile) - for (const file of files) { - let fileCulture: string - let fileName: string - const luFiles = await fileHelper.getLuObjects(undefined, file, true, fileExtEnum.LUFile) - const result = await LuisBuilder.build(luFiles, true, flags.culture) - const fileContent = result.parseToLuContent() - this.log(`${file} loaded\n`) - let cultureFromPath = fileHelper.getCultureFromPath(file) - if (cultureFromPath) { - fileCulture = cultureFromPath - let fileNameWithCulture = path.basename(file, path.extname(file)) - fileName = fileNameWithCulture.substring(0, fileNameWithCulture.length - fileCulture.length - 1) - } else { - fileCulture = flags.culture - fileName = path.basename(file, path.extname(file)) - } - - const multiRecognizerPath = path.join(dialogFilePath, `${fileName}.lu.dialog`) - if (!multiRecognizers.has(fileName)) { - let multiRecognizerContent = {} - if (fs.existsSync(multiRecognizerPath)) { - multiRecognizerContent = JSON.parse(await fileHelper.getContentFromFile(multiRecognizerPath)).recognizers - this.log(`${multiRecognizerPath} loaded\n`) - } - - multiRecognizers.set(fileName, new MultiLanguageRecognizer(multiRecognizerPath, multiRecognizerContent)) - } - - luContents.push(new Content(fileContent, fileName, true, fileCulture, file)) - } + this.log('Start to load lu files') - let settingsPath = path.join(dialogFilePath, `luis.settings.${flags.suffix}.${flags.region}.json`) - let settingsContent: any = {} - if (fs.existsSync(settingsPath)) { - settingsContent = JSON.parse(await fileHelper.getContentFromFile(settingsPath)).luis - this.log(`${settingsPath} loaded\n`) + // get lu files from flags.in + if (flags.in && flags.in !== '') { + const luFiles = await file.getLuFiles(flags.in, true, fileExtEnum.LUFile) + files.push(...luFiles) } - settings = new Settings(settingsPath, settingsContent) + // load lu contents from lu files + // load existing recognizers, multiRecogniers and settings or create default ones + const loadedResources = await builder.loadContents(files, flags.defaultCulture, flags.suffix, flags.region) + luContents = loadedResources.luContents + recognizers = loadedResources.recognizers + multiRecognizers = loadedResources.multiRecognizers + settings = loadedResources.settings } - // validate if there are duplicated files with same name and locale - let setOfContents = new Set() - const hasDuplicates = luContents.some(function (currentObj) { - return setOfContents.size === setOfContents.add(currentObj.name).size - }) + // update or create and then train and publish luis applications based on loaded resources + this.log('Start to handle applications') + const dialogContents = await builder.build(luContents, recognizers, flags.authoringKey, flags.region, flags.botName, flags.suffix, flags.fallbackLocale, flags.deleteOldVersion, multiRecognizers, settings) - if (hasDuplicates) { - throw new CLIError('Files with same name and locale are found.') - } - - this.log('Start to handle applications\n') - const luBuildCore = new LuBuildCore(flags.authoringKey, `https://${flags.region}.api.cognitive.microsoft.com`) - const apps = await luBuildCore.GetApplicationList() - - // here we do a while loop to make full use of luis tps capacity - while (luContents.length > 0) { - // get a number(set by luisApiTps) of contents for each loop - const subLuContents = luContents.splice(0, luisApiTps) - - // concurrently handle applications - await Promise.all(subLuContents.map(async content => { - // init current application object from lu content - let currentApp = await this.InitApplicationFromLuContent(content, flags) - - // init recogizer of current app - let dialogFile = path.join(dialogFilePath, `${content.name}.dialog`) - - let existingDialogObj: any - if (fs.existsSync(dialogFile)) { - existingDialogObj = JSON.parse(await fileHelper.getContentFromFile(dialogFile)) - this.log(`${dialogFile} loaded\n`) - } - - let recognizer = Recognizer.load(content.path, content.name, dialogFile, settings, existingDialogObj) - - // find if there is a matched name with current app under current authoring key - if (!recognizer.getAppId()) { - for (let app of apps) { - if (app.name === currentApp.name) { - recognizer.setAppId(app.id) - break - } - } - } - - let needTrainAndPublish = false - - // compare models to update the model if a match found - // otherwise create a new application - if (recognizer.getAppId() && recognizer.getAppId() !== '') { - // To see if need update the model - needTrainAndPublish = await this.UpdateApplication(currentApp, luBuildCore, recognizer, delayDuration) - } else { - // create a new application - needTrainAndPublish = await this.CreateApplication(currentApp, luBuildCore, recognizer, delayDuration) - } - - if (needTrainAndPublish) { - // train and publish application - await this.TrainAndPublishApplication(luBuildCore, recognizer, delayDuration) - } - - // save dialog assets - // save multiLanguageRecognizer assert - if (multiRecognizers.has(content.id)) { - let multiRecognizer = multiRecognizers.get(content.id) as MultiLanguageRecognizer - multiRecognizer.recognizers[currentApp.culture] = path.basename(dialogFile, '.dialog') - if (currentApp.culture.toLowerCase() === flags.fallbackLocale.toLowerCase()) { - multiRecognizer.recognizers[''] = path.basename(dialogFile, '.dialog') - } - } - - // save settings assert - settings.luis[content.name.split('.').join('_')] = recognizer.getAppId() - - // save recognizers assert - recognizers.push(recognizer) - })) - } - - // write dialog assets - const contents = luBuildCore.GenerateDeclarativeAssets(recognizers, Array.from(multiRecognizers.values()), settings) + // write dialog assets based on config if (flags.dialog) { - for (const content of contents) { - if (flags.out) { - const outFilePath = path.join(path.resolve(flags.out), path.basename(content.path)) - if (flags.force || !fs.existsSync(outFilePath)) { - this.log(`Writing to ${outFilePath}\n`) - await fs.writeFile(outFilePath, content.content, 'utf-8') - } - } else { - if (flags.force || !fs.existsSync(content.path)) { - this.log(`Writing to ${content.path}\n`) - await fs.writeFile(content.path, content.content, 'utf-8') - } - } - } - } else { - if (contents.length > 0) { - this.log('The published application ids:') - this.log(JSON.parse(contents[contents.length - 1].content).luis) - this.log('\n') - } - } - - this.log('All tasks done\n') - } - - async InitApplicationFromLuContent(content: any, flags: any) { - let currentApp = await content.parseToLuis(true, content.language) - currentApp.culture = currentApp.culture && currentApp.culture !== '' && currentApp.culture !== 'en-us' ? currentApp.culture : content.language as string - currentApp.desc = currentApp.desc && currentApp.desc !== '' ? currentApp.desc : `Model for ${flags.botName} app, targetting ${flags.suffix}` - - if (currentApp.name === undefined || currentApp.name === '') { - currentApp.name = `${flags.botName}(${flags.suffix})-${content.name}` - } - - return currentApp - } - - async UpdateApplication(currentApp: any, luBuildCore: LuBuildCore, recognizer: Recognizer, delayDuration: number) { - await delay(delayDuration) - const appInfo = await luBuildCore.GetApplicationInfo(recognizer.getAppId()) - recognizer.versionId = appInfo.activeVersion - - await delay(delayDuration) - const existingApp = await luBuildCore.ExportApplication(recognizer.getAppId(), recognizer.versionId) - - // compare models - const needUpdate = luBuildCore.CompareApplications(currentApp, existingApp) - if (needUpdate) { - const newVersionId = luBuildCore.UpdateVersion(currentApp, existingApp) - recognizer.versionId = newVersionId - const options: any = { - versionId: newVersionId + const writeDone = await builder.writeDialogAssets(dialogContents, flags.force, flags.out) + const dialogFilePath = (flags.stdin || !flags.in) ? process.cwd() : flags.in.endsWith(fileExtEnum.LUFile) ? path.dirname(path.resolve(flags.in)) : path.resolve(flags.in) + const outputFolder = flags.out ? path.resolve(flags.out) : dialogFilePath + if (writeDone) { + this.log(`Successfully wrote .dialog files to ${outputFolder}`) + } else { + this.log(`No changes to the .dialog files in ${outputFolder}`) } - - this.log(`${recognizer.getLuPath()} creating version=${newVersionId}\n`) - await delay(delayDuration) - await luBuildCore.ImportNewVersion(recognizer.getAppId(), currentApp, options) - return true } else { - this.log(`${recognizer.getLuPath()} no changes\n`) - return false + this.log('The published application ids:') + this.log(JSON.parse(dialogContents[dialogContents.length - 1].content).luis) } } - - async CreateApplication(currentApp: any, luBuildCore: LuBuildCore, recognizer: Recognizer, delayDuration: number) { - currentApp.versionId = currentApp.versionId && currentApp.versionId !== '' ? currentApp.versionId : '0.1' - recognizer.versionId = currentApp.versionId - this.log(`Creating LUIS.ai application: ${currentApp.name} version:${currentApp.versionId}\n`) - await delay(delayDuration) - const response = await luBuildCore.ImportApplication(currentApp) - recognizer.setAppId(typeof response.body === 'string' ? response.body : response.body[Object.keys(response.body)[0]]) - return true - } - - async TrainAndPublishApplication(luBuildCore: LuBuildCore, recognizer: Recognizer, delayDuration: number) { - // send train application request - this.log(`${recognizer.getLuPath()} training version=${recognizer.versionId}\n`) - await delay(delayDuration) - await luBuildCore.TrainApplication(recognizer.getAppId(), recognizer.versionId) - this.log(`${recognizer.getLuPath()} waiting for training for version=${recognizer.versionId}...`) - let done = true - do { - await delay(delayDuration) - - // get training status to see if training completed - let trainingStatus = await luBuildCore.GetTrainingStatus(recognizer.getAppId(), recognizer.versionId) - done = true - for (let status of trainingStatus) { - if (status.details) { - if (status.details.status === 'InProgress' || status.details.status === 'Queued') { - done = false - break - } - } - } - } while (!done) - this.log('done\n') - - // publish applications - this.log(`${recognizer.getLuPath()} publishing version=${recognizer.versionId}\n`) - await delay(delayDuration) - await luBuildCore.PublishApplication(recognizer.getAppId(), recognizer.versionId) - this.log(`${recognizer.getLuPath()} publishing finished\n`) - } } -/* eslint-enable no-multiple-empty-lines, node/no-missing-require, complexity, prefer-const, new-cap, unicorn/prefer-spread, no-lonely-if, comma-dangle, no-else-return */ diff --git a/packages/lu-cli/test/commands/luis/build.test.ts b/packages/lu-cli/test/commands/luis/build.test.ts index 00bebded6..fc5770384 100644 --- a/packages/lu-cli/test/commands/luis/build.test.ts +++ b/packages/lu-cli/test/commands/luis/build.test.ts @@ -26,7 +26,7 @@ describe('luis:build cli parameters test', () => { .stderr() .command(['luis:build', '--in', `${path.join(__dirname, './../../fixtures/testcases/lubuild')}`, '--botName', 'Contoso']) .it('displays an error if any required input parameters are missing', ctx => { - expect(ctx.stderr).to.contain(`Missing required flag:\n --authoringKey AUTHORINGKEY`) + expect(ctx.stderr).to.contain('Missing required flag:\n --authoringKey AUTHORINGKEY') }) test @@ -34,7 +34,7 @@ describe('luis:build cli parameters test', () => { .stderr() .command(['luis:build', '--authoringKey', uuidv1(), '--botName', 'Contoso']) .it('displays an error if any required input parameters are missing', ctx => { - expect(ctx.stderr).to.contain(`Missing input. Please use stdin or pass a file or folder location with --in flag`) + expect(ctx.stderr).to.contain('Missing input. Please use stdin or pass a file or folder location with --in flag') }) test @@ -42,7 +42,7 @@ describe('luis:build cli parameters test', () => { .stderr() .command(['luis:build', '--authoringKey', uuidv1(), '--in', `${path.join(__dirname, './../../fixtures/testcases/lubuild')}`]) .it('displays an error if any required input parameters are missing', ctx => { - expect(ctx.stderr).to.contain(`Missing required flag:\n --botName BOTNAME Bot name`) + expect(ctx.stderr).to.contain('Missing bot name. Please pass bot name with --botName flag') }) test @@ -50,7 +50,7 @@ describe('luis:build cli parameters test', () => { .stderr() .command(['luis:build', '--authoringKey', uuidv1(), '--in', `${path.join(__dirname, './../../fixtures/testcases/lubuild/file-name-duplicated')}`, '--botName', 'Contoso']) .it('displays an error if files with same name and locale are found', ctx => { - expect(ctx.stderr).to.contain(`Files with same name and locale are found`) + expect(ctx.stderr).to.contain('Files with same name and locale are found') }) }) @@ -97,7 +97,7 @@ describe('luis:build create a new application successfully', () => { test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich//lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich//lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--log']) .it('should create a new application successfully', ctx => { expect(ctx.stdout).to.contain('Start to handle applications') expect(ctx.stdout).to.contain('Creating LUIS.ai application') @@ -162,7 +162,7 @@ describe('luis:build update application succeed when utterances changed', () => test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--log']) .it('should update a luis application when utterances changed', ctx => { expect(ctx.stdout).to.contain('Start to handle applications') expect(ctx.stdout).to.contain('creating version=0.2') @@ -227,7 +227,7 @@ describe('luis:build update application succeed when utterances added', () => { test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--log']) .it('should update a luis application when utterances added', ctx => { expect(ctx.stdout).to.contain('Start to handle applications') expect(ctx.stdout).to.contain('creating version=0.2') @@ -263,7 +263,7 @@ describe('luis:build not update application if no changes', () => { test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--log']) .it('should not update a luis application when there are no changes for the coming lu file', ctx => { expect(ctx.stdout).to.contain('Start to handle applications') expect(ctx.stdout).to.contain('no changes') @@ -301,7 +301,7 @@ describe('luis:build write dialog assets successfully if --dialog set', () => { test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results', '--log']) .it('should write dialog assets successfully when --dialog set', async ctx => { expect(await compareFiles('./../../../results/luis.settings.development.westus.json', './../../fixtures/testcases/lubuild/sandwich/config/luis.settings.development.westus.json')).to.be.true expect(await compareFiles('./../../../results/sandwich.en-us.lu.dialog', './../../fixtures/testcases/lubuild/sandwich/dialogs/sandwich.en-us.lu.dialog')).to.be.true @@ -420,7 +420,7 @@ describe('luis:build create multiple applications successfully when input is a f test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/foo/lufiles', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/foo/lufiles', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results', '--log']) .it('should create multiple applications and write dialog assets successfully when input is a folder', async ctx => { expect(ctx.stdout).to.contain('foo.fr-fr.lu loaded') expect(ctx.stdout).to.contain('foo.lu loaded') @@ -526,7 +526,7 @@ describe('luis:build update dialog assets successfully when dialog assets exist' test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/foo2/lufiles-and-dialog-assets', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/foo2/lufiles-and-dialog-assets', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results', '--log']) .it('should update dialog assets successfully when dialog assets exist', async ctx => { expect(ctx.stdout).to.contain('foo.fr-fr.lu loaded') expect(ctx.stdout).to.contain('foo.lu loaded') diff --git a/packages/lu/src/commands/luis/build.ts b/packages/lu/src/commands/luis/build.ts index 2be8af1c4..3e9d44998 100644 --- a/packages/lu/src/commands/luis/build.ts +++ b/packages/lu/src/commands/luis/build.ts @@ -3,17 +3,15 @@ * Licensed under the MIT License. */ -import {Command, flags, CLIError} from '@microsoft/bf-cli-command' -import {LuBuildCore} from './../../parser/lubuild/core' +import {Command, flags} from '@microsoft/bf-cli-command' +import {Builder} from './../../parser/lubuild/builder' import {Settings} from './../../parser/lubuild/settings' -import {MultiLanguageRecognizer} from '../../parser/lubuild/multi-language-recognizer' +import {MultiLanguageRecognizer} from './../../parser/lubuild/multi-language-recognizer' import {Recognizer} from './../../parser/lubuild/recognizer' const path = require('path') const fs = require('fs-extra') -const delay = require('delay') const fileHelper = require('./../../utils/filehelper') const fileExtEnum = require('./../../parser/utils/helpers').FileExtTypeEnum -const LuisBuilder = require('./../../parser/luis/luisBuilder') const Content = require('./../../parser/lu/lu') export default class LuisBuild extends Command { @@ -27,278 +25,106 @@ export default class LuisBuild extends Command { help: flags.help({char: 'h'}), in: flags.string({char: 'i', description: 'Lu file or folder'}), authoringKey: flags.string({description: 'LUIS authoring key', required: true}), - botName: flags.string({description: 'Bot name', required: true}), + botName: flags.string({description: 'Bot name'}), out: flags.string({description: 'Output location'}), - culture: flags.string({description: 'Culture code for the content. Infer from .lu if available. Defaults to en-us'}), + defaultCulture: flags.string({description: 'Culture code for the content. Infer from .lu if available. Defaults to en-us'}), region: flags.string({description: 'LUIS authoring region'}), suffix: flags.string({description: 'Environment name as a suffix identifier to include in LUIS app name'}), force: flags.boolean({char: 'f', description: 'Force write dialog and settings files', default: false}), dialog: flags.boolean({description: 'Write out .dialog files', default: false}), - fallbackLocale: flags.string({description: 'Locale to be used at the fallback if no locale specific recognizer is found. Only valid if --dialog is set'}) + fallbackLocale: flags.string({description: 'Locale to be used at the fallback if no locale specific recognizer is found. Only valid if --dialog is set'}), + luConfig: flags.string({description: 'Path to config for lu build'}), + log: flags.boolean({description: 'write out log messages to console', default: false}) } async run() { const {flags} = this.parse(LuisBuild) - // Check stdin or in parameter - const stdin = await this.readStdin() - if (!stdin && !flags.in) { - throw new CLIError('Missing input. Please use stdin or pass a file or folder location with --in flag') + flags.stdin = await this.readStdin() + + let files: string[] = [] + if (flags.luConfig) { + const configFilePath = path.resolve(flags.luConfig) + if (fs.existsSync(configFilePath)) { + const configObj = JSON.parse(await fileHelper.getContentFromFile(configFilePath)) + if (configObj.name && configObj.name !== '') flags.botName = configObj.name + if (configObj.defaultLanguage && configObj.defaultLanguage !== '') flags.defaultCulture = configObj.defaultLanguage + if (configObj.deleteOldVersion) flags.deleteOldVersion = true + if (configObj.out && configObj.out !== '') flags.out = configObj.out + if (configObj.writeDialogFiles) flags.dialog = true + if (configObj.models && configObj.models.length > 0) { + files = configObj.models.map((m: string) => path.resolve(m)) + } + } + } + + if (!flags.stdin && !flags.in && files.length === 0) { + throw new Error('Missing input. Please use stdin or pass a file or folder location with --in flag') } - flags.culture = flags.culture && flags.culture !== '' ? flags.culture : 'en-us' + if (!flags.botName) { + throw new Error('Missing bot name. Please pass bot name with --botName flag') + } + + flags.defaultCulture = flags.defaultCulture && flags.defaultCulture !== '' ? flags.defaultCulture : 'en-us' flags.region = flags.region && flags.region !== '' ? flags.region : 'westus' flags.suffix = flags.suffix && flags.suffix !== '' ? flags.suffix : 'development' flags.fallbackLocale = flags.fallbackLocale && flags.fallbackLocale !== '' ? flags.fallbackLocale : 'en-us' - let multiRecognizers = new Map() - let settings: Settings - let recognizers: Recognizer[] = [] - let luContents: Array = [] - let dialogFilePath = process.cwd() - - // luis api TPS which means 5 concurrent transactions to luis api in 1 second - // can set to other value if switched to a higher TPS(transaction per second) key - let luisApiTps = 5 + // create builder class + const builder = new Builder((input: string) => { + if (flags.log) this.log(input) + }) - // set luis call delay duration to 1100 millisecond because 1000 can hit corner case of rate limit - let delayDuration = 1100 + let luContents: any[] = [] + let recognizers = new Map() + let multiRecognizers = new Map() + let settings = new Map() - if (stdin && stdin !== '') { + if (flags.stdin && flags.stdin !== '') { + // load lu content from stdin and create default recognizer, multiRecognier and settings this.log('Load lu content from stdin') - luContents.push(new Content(stdin, 'stdin', true, flags.culture, path.join(process.cwd(), 'stdin'))) + const content = new Content(flags.stdin, 'stdin', true, flags.defaultCulture, path.join(process.cwd(), 'stdin')) + luContents.push(content) multiRecognizers.set('stdin', new MultiLanguageRecognizer(path.join(process.cwd(), 'stdin.lu.dialog'), {})) - settings = new Settings(path.join(process.cwd(), `luis.settings.${flags.suffix}.${flags.region}.json`), {}) + settings.set('stdin', new Settings(path.join(process.cwd(), `luis.settings.${flags.suffix}.${flags.region}.json`), {})) + let recognizer = Recognizer.load(content.path, content.name, path.join(process.cwd(), `${content.name}.dialog`), settings.get('stdin') as Settings, {}) + recognizers.set(content.name, recognizer) } else { - this.log('Start to load lu files\n') - dialogFilePath = flags.in.endsWith(fileExtEnum.LUFile) ? path.dirname(path.resolve(flags.in)) : path.resolve(flags.in) - let files = await fileHelper.getLuFiles(flags.in, true, fileExtEnum.LUFile) - for (const file of files) { - let fileCulture: string - let fileName: string - const luFiles = await fileHelper.getLuObjects(undefined, file, true, fileExtEnum.LUFile) - const result = await LuisBuilder.build(luFiles, true, flags.culture) - const fileContent = result.parseToLuContent() - this.log(`${file} loaded\n`) - let cultureFromPath = fileHelper.getCultureFromPath(file) - if (cultureFromPath) { - fileCulture = cultureFromPath - let fileNameWithCulture = path.basename(file, path.extname(file)) - fileName = fileNameWithCulture.substring(0, fileNameWithCulture.length - fileCulture.length - 1) - } else { - fileCulture = flags.culture - fileName = path.basename(file, path.extname(file)) - } - - const multiRecognizerPath = path.join(dialogFilePath, `${fileName}.lu.dialog`) - if (!multiRecognizers.has(fileName)) { - let multiRecognizerContent = {} - if (fs.existsSync(multiRecognizerPath)) { - multiRecognizerContent = JSON.parse(await fileHelper.getContentFromFile(multiRecognizerPath)).recognizers - this.log(`${multiRecognizerPath} loaded\n`) - } - - multiRecognizers.set(fileName, new MultiLanguageRecognizer(multiRecognizerPath, multiRecognizerContent)) - } - - luContents.push(new Content(fileContent, fileName, true, fileCulture, file)) - } + this.log('Start to load lu files') - let settingsPath = path.join(dialogFilePath, `luis.settings.${flags.suffix}.${flags.region}.json`) - let settingsContent: any = {} - if (fs.existsSync(settingsPath)) { - settingsContent = JSON.parse(await fileHelper.getContentFromFile(settingsPath)).luis - this.log(`${settingsPath} loaded\n`) + // get lu files from flags.in + if (flags.in && flags.in !== '') { + let luFiles = await fileHelper.getLuFiles(flags.in, true, fileExtEnum.LUFile) + files.push(...luFiles) } - settings = new Settings(settingsPath, settingsContent) + // load lu contents from lu files + // load existing recognizers, multiRecogniers and settings or create default ones + const loadedResources = await builder.loadContents(files, flags.defaultCulture, flags.suffix, flags.region) + luContents = loadedResources.luContents + recognizers = loadedResources.recognizers + multiRecognizers = loadedResources.multiRecognizers + settings = loadedResources.settings } - // validate if there are duplicated files with same name and locale - let setOfContents = new Set() - const hasDuplicates = luContents.some(function (currentObj) { - return setOfContents.size === setOfContents.add(currentObj.name).size - }) - - if (hasDuplicates) { - throw new CLIError('Files with same name and locale are found.') - } - - this.log('Start to handle applications\n') - const luBuildCore = new LuBuildCore(flags.authoringKey, `https://${flags.region}.api.cognitive.microsoft.com`) - const apps = await luBuildCore.GetApplicationList() - - // here we do a while loop to make full use of luis tps capacity - while (luContents.length > 0) { - // get a number(set by luisApiTps) of contents for each loop - const subLuContents = luContents.splice(0, luisApiTps) - - // concurrently handle applications - await Promise.all(subLuContents.map(async content => { - // init current application object from lu content - let currentApp = await this.InitApplicationFromLuContent(content, flags) - - // init recogizer of current app - let dialogFile = path.join(dialogFilePath, `${content.name}.dialog`) - - let existingDialogObj: any - if (fs.existsSync(dialogFile)) { - existingDialogObj = JSON.parse(await fileHelper.getContentFromFile(dialogFile)) - this.log(`${dialogFile} loaded\n`) - } - - let recognizer = Recognizer.load(content.path, content.name, dialogFile, settings, existingDialogObj) - - // find if there is a matched name with current app under current authoring key - if (!recognizer.getAppId()) { - for (let app of apps) { - if (app.name === currentApp.name) { - recognizer.setAppId(app.id) - break - } - } - } - - let needTrainAndPublish = false - - // compare models to update the model if a match found - // otherwise create a new application - if (recognizer.getAppId() && recognizer.getAppId() !== '') { - // To see if need update the model - needTrainAndPublish = await this.UpdateApplication(currentApp, luBuildCore, recognizer, delayDuration) - } else { - // create a new application - needTrainAndPublish = await this.CreateApplication(currentApp, luBuildCore, recognizer, delayDuration) - } - - if (needTrainAndPublish) { - // train and publish application - await this.TrainAndPublishApplication(luBuildCore, recognizer, delayDuration) - } - - // save dialog assets - // save multiLanguageRecognizer assert - if (multiRecognizers.has(content.id)) { - let multiRecognizer = multiRecognizers.get(content.id) as MultiLanguageRecognizer - multiRecognizer.recognizers[currentApp.culture] = path.basename(dialogFile, '.dialog') - if (currentApp.culture.toLowerCase() === flags.fallbackLocale.toLowerCase()) { - multiRecognizer.recognizers[''] = path.basename(dialogFile, '.dialog') - } - } - - // save settings assert - settings.luis[content.name.split('.').join('_')] = recognizer.getAppId() - - // save recognizers assert - recognizers.push(recognizer) - })) - } + // update or create and then train and publish luis applications based on loaded resources + this.log('Start to handle applications') + const dialogContents = await builder.build(luContents, recognizers, flags.authoringKey, flags.region, flags.botName, flags.suffix, flags.fallbackLocale, flags.deleteOldVersion, multiRecognizers, settings) - // write dialog assets - const contents = luBuildCore.GenerateDeclarativeAssets(recognizers, Array.from(multiRecognizers.values()), settings) + // write dialog assets based on config if (flags.dialog) { - for (const content of contents) { - if (flags.out) { - const outFilePath = path.join(path.resolve(flags.out), path.basename(content.path)) - if (flags.force || !fs.existsSync(outFilePath)) { - this.log(`Writing to ${outFilePath}\n`) - await fs.writeFile(outFilePath, content.content, 'utf-8') - } - } else { - if (flags.force || !fs.existsSync(content.path)) { - this.log(`Writing to ${content.path}\n`) - await fs.writeFile(content.path, content.content, 'utf-8') - } - } + const writeDone = await builder.writeDialogAssets(dialogContents, flags.force, flags.out) + const dialogFilePath = (flags.stdin || !flags.in) ? process.cwd() : flags.in.endsWith(fileExtEnum.LUFile) ? path.dirname(path.resolve(flags.in)) : path.resolve(flags.in) + const outputFolder = flags.out ? path.resolve(flags.out) : dialogFilePath + if (writeDone) { + this.log(`Successfully wrote .dialog files to ${outputFolder}`) + } else { + this.log(`No changes to the .dialog files in ${outputFolder}`) } } else { - if (contents.length > 0) { - this.log('The published application ids:') - this.log(JSON.parse(contents[contents.length - 1].content).luis) - this.log('\n') - } - } - - this.log('All tasks done\n') - } - - async InitApplicationFromLuContent(content: any, flags: any) { - let currentApp = await content.parseToLuis(true, content.language) - currentApp.culture = currentApp.culture && currentApp.culture !== '' && currentApp.culture !== 'en-us' ? currentApp.culture : content.language as string - currentApp.desc = currentApp.desc && currentApp.desc !== '' ? currentApp.desc : `Model for ${flags.botName} app, targetting ${flags.suffix}` - - if (currentApp.name === undefined || currentApp.name === '') { - currentApp.name = `${flags.botName}(${flags.suffix})-${content.name}` + this.log('The published application ids:') + this.log(JSON.parse(dialogContents[dialogContents.length - 1].content).luis) } - - return currentApp - } - - async UpdateApplication(currentApp: any, luBuildCore: LuBuildCore, recognizer: Recognizer, delayDuration: number) { - await delay(delayDuration) - const appInfo = await luBuildCore.GetApplicationInfo(recognizer.getAppId()) - recognizer.versionId = appInfo.activeVersion - - await delay(delayDuration) - const existingApp = await luBuildCore.ExportApplication(recognizer.getAppId(), recognizer.versionId) - - // compare models - const needUpdate = luBuildCore.CompareApplications(currentApp, existingApp) - if (needUpdate) { - const newVersionId = luBuildCore.UpdateVersion(currentApp, existingApp) - recognizer.versionId = newVersionId - const options: any = { - versionId: newVersionId - } - - this.log(`${recognizer.getLuPath()} creating version=${newVersionId}\n`) - await delay(delayDuration) - await luBuildCore.ImportNewVersion(recognizer.getAppId(), currentApp, options) - return true - } else { - this.log(`${recognizer.getLuPath()} no changes\n`) - return false - } - } - - async CreateApplication(currentApp: any, luBuildCore: LuBuildCore, recognizer: Recognizer, delayDuration: number) { - currentApp.versionId = currentApp.versionId && currentApp.versionId !== '' ? currentApp.versionId : '0.1' - recognizer.versionId = currentApp.versionId - this.log(`Creating LUIS.ai application: ${currentApp.name} version:${currentApp.versionId}\n`) - await delay(delayDuration) - const response = await luBuildCore.ImportApplication(currentApp) - recognizer.setAppId(typeof response.body === 'string' ? response.body : response.body[Object.keys(response.body)[0]]) - return true - } - - async TrainAndPublishApplication(luBuildCore: LuBuildCore, recognizer: Recognizer, delayDuration: number) { - // send train application request - this.log(`${recognizer.getLuPath()} training version=${recognizer.versionId}\n`) - await delay(delayDuration) - await luBuildCore.TrainApplication(recognizer.getAppId(), recognizer.versionId) - this.log(`${recognizer.getLuPath()} waiting for training for version=${recognizer.versionId}...`) - let done = true - do { - await delay(delayDuration) - - // get training status to see if training completed - let trainingStatus = await luBuildCore.GetTrainingStatus(recognizer.getAppId(), recognizer.versionId) - done = true - for (let status of trainingStatus) { - if (status.details) { - if (status.details.status === 'InProgress' || status.details.status === 'Queued') { - done = false - break - } - } - } - } while (!done) - this.log('done\n') - - // publish applications - this.log(`${recognizer.getLuPath()} publishing version=${recognizer.versionId}\n`) - await delay(delayDuration) - await luBuildCore.PublishApplication(recognizer.getAppId(), recognizer.versionId) - this.log(`${recognizer.getLuPath()} publishing finished\n`) } } diff --git a/packages/lu/src/parser/lubuild.js b/packages/lu/src/parser/lubuild.js new file mode 100644 index 000000000..ee27843c9 --- /dev/null +++ b/packages/lu/src/parser/lubuild.js @@ -0,0 +1,10 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +const modules = { + luBuild: { + Builder: require('./lubuild/builder').Builder + } +}; +module.exports = modules; \ No newline at end of file diff --git a/packages/lu/src/parser/lubuild/builder.ts b/packages/lu/src/parser/lubuild/builder.ts new file mode 100644 index 000000000..6db57484d --- /dev/null +++ b/packages/lu/src/parser/lubuild/builder.ts @@ -0,0 +1,335 @@ +/*! + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +import {LuBuildCore} from './core' +import {Settings} from './settings' +import {MultiLanguageRecognizer} from './multi-language-recognizer' +import {Recognizer} from './recognizer' +const path = require('path') +const fs = require('fs-extra') +const delay = require('delay') +const fileHelper = require('./../../utils/filehelper') +const fileExtEnum = require('./../utils/helpers').FileExtTypeEnum +const LuisBuilder = require('./../luis/luisBuilder') +const Content = require('./../lu/lu') + +export class Builder { + private readonly handler: (input: string) => any + + constructor(handler: any) { + this.handler = handler + } + + async loadContents( + files: string[], + culture: string, + suffix: string, + region: string) { + let multiRecognizers = new Map() + let settings = new Map() + let recognizers = new Map() + let luContents: Array = [] + + for (const file of files) { + let fileCulture: string + let fileName: string + const luFiles = await fileHelper.getLuObjects(undefined, file, true, fileExtEnum.LUFile) + const result = await LuisBuilder.build(luFiles, true, culture) + const fileContent = result.parseToLuContent() + this.handler(`${file} loaded\n`) + let cultureFromPath = fileHelper.getCultureFromPath(file) + if (cultureFromPath) { + fileCulture = cultureFromPath + let fileNameWithCulture = path.basename(file, path.extname(file)) + fileName = fileNameWithCulture.substring(0, fileNameWithCulture.length - fileCulture.length - 1) + } else { + fileCulture = culture + fileName = path.basename(file, path.extname(file)) + } + + const fileFolder = path.dirname(file) + const multiRecognizerPath = path.join(fileFolder, `${fileName}.lu.dialog`) + if (!multiRecognizers.has(fileName)) { + let multiRecognizerContent = {} + if (fs.existsSync(multiRecognizerPath)) { + multiRecognizerContent = JSON.parse(await fileHelper.getContentFromFile(multiRecognizerPath)).recognizers + this.handler(`${multiRecognizerPath} loaded\n`) + } + + multiRecognizers.set(fileName, new MultiLanguageRecognizer(multiRecognizerPath, multiRecognizerContent)) + } + + const settingsPath = path.join(fileFolder, `luis.settings.${suffix}.${region}.json`) + if (!settings.has(fileFolder)) { + let settingsContent = {} + if (fs.existsSync(settingsPath)) { + settingsContent = JSON.parse(await fileHelper.getContentFromFile(settingsPath)).luis + this.handler(`${settingsPath} loaded\n`) + } + + settings.set(fileFolder, new Settings(settingsPath, settingsContent)) + } + + const content = new Content(fileContent, fileName, true, fileCulture, file) + luContents.push(content) + + const dialogFile = path.join(fileFolder, `${content.name}.dialog`) + let existingDialogObj: any + if (fs.existsSync(dialogFile)) { + existingDialogObj = JSON.parse(await fileHelper.getContentFromFile(dialogFile)) + this.handler(`${dialogFile} loaded\n`) + } + + let recognizer = Recognizer.load(content.path, content.name, dialogFile, settings.get(fileFolder) as Settings, existingDialogObj) + recognizers.set(content.name, recognizer) + } + + // validate if there are duplicated files with same name and locale + let setOfContents = new Set() + const hasDuplicates = luContents.some(function (currentObj) { + return setOfContents.size === setOfContents.add(currentObj.name).size + }) + + if (hasDuplicates) { + throw new Error('Files with same name and locale are found.') + } + + return {luContents, recognizers, multiRecognizers, settings} + } + + async build( + luContents: any[], + recognizers: Map, + authoringKey: string, + region: string, + botName: string, + suffix: string, + fallbackLocale: string, + deleteOldVersion: boolean, + multiRecognizers?: Map, + settings?: Map) { + // luis api TPS which means 5 concurrent transactions to luis api in 1 second + // can set to other value if switched to a higher TPS(transaction per second) key + let luisApiTps = 5 + + // set luis call delay duration to 1100 millisecond because 1000 can hit corner case of rate limit + let delayDuration = 1100 + + const luBuildCore = new LuBuildCore(authoringKey, `https://${region}.api.cognitive.microsoft.com`) + const apps = await luBuildCore.getApplicationList() + + // here we do a while loop to make full use of luis tps capacity + while (luContents.length > 0) { + // get a number(set by luisApiTps) of contents for each loop + const subLuContents = luContents.splice(0, luisApiTps) + + // concurrently handle applications + await Promise.all(subLuContents.map(async content => { + // init current application object from lu content + let currentApp = await this.initApplicationFromLuContent(content, botName, suffix) + + // get recognizer + let recognizer = recognizers.get(content.name) as Recognizer + + // find if there is a matched name with current app under current authoring key + if (!recognizer.getAppId()) { + for (let app of apps) { + if (app.name === currentApp.name) { + recognizer.setAppId(app.id) + break + } + } + } + + let needTrainAndPublish = false + + // compare models to update the model if a match found + // otherwise create a new application + if (recognizer.getAppId() && recognizer.getAppId() !== '') { + // To see if need update the model + needTrainAndPublish = await this.updateApplication(currentApp, luBuildCore, recognizer, delayDuration, deleteOldVersion) + } else { + // create a new application + needTrainAndPublish = await this.createApplication(currentApp, luBuildCore, recognizer, delayDuration) + } + + if (needTrainAndPublish) { + // train and publish application + await this.trainAndPublishApplication(luBuildCore, recognizer, delayDuration) + } + + // update multiLanguageRecognizer asset + if (multiRecognizers && multiRecognizers.has(content.id)) { + let multiRecognizer = multiRecognizers.get(content.id) as MultiLanguageRecognizer + multiRecognizer.recognizers[currentApp.culture] = path.basename(recognizer.getDialogPath(), '.dialog') + if (currentApp.culture.toLowerCase() === fallbackLocale.toLowerCase()) { + multiRecognizer.recognizers[''] = path.basename(recognizer.getDialogPath(), '.dialog') + } + } + + // update settings asset + if (settings && settings.has(path.dirname(content.path))) { + let setting = settings.get(path.dirname(content.path)) as Settings + setting.luis[content.name.split('.').join('_')] = recognizer.getAppId() + } + })) + } + + // write dialog assets + let recognizerValues: Recognizer[] = [] + if (recognizers) { + recognizerValues = Array.from(recognizers.values()) + } + + let multiRecognizerValues: MultiLanguageRecognizer[] = [] + if (multiRecognizers) { + multiRecognizerValues = Array.from(multiRecognizers.values()) + } + + let settingValues: Settings[] = [] + if (settings) { + settingValues = Array.from(settings.values()) + } + + const dialogContents = luBuildCore.generateDeclarativeAssets(recognizerValues, multiRecognizerValues, settingValues) + + return dialogContents + } + + async writeDialogAssets(contents: any[], force: boolean, out: string) { + let writeDone = false + if (out) { + let settingsContents = contents.filter(c => c.id.endsWith('.json')) + let writeContents = contents.filter(c => c.id.endsWith('.dialog')) + + if (settingsContents && settingsContents.length > 0) { + writeContents.push(this.mergeSettingsContent(path.join(path.resolve(out), settingsContents[0].id), settingsContents)) + } + + for (const content of writeContents) { + const outFilePath = path.join(path.resolve(out), path.basename(content.path)) + if (force || !fs.existsSync(outFilePath)) { + this.handler(`Writing to ${outFilePath}\n`) + await fs.writeFile(outFilePath, content.content, 'utf-8') + writeDone = true + } + } + } else { + for (const content of contents) { + if (force || !fs.existsSync(content.path)) { + this.handler(`Writing to ${content.path}\n`) + await fs.writeFile(content.path, content.content, 'utf-8') + writeDone = true + } + } + } + + return writeDone + } + + async initApplicationFromLuContent(content: any, botName: string, suffix: string) { + let currentApp = await content.parseToLuis(true, content.language) + currentApp.culture = currentApp.culture && currentApp.culture !== '' && currentApp.culture !== 'en-us' ? currentApp.culture : content.language as string + currentApp.desc = currentApp.desc && currentApp.desc !== '' ? currentApp.desc : `Model for ${botName} app, targetting ${suffix}` + + if (currentApp.name === undefined || currentApp.name === '') { + currentApp.name = `${botName}(${suffix})-${content.name}` + } + + return currentApp + } + + async updateApplication(currentApp: any, luBuildCore: LuBuildCore, recognizer: Recognizer, delayDuration: number, deleteOldVersion: boolean) { + await delay(delayDuration) + const appInfo = await luBuildCore.getApplicationInfo(recognizer.getAppId()) + recognizer.versionId = appInfo.activeVersion + + await delay(delayDuration) + const existingApp = await luBuildCore.exportApplication(recognizer.getAppId(), recognizer.versionId) + + // compare models + const needUpdate = luBuildCore.compareApplications(currentApp, existingApp) + if (needUpdate) { + const newVersionId = luBuildCore.updateVersion(currentApp, existingApp) + recognizer.versionId = newVersionId + const options: any = { + versionId: newVersionId + } + + this.handler(`${recognizer.getLuPath()} creating version=${newVersionId}\n`) + await delay(delayDuration) + await luBuildCore.importNewVersion(recognizer.getAppId(), currentApp, options) + + if (deleteOldVersion) { + await delay(delayDuration) + const versionObjs = await luBuildCore.listApplicationVersions(recognizer.getAppId()) + for (const versionObj of versionObjs) { + if (versionObj.version !== newVersionId) { + this.handler(`deleting old version=${versionObj.version}`) + await luBuildCore.deleteVersion(recognizer.getAppId(), versionObj.version) + } + } + } + + return true + } else { + this.handler(`${recognizer.getLuPath()} no changes\n`) + return false + } + } + + async createApplication(currentApp: any, luBuildCore: LuBuildCore, recognizer: Recognizer, delayDuration: number) { + currentApp.versionId = currentApp.versionId && currentApp.versionId !== '' ? currentApp.versionId : '0.1' + recognizer.versionId = currentApp.versionId + this.handler(`Creating LUIS.ai application: ${currentApp.name} version:${currentApp.versionId}\n`) + await delay(delayDuration) + const response = await luBuildCore.importApplication(currentApp) + recognizer.setAppId(typeof response.body === 'string' ? response.body : response.body[Object.keys(response.body)[0]]) + return true + } + + async trainAndPublishApplication(luBuildCore: LuBuildCore, recognizer: Recognizer, delayDuration: number) { + // send train application request + this.handler(`${recognizer.getLuPath()} training version=${recognizer.versionId}\n`) + await delay(delayDuration) + await luBuildCore.trainApplication(recognizer.getAppId(), recognizer.versionId) + this.handler(`${recognizer.getLuPath()} waiting for training for version=${recognizer.versionId}...`) + let done = true + do { + await delay(delayDuration) + + // get training status to see if training completed + let trainingStatus = await luBuildCore.getTrainingStatus(recognizer.getAppId(), recognizer.versionId) + done = true + for (let status of trainingStatus) { + if (status.details) { + if (status.details.status === 'InProgress' || status.details.status === 'Queued') { + done = false + break + } + } + } + } while (!done) + this.handler('done\n') + + // publish applications + this.handler(`${recognizer.getLuPath()} publishing version=${recognizer.versionId}\n`) + await delay(delayDuration) + await luBuildCore.publishApplication(recognizer.getAppId(), recognizer.versionId) + this.handler(`${recognizer.getLuPath()} publishing finished\n`) + } + + mergeSettingsContent(settingsPath: string, contents: any[]) { + let settings = new Settings(settingsPath, {}) + for (const content of contents) { + const luisAppsMap = JSON.parse(content.content).luis + for (const appName of Object.keys(luisAppsMap)) { + settings.luis[appName] = luisAppsMap[appName] + } + } + + return new Content(settings.save(), path.basename(settings.getSettingsPath()), true, '', settings.getSettingsPath()) + } +} diff --git a/packages/lu/src/parser/lubuild/core.ts b/packages/lu/src/parser/lubuild/core.ts index 56a710644..db205006b 100644 --- a/packages/lu/src/parser/lubuild/core.ts +++ b/packages/lu/src/parser/lubuild/core.ts @@ -21,31 +21,31 @@ export class LuBuildCore { this.client = new LUISAuthoringClient(creds, endpoint) } - public async GetApplicationList() { + public async getApplicationList() { let apps = await this.client.apps.list(undefined, undefined) return apps } - public async GetApplicationInfo(appId: string) { + public async getApplicationInfo(appId: string) { let appInfo = await this.client.apps.get(appId) return appInfo } - public async ImportApplication(currentApp: any): Promise { + public async importApplication(currentApp: any): Promise { let response = await this.client.apps.importMethod(currentApp) return response } - public async ExportApplication(appId: string, versionId: string) { + public async exportApplication(appId: string, versionId: string) { const response = await this.client.versions.exportMethod(appId, versionId) return response } - public CompareApplications(currentApp: any, existingApp: any) { + public compareApplications(currentApp: any, existingApp: any) { currentApp.desc = currentApp.desc && currentApp.desc !== '' && currentApp.desc !== existingApp.desc ? currentApp.desc : existingApp.desc currentApp.culture = currentApp.culture && currentApp.culture !== '' && currentApp.culture !== existingApp.culture ? currentApp.culture : existingApp.culture currentApp.versionId = currentApp.versionId && currentApp.versionId !== '' && currentApp.versionId !== existingApp.versionId ? currentApp.versionId : existingApp.versionId; @@ -82,12 +82,12 @@ export class LuBuildCore { return !this.isApplicationEqual(currentApp, existingApp) } - public UpdateVersion(currentApp: any, existingApp: any) { + public updateVersion(currentApp: any, existingApp: any) { let newVersionId: string if (currentApp.versionId && currentApp.versionId !== existingApp.versionId) { newVersionId = currentApp.versionId } else { - newVersionId = this.updateVersion(existingApp.versionId) + newVersionId = this.updateVersionValue(existingApp.versionId) } currentApp.versionId = newVersionId @@ -95,21 +95,29 @@ export class LuBuildCore { return newVersionId } - public async ImportNewVersion(appId: string, app: any, options: any) { + public async importNewVersion(appId: string, app: any, options: any) { await this.client.versions.importMethod(appId, app, options) } - public async TrainApplication(appId: string, versionId: string) { + public async listApplicationVersions(appId: string) { + return this.client.versions.list(appId) + } + + public async deleteVersion(appId: string, versionId: string) { + await this.client.versions.deleteMethod(appId, versionId) + } + + public async trainApplication(appId: string, versionId: string) { await this.client.train.trainVersion(appId, versionId) } - public async GetTrainingStatus(appId: string, versionId: string) { + public async getTrainingStatus(appId: string, versionId: string) { const status = this.client.train.getStatus(appId, versionId) return status } - public async PublishApplication(appId: string, versionId: string) { + public async publishApplication(appId: string, versionId: string) { this.client.apps.publish(appId, { versionId, @@ -117,7 +125,7 @@ export class LuBuildCore { }) } - public GenerateDeclarativeAssets(recognizers: Array, multiRecognizers: Array, settings: Settings) + public generateDeclarativeAssets(recognizers: Array, multiRecognizers: Array, settings: Array) : Array { let contents = new Array() for (const recognizer of recognizers) { @@ -130,13 +138,15 @@ export class LuBuildCore { contents.push(multiLangContent) } - const settingsContent = new Content(settings.save(), path.basename(settings.getSettingsPath()), true, '', settings.getSettingsPath()) - contents.push(settingsContent) + for (const setting of settings) { + const settingsContent = new Content(setting.save(), path.basename(setting.getSettingsPath()), true, '', setting.getSettingsPath()) + contents.push(settingsContent) + } return contents } - private updateVersion(versionId: string) { + private updateVersionValue(versionId: string) { let numberVersionId = parseFloat(versionId) if (isNaN(numberVersionId)) { const index = versionId.lastIndexOf('-') diff --git a/packages/lu/test/commands/luis/build.test.ts b/packages/lu/test/commands/luis/build.test.ts index 00bebded6..fc5770384 100644 --- a/packages/lu/test/commands/luis/build.test.ts +++ b/packages/lu/test/commands/luis/build.test.ts @@ -26,7 +26,7 @@ describe('luis:build cli parameters test', () => { .stderr() .command(['luis:build', '--in', `${path.join(__dirname, './../../fixtures/testcases/lubuild')}`, '--botName', 'Contoso']) .it('displays an error if any required input parameters are missing', ctx => { - expect(ctx.stderr).to.contain(`Missing required flag:\n --authoringKey AUTHORINGKEY`) + expect(ctx.stderr).to.contain('Missing required flag:\n --authoringKey AUTHORINGKEY') }) test @@ -34,7 +34,7 @@ describe('luis:build cli parameters test', () => { .stderr() .command(['luis:build', '--authoringKey', uuidv1(), '--botName', 'Contoso']) .it('displays an error if any required input parameters are missing', ctx => { - expect(ctx.stderr).to.contain(`Missing input. Please use stdin or pass a file or folder location with --in flag`) + expect(ctx.stderr).to.contain('Missing input. Please use stdin or pass a file or folder location with --in flag') }) test @@ -42,7 +42,7 @@ describe('luis:build cli parameters test', () => { .stderr() .command(['luis:build', '--authoringKey', uuidv1(), '--in', `${path.join(__dirname, './../../fixtures/testcases/lubuild')}`]) .it('displays an error if any required input parameters are missing', ctx => { - expect(ctx.stderr).to.contain(`Missing required flag:\n --botName BOTNAME Bot name`) + expect(ctx.stderr).to.contain('Missing bot name. Please pass bot name with --botName flag') }) test @@ -50,7 +50,7 @@ describe('luis:build cli parameters test', () => { .stderr() .command(['luis:build', '--authoringKey', uuidv1(), '--in', `${path.join(__dirname, './../../fixtures/testcases/lubuild/file-name-duplicated')}`, '--botName', 'Contoso']) .it('displays an error if files with same name and locale are found', ctx => { - expect(ctx.stderr).to.contain(`Files with same name and locale are found`) + expect(ctx.stderr).to.contain('Files with same name and locale are found') }) }) @@ -97,7 +97,7 @@ describe('luis:build create a new application successfully', () => { test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich//lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich//lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--log']) .it('should create a new application successfully', ctx => { expect(ctx.stdout).to.contain('Start to handle applications') expect(ctx.stdout).to.contain('Creating LUIS.ai application') @@ -162,7 +162,7 @@ describe('luis:build update application succeed when utterances changed', () => test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--log']) .it('should update a luis application when utterances changed', ctx => { expect(ctx.stdout).to.contain('Start to handle applications') expect(ctx.stdout).to.contain('creating version=0.2') @@ -227,7 +227,7 @@ describe('luis:build update application succeed when utterances added', () => { test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--log']) .it('should update a luis application when utterances added', ctx => { expect(ctx.stdout).to.contain('Start to handle applications') expect(ctx.stdout).to.contain('creating version=0.2') @@ -263,7 +263,7 @@ describe('luis:build not update application if no changes', () => { test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--log']) .it('should not update a luis application when there are no changes for the coming lu file', ctx => { expect(ctx.stdout).to.contain('Start to handle applications') expect(ctx.stdout).to.contain('no changes') @@ -301,7 +301,7 @@ describe('luis:build write dialog assets successfully if --dialog set', () => { test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/sandwich/lufiles/sandwich.en-us.lu', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results', '--log']) .it('should write dialog assets successfully when --dialog set', async ctx => { expect(await compareFiles('./../../../results/luis.settings.development.westus.json', './../../fixtures/testcases/lubuild/sandwich/config/luis.settings.development.westus.json')).to.be.true expect(await compareFiles('./../../../results/sandwich.en-us.lu.dialog', './../../fixtures/testcases/lubuild/sandwich/dialogs/sandwich.en-us.lu.dialog')).to.be.true @@ -420,7 +420,7 @@ describe('luis:build create multiple applications successfully when input is a f test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/foo/lufiles', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/foo/lufiles', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results', '--log']) .it('should create multiple applications and write dialog assets successfully when input is a folder', async ctx => { expect(ctx.stdout).to.contain('foo.fr-fr.lu loaded') expect(ctx.stdout).to.contain('foo.lu loaded') @@ -526,7 +526,7 @@ describe('luis:build update dialog assets successfully when dialog assets exist' test .stdout() - .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/foo2/lufiles-and-dialog-assets', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results']) + .command(['luis:build', '--in', './test/fixtures/testcases/lubuild/foo2/lufiles-and-dialog-assets', '--authoringKey', uuidv1(), '--botName', 'test', '--dialog', '--out', './results', '--log']) .it('should update dialog assets successfully when dialog assets exist', async ctx => { expect(ctx.stdout).to.contain('foo.fr-fr.lu loaded') expect(ctx.stdout).to.contain('foo.lu loaded')