"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BotonicNLU = void 0;
/* eslint-disable @typescript-eslint/unbound-method */
var tfjs_node_1 = require("@tensorflow/tfjs-node");
var fs_1 = require("fs");
var path_1 = require("path");
var constants_1 = require("./constants");
var data_reader_1 = require("./data-reader");
var intents_processor_1 = require("./intents-processor");
var model_manager_1 = require("./model-manager");
var normalizer_1 = require("./preprocessing-tools/normalizer");
var stemmer_1 = require("./preprocessing-tools/stemmer");
var tokenizer_1 = require("./preprocessing-tools/tokenizer");
var preprocessor_1 = require("./preprocessor");
var file_system_1 = require("./util/file-system");
var object_tools_1 = require("./util/object-tools");
var BotonicNLU = /** @class */ (function () {
    function BotonicNLU(_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.normalizer, normalizer = _c === void 0 ? new normalizer_1.DefaultNormalizer() : _c, _d = _b.tokenizer, tokenizer = _d === void 0 ? new tokenizer_1.DefaultTokenizer() : _d, _e = _b.stemmer, stemmer = _e === void 0 ? new stemmer_1.DefaultStemmer() : _e;
        this.engines = {};
        this.engines.normalizer = normalizer;
        this.engines.tokenizer = tokenizer;
        this.engines.stemmer = stemmer;
    }
    Object.defineProperty(BotonicNLU.prototype, "model", {
        set: function (model) {
            this.modelManager = model_manager_1.ModelManager.fromModel(model);
        },
        enumerable: false,
        configurable: true
    });
    BotonicNLU.prototype.loadModel = function (modelPath, modelDataPath) {
        return __awaiter(this, void 0, void 0, function () {
            var modelData, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        modelData = file_system_1.readJSON(modelDataPath);
                        this.language = modelData.language;
                        this.maxSeqLen = modelData.maxSeqLen;
                        this.vocabulary = modelData.vocabulary;
                        this.intentsProcessor = intents_processor_1.IntentsProcessor.fromDecoder(modelData.intents);
                        this.preprocessor = preprocessor_1.Preprocessor.fromModelData(modelData, this.engines);
                        _a = this;
                        return [4 /*yield*/, model_manager_1.ModelManager.fromModelPath(modelPath)];
                    case 1:
                        _a.modelManager = _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    BotonicNLU.prototype.predict = function (sentence) {
        var input = tfjs_node_1.tensor([this.preprocessor.preprocess(sentence)]);
        var intentId = this.modelManager.predict(input);
        var intent = this.intentsProcessor.decode(intentId);
        return intent;
    };
    BotonicNLU.prototype.predictProbabilities = function (sentence) {
        var _this = this;
        var input = tfjs_node_1.tensor([this.preprocessor.preprocess(sentence)]);
        var encodedPrediction = this.modelManager.predictProbabilities(input);
        return encodedPrediction.map(function (intentConfidence) {
            var intent = _this.intentsProcessor.decode(intentConfidence.intentId);
            return {
                intent: intent,
                confidence: intentConfidence.confidence,
            };
        });
    };
    BotonicNLU.prototype.readData = function (options, readerConfig) {
        this.language = options.language;
        this.maxSeqLen = options.maxSeqLen;
        return data_reader_1.DatasetReader.readData(options.path, {
            csvSeparator: readerConfig === null || readerConfig === void 0 ? void 0 : readerConfig.csvSeparator,
        });
    };
    BotonicNLU.prototype.trainTestSplit = function (options) {
        if (options.testPercentage > 1 || options.testPercentage < 0) {
            throw new RangeError('testPercentage should be a number between 0 and 1.');
        }
        var data = object_tools_1.shuffle(options.data);
        var trainSet = [];
        var testSet = [];
        if (options.stratify !== false) {
            var intents = Array.from(new Set(data.map(function (sample) { return sample.label; })));
            var _loop_1 = function (intent) {
                var intentData = data.filter(function (sample) { return sample.label == intent; });
                var intentSize = intentData.length;
                var testSize = Math.round(intentSize * options.testPercentage);
                testSet = testSet.concat(intentData.slice(0, testSize));
                trainSet = trainSet.concat(intentData.slice(testSize, intentSize));
            };
            for (var _i = 0, intents_1 = intents; _i < intents_1.length; _i++) {
                var intent = intents_1[_i];
                _loop_1(intent);
            }
        }
        else {
            var dataSize = data.length;
            var testSize = Math.round(dataSize * options.testPercentage);
            testSet = testSet.concat(data.slice(0, testSize));
            trainSet = trainSet.concat(data.slice(testSize, dataSize));
        }
        this.preprocessor = preprocessor_1.Preprocessor.fromData(trainSet, this.language, this.maxSeqLen, this.engines);
        this.vocabulary = this.preprocessor.vocabulary;
        this.intentsProcessor = intents_processor_1.IntentsProcessor.fromDataset(trainSet);
        var _a = this.inputOutputSplit(trainSet), xTrain = _a[0], yTrain = _a[1];
        var _b = this.inputOutputSplit(testSet), xTest = _b[0], yTest = _b[1];
        return [xTrain, xTest, yTrain, yTest];
    };
    BotonicNLU.prototype.inputOutputSplit = function (data) {
        var _this = this;
        var x = tfjs_node_1.tensor(data.map(function (sample) { return _this.preprocessor.preprocess(sample.feature); }));
        var y = tfjs_node_1.tensor(data.map(function (sample) { return _this.intentsProcessor.encode(sample.label); }));
        return [x, y];
    };
    BotonicNLU.prototype.createModel = function (options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var wordEmbeddingsConfig, parameters, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        wordEmbeddingsConfig = {
                            type: options.wordEmbeddingsType || '10k-fasttext',
                            dimension: options.wordEmbeddingsDimension || 300,
                            language: this.language,
                            vocabulary: this.vocabulary,
                        };
                        parameters = {
                            maxSeqLen: this.maxSeqLen,
                            learningRate: options.learningRate,
                            intentsCount: this.intentsProcessor.intentsCount,
                            trainableEmbeddings: (_a = options.trainableEmbeddings) !== null && _a !== void 0 ? _a : true,
                        };
                        _b = this;
                        return [4 /*yield*/, model_manager_1.ModelManager.fromModelTemplate(options.template, wordEmbeddingsConfig, parameters)];
                    case 1:
                        _b.modelManager = _c.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    BotonicNLU.prototype.train = function (x, y, options) {
        return __awaiter(this, void 0, void 0, function () {
            var parameters;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        parameters = {
                            x: x,
                            y: y,
                            epochs: (options === null || options === void 0 ? void 0 : options.epochs) || 10,
                            batchSize: (options === null || options === void 0 ? void 0 : options.batchSize) || 8,
                            validationSplit: (options === null || options === void 0 ? void 0 : options.validationSplit) || 0.2,
                        };
                        return [4 /*yield*/, this.modelManager.train(parameters)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    BotonicNLU.prototype.evaluate = function (x, y) {
        var accuracy = this.modelManager.evaluate(x, y);
        return accuracy;
    };
    BotonicNLU.prototype.saveModel = function (path) {
        return __awaiter(this, void 0, void 0, function () {
            var modelDir, modelDataPath, modelData;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        modelDir = path ||
                            path_1.join(process.cwd(), 'src', constants_1.NLU_DIR, constants_1.MODELS_DIR, this.preprocessor.language);
                        fs_1.mkdirSync(modelDir, { recursive: true });
                        modelDataPath = path_1.join(modelDir, constants_1.MODEL_DATA_FILENAME);
                        modelData = {
                            language: this.preprocessor.language,
                            intents: this.intentsProcessor.decoder,
                            maxSeqLen: this.preprocessor.maxSeqLen,
                            vocabulary: this.preprocessor.vocabulary,
                        };
                        fs_1.writeFileSync(modelDataPath, JSON.stringify(modelData));
                        return [4 /*yield*/, this.modelManager.saveModel(modelDir)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return BotonicNLU;
}());
exports.BotonicNLU = BotonicNLU;
//# sourceMappingURL=botonic-nlu.js.map