asksuite-core
Version:
97 lines (83 loc) • 2.51 kB
JavaScript
const md5 = require('md5');
const { CacheRedis } = require('../util/CacheRedis');
const AsksuiteUtil = require('../asksuite.util')();
class RasaLayersRedisService {
constructor(config) {
this.config = config;
this.client = config.redis;
this.caches = {};
if (this.client && config.config && config.rasaLayers) {
config.config.rasaLayers.languages &&
config.config.rasaLayers.languages.forEach((lang) => {
this.caches[lang] = new CacheRedis({
client: this.client,
prefixKey: `rasalayers:${lang}`,
expirationTime: config.config.rasaLayers.expiration,
isJson: true,
});
});
}
}
async resolveText(text, language, order, languages) {
const lang = AsksuiteUtil.resolveLanguage(language, languages);
if (!text || !order || !order.length || !language || !this.caches[lang]) {
return null;
}
const key = md5(this.normalizeText(text));
const cached = await this.caches[lang].get(key);
if (cached && cached.matches && cached.matches.length) {
for (let i = 1; i <= order.length; i++) {
const match = cached.matches.find(
(e) => JSON.stringify(e.order) === JSON.stringify(order.slice(0, i)),
);
if (match) {
return match.intent;
}
}
}
return null;
}
async saveToCache(intent, text, language, order, languages) {
const lang = AsksuiteUtil.resolveLanguage(language, languages);
if (!this.caches[lang]) {
return;
}
const key = md5(this.normalizeText(text));
let cached = await this.caches[lang].get(key);
if (!cached) {
cached = new CacheItem();
cached.text = text;
}
if (order && order.length) {
const orderStr = JSON.stringify(order);
if (!cached.matches.find((e) => JSON.stringify(e.order) === orderStr)) {
cached.matches.push({
order,
intent,
});
}
await this.caches[lang].set(key, cached);
}
}
normalizeText(text) {
try {
return text
.trim()
.replace(/\s\s+/g, ' ')
.replace(/[.,\/#!$%^&*;:{}=\-_`~()?@]/g, '')
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase();
} catch (e) {
console.error('RedisService.normalizeText', text, e);
return text;
}
}
}
class CacheItem {
constructor() {
this.text = '';
this.matches = [];
}
}
module.exports = RasaLayersRedisService;