UNPKG

asksuite-core

Version:
101 lines (84 loc) 2.94 kB
const { CacheRedis } = require('../util/CacheRedis'); const md5 = require('md5'); const AsksuiteProcessingNaturalUtils = require('../AsksuiteProcessingNaturalUtils'); const AsksuiteTranslator = require('../util/Translator'); const defaultFallbackIntent = require('../util/defaultFallbackIntent'); class ExactMatcherAccessor { constructor(config) { this.config = config.config; this.client = config.redis; this.caches = {}; this.utils = new AsksuiteProcessingNaturalUtils(); this.caches = new CacheRedis({ client: this.client, prefixKey: `exact_matcher`, expirationTime: 0, isJson: false, }); } async resolveText(request) { const { companyId, language: requestLanguage, languages, defaultLanguage } = request; const language = this.utils.resolveLanguage(requestLanguage, languages); let { text } = request; let processingStep = {}; if (defaultLanguage && language.substr(0, 2) !== defaultLanguage.substr(0, 2)) { const result = await this.resolveText({ ...request, defaultLanguage: language, }); if (result.intent !== 'naoentendi') { return result; } const asksuiteTranslator = new AsksuiteTranslator( this.config.INFOCHAT_DATA_SERVER, this.config.GOOGLE_TRANSLATE_KEY, this.config.TRANSLATION_API_URL ); const translation = await asksuiteTranslator.translateByTranslationApi(text, language, 'pt-br', languages); text = translation.translation; } const textHash = md5(this.normalizeText(text)); const key = `${companyId}:${defaultLanguage.substr(0, 2)}:${textHash}`; const intentFound = await this.caches.get(key); const dialogFound = this.utils.findDialogByIntent(request, intentFound); processingStep = dialogFound.processingStep; processingStep.cacheKey = key; let dialog = ''; if (dialogFound && dialogFound.dialog) { dialog = dialogFound.dialog; } if (this.isIntentNotMapped(processingStep)) { processingStep.intentFound = intentFound.intent; } const intent = intentFound && !this.isIntentNotMapped(processingStep) ? intentFound : (request.findIntent && request.findIntent.intent) || defaultFallbackIntent(companyId).intent; return { intent, dialog, fromCache: true, extractedData: null, processingStep, }; } isIntentNotMapped(processingStep) { return processingStep.fallbackReason === 'intent_not_mapped'; } normalizeText(text) { try { return text .replace(/\s\s+/g, ' ') .replace(/[.,\/#!$%^&*;:{}=\-_`~()?@]/g, '') .normalize('NFD') .replace(/[\u0300-\u036f]/g, '') .toLowerCase() .trim(); } catch (e) { console.error('RedisService.normalizeText', text, e); return text; } } } module.exports = ExactMatcherAccessor;