Commit 762bfc3e by softwhiskey8

0.1

1 parent 13dfce61
node_modules/
package-lock.json
log.txt
MIT License
Copyright (c) 2020 Dasha Samples
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{
"formatVersion": "2",
"dialogue": {
"file": "main.dsl"
},
"nlu": {
"language": "ru-RU",
"skills": [
"sentiment",
"common_phrases",
"common-numbers"
],
"customIntents": {
"file": "intents.json"
}
},
"nlg": {
"type": "phrases",
"file": "phrasemap.json",
"signatureFile": "phrasemap.json"
},
"name": "megafon-phone-book"
}
library
import "canHearYou.dsl";
import "dontUnderstand.dsl";
import "hangup.dsl";
import "hello.dsl";
import "repeatAndPing.dsl";
library
preprocessor digression can_hear_you_preprocessor
{
conditions { on true priority 100; }
var retriesLimit=2;
var counter=0;
do
{
if (digression.can_hear_you.resetOnRecognized)
{
set digression.can_hear_you.counter = 0;
#log(digression.can_hear_you.counter);
}
set digression.can_hear_you.resetOnRecognized = true;
#log(digression.can_hear_you.resetOnRecognized);
return;
}
transitions
{
}
}
digression can_hear_you
{
conditions { on #messageHasAnyIntent(digression.can_hear_you.triggers) priority -100; }
var retriesLimit = 2;
var counter = 0;
var resetOnRecognized=false;
var triggers = ["can_you_hear_me"];
var responses: Phrases[] = ["i_can_hear_you"];
do
{
set $cjm = external performed_stage($cjm, "can_hear_you_dig");
if (digression.can_hear_you.counter == digression.can_hear_you.retriesLimit)
{
goto bye;
}
set digression.can_hear_you.counter = digression.can_hear_you.counter + 1;
#log(digression.can_hear_you.counter);
set digression.can_hear_you.resetOnRecognized = false;
for (var item in digression.can_hear_you.responses)
{
#say(item, repeatMode: "ignore");
}
#repeat(accuracy: "repeat");
return;
}
transitions
{
bye: goto dont_understand_hangup;
}
}
library
context
{
output status:string?;
output serviceStatus:string?;
}
digression dont_understand_hangup_params
{
conditions { on false; }
var responses: Phrases[] = ["dont_understand_forward"];
var status = "DontUnderstandHangup";
var serviceStatus = "Done";
do
{
set $cjm = external performed_stage($cjm, "dont_understand_hangup_params");
}
transitions
{
}
}
digression dont_understand
{
conditions { on true priority -1000; }
var retriesLimit=0;
var counter=0;
var resetOnRecognized=false;
var responses: Phrases[] = ["dont_understand"];
do
{
set $cjm = external performed_stage($cjm, "dont_understand");
if (digression.dont_understand.counter == digression.dont_understand.retriesLimit)
{
goto hangup;
}
set digression.dont_understand.counter=digression.dont_understand.counter+1;
set digression.dont_understand.resetOnRecognized = false;
for (var item in digression.dont_understand.responses)
{
#say(item, repeatMode: "ignore");
//#say("dont_understand_question");
}
#repeat(accuracy: "short");
return;
}
transitions
{
hangup: goto dont_understand_hangup;
}
}
preprocessor digression dont_understand_preprocessor
{
conditions { on true priority 50000; }
do
{
if (digression.dont_understand.resetOnRecognized)
{
set digression.dont_understand.counter = 0;
}
set digression.dont_understand.resetOnRecognized = true;
return;
}
transitions
{
}
}
node dont_understand_hangup
{
do
{
set $cjm = external performed_stage($cjm, "dont_understand_hangup");
for (var item in digression.dont_understand_hangup_params.responses)
{
#say(item, repeatMode: "ignore");
}
set $status=digression.dont_understand_hangup_params.status;
set $serviceStatus=digression.dont_understand_hangup_params.serviceStatus;
//#forward("12223334455"); //use if you want to transfer a call
#disconnect();
goto do_before_exit;
}
transitions
{
do_before_exit: goto do_before_exit;
}
}
\ No newline at end of file
library
context
{
output serviceStatus: string?;
}
digression hangup
{
conditions
{
on true tags: onclosed;
}
var serviceStatus = "UserHangup";
do
{
set $cjm = external performed_stage($cjm, "hangup");
set $serviceStatus = digression.hangup.serviceStatus;
//#disconnect();
goto do_before_exit;
}
transitions
{
do_before_exit: goto do_before_exit;
}
}
library
/**
* Reaction if nothing meaningful happens in the dialogue for too long.
*/
preprocessor digression hello
{
conditions { on #getIdleTime() - digression.hello.lastIdleTime > digression.hello.idleTimeLimit tags: ontick; }
var idleTimeLimit=8000;
var lastIdleTime=0;
var retriesLimit=2;
var counter=0;
do
{
set digression.hello.lastIdleTime=#getIdleTime();
if (digression.hello.counter > digression.hello.retriesLimit)
{
goto hangup;
}
set digression.hello.counter=digression.hello.counter+1;
#say("hello", repeatMode: "ignore");
//#say("dont_understand_question");
#repeat(accuracy: "short");
return;
}
transitions
{
hangup: goto hello_hangup;
}
}
preprocessor digression hello_preprocessor
{
conditions { on true priority 50000; }
do
{
set digression.hello.lastIdleTime = 0;
set digression.hello.counter = 0;
return;
}
transitions
{
}
}
node hello_hangup
{
do
{
set $cjm = external performed_stage($cjm, "hello_hangup");
#say("dont_understand_hangup");
set $status="EmptyCall";
set $serviceStatus="Done";
//#disconnect();
goto do_before_exit;
}
transitions
{
do_before_exit: goto do_before_exit;
}
}
library
preprocessor digression repeat_preprocessor
{
conditions { on true priority 50000; }
var retriesLimit=2;
var counter=0;
do
{
if (digression.repeat.resetOnRecognized)
{
set digression.repeat.counter = 0;
#log(digression.repeat.counter);
}
set digression.repeat.resetOnRecognized = true;
#log(digression.repeat.resetOnRecognized);
return;
}
transitions
{
}
}
digression repeat_hangup_params
{
conditions { on false; }
var responses: Phrases[] = ["dont_understand_hangup"];
var status = "RepeatHangup";
var serviceStatus = "Done";
do
{
set $cjm = external performed_stage($cjm, "repeat_hangup_params");
}
transitions
{
}
}
digression repeat
{
conditions { on #messageHasAnyIntent(digression.repeat.triggers); }
var retriesLimit = 2;
var counter = 0;
var resetOnRecognized=false;
var triggers = ["repeat", "dont_understand"];
var responses: Phrases[] = ["i_said"];
do
{
set $cjm = external performed_stage($cjm, "repeat_dig");
if (digression.repeat.counter == digression.repeat.retriesLimit)
{
goto hangup;
}
set digression.repeat.counter = digression.repeat.counter + 1;
#log(digression.repeat.counter);
set digression.repeat.resetOnRecognized = false;
for (var item in digression.repeat.responses)
{
#say(item, repeatMode: "ignore");
}
#repeat(accuracy: "short");
return;
}
transitions
{
hangup: goto repeat_or_ping_hangup;
}
}
digression ping
{
conditions { on #messageHasAnyIntent(digression.ping.triggers) and !#messageHasIntent("greeting") priority -100; }
var retriesLimit = 2;
var counter = 0;
var resetOnRecognized=false;
var triggers = ["ping"];
do
{
set $cjm = external performed_stage($cjm, "ping_dig");
if (digression.repeat.counter == digression.repeat.retriesLimit)
{
goto hangup;
}
set digression.repeat.counter = digression.repeat.counter + 1;
#log(digression.repeat.counter);
set digression.repeat.resetOnRecognized = false;
#repeat(accuracy: "short");
return;
}
transitions
{
hangup: goto repeat_or_ping_hangup;
}
}
node repeat_or_ping_hangup
{
do
{
set $cjm = external performed_stage($cjm, "repeat_or_ping_hangup");
for (var item in digression.repeat_hangup_params.responses)
{
#say(item, repeatMode: "ignore");
}
set $status=digression.repeat_hangup_params.status;
set $serviceStatus=digression.repeat_hangup_params.serviceStatus;
#disconnect();
goto do_before_exit;
}
transitions
{
do_before_exit: goto do_before_exit;
}
}
{
"version": "v2",
"intents": {
"accept": {
"includes": [
"да",
"ну да",
"давай",
"ага",
"угу",
"окей",
"все верно",
"правильно"
],
"excludes":[
"але",
"передавай"
]
},
"decline": {
"includes": [
"нет",
"хватит",
"не надо",
"не нужно",
"достаточно",
"отказ",
"отказываюсь"
],
"excludes":[
"может",
"надо бы",
"пока все",
"не помню"
]
},
"wait_message": {
"includes": [
"передайте",
"скажите"
]
},
"im_done": {
"includes": [
"вроде всё",
"больше ничего",
"я закончил",
"пока всё"
]
},
"ready_to_message": {
"includes": [
"давай оставим запрос",
"оставить запрос",
"оставить срочную заявку",
"хочу оставить сообщение",
"надо бы"
],
"excludes":[
]
},
"not_ready_to_message": {
"includes": [
"мне не нужен автоответчик",
"опять бот",
"мне не запрос надо, а менеджера",
"мне человек нужен прямо сейчас"
]
},
"shared_phone": {
"includes": [
"общий номер",
"это общий телефон",
"это не мой номер",
"нужен добавочный"
]
},
"not_know": {
"includes": [
"я не знаю",
"без понятия",
"кто бы знал",
"не располагаю такой информацией"
]
},
"forget": {
"includes": [
"не помню",
"не могу сейчас вспомнить",
"знаете я забыл",
"что то запамятовал"
],
"excludes":[
"я не знаю"
]
},
"agree": {
"includes": [
"можно",
"можете",
"разрешаю"
],
"excludes": [
]
},
"additional": {
"includes": [
"добавочный",
"добавочный номер"
],
"excludes":[
"я не знаю"
]
}
}
}
\ No newline at end of file
import "commonReactions/all.dsl";
context {
input phone: string;
input caller: string;
output cjm: string[] = [];
output need_ask_name: boolean = true;
output template_id: number = 3;
output conversation_start: number = 0;
output conversation_begin: number = 0;
output conversation_stop: number = 0;
output conversation_status: string = "normal";
output abonent_request: string[] = [];
output another_phone_number: string = "";
output abonent_name: string = "";
output company_name: string = "";
output phone_suffix: string = "";
}
external function numbers_from_text(text: string): string;
external function dates_from_text(text: string): string;
external function part_of_the_day(): string;
external function array_size(arr: unknown): number;
external function string_trim(one_line: string): string;
external function is_empty(check: unknown): boolean;
external function performed_stage(stages: string[], stage: string): string[];
external function sleep_ms(duration: number): unknown;
external function json_encode(object: unknown): string;
external function time_stamp(): number;
external function math_floor(value: number, presision: number|empty = 0): number;
external function math_round(value: number, presision: number|empty = 0): number;
external function math_ceil(value: number, presision: number|empty = 0): number;
external function phone_human(phone: string): string;
external function last_four(phone: string): string;
external function hours_now(): number;
external function check_mobile_code(phone: string): boolean;
external function countWords(message: string): number;
start node root
{
do
{
set $cjm = external performed_stage($cjm, "root");
set $conversation_start = external time_stamp();
goto caller_id;
}
transitions
{
caller_id: goto caller_id;
}
}
node caller_id
{
do
{
set $cjm = external performed_stage($cjm, "caller_id");
#connectSafe($phone);
#waitForSpeech(1000);
// Строим приветствие, зависящее от времени суток
var part_of_the_day_name = external part_of_the_day();
var abonent_greeting = "Здравствуйте";
if (part_of_the_day_name == "night")
{
set abonent_greeting = "Доброй ночи";
}
if (part_of_the_day_name == "morning")
{
set abonent_greeting = "Доброе утро";
}
if (part_of_the_day_name == "day")
{
set abonent_greeting = "Добрый день";
}
if (part_of_the_day_name == "evening")
{
set abonent_greeting = "Добрый вечер";
}
// Запоминаем временной штамп перед самой первой репликой
set $conversation_begin = external time_stamp();
#sayText(abonent_greeting, options: {speed: 1.15});
#say("dont_understand_question");
wait *;
}
transitions
{
end_conversation: goto end_conversation on true;
}
onexit
{
end_conversation: do
{
var abonent_say = #getMessageText();
set $abonent_request = external performed_stage($abonent_request, abonent_say);
}
}
}
node end_conversation
{
do
{
set $cjm = external performed_stage($cjm, "end_conversation");
#say("end_conversation");
goto do_before_exit;
}
transitions
{
do_before_exit: goto do_before_exit;
}
}
node do_before_exit
{
do
{
set $cjm = external performed_stage($cjm, "do_before_exit");
set $conversation_stop = external time_stamp();
exit;
}
transitions
{
}
}
digression @exit_dig
{
conditions { on true tags: onclosed; }
do
{
set $cjm = external performed_stage($cjm, "@exit_dig");
set $conversation_status = "broken";
goto do_before_exit;
}
transitions
{
do_before_exit: goto do_before_exit;
}
}
{
"default": {
"voiceInfo": {
"emotion": "good",
"lang": "ru-RU",
"speaker": "alena",
"speed": 1.0
},
"phrases": {
"hello": {
"random": [
[
{
"text": "Алло"
}
],
[
{
"text": "Ало?"
}
],
[
{
"text": "Вы меня слышите?"
}
]
]
},
"i_said": [
{
"text": "Я говорю"
}
],
"sorry_wont_call": [
{
"text": "Извините за беспокойство, всего доброго, до свидания"
}
],
"i_will_wait": {
"random": [
[
{
"text": "Хорошо, я жду"
}
],
[
{
"text": "Конечно, я подожду"
}
],
[
{
"text": "Хорошо, жду"
}
]
]
},
"i_can_hear_you": [
{
"text": "Да. Я вас слышу."
}
],
"dont_understand": {
"random": [
[
{
"text": "Извините, можете повторить?"
}
],
[
{
"text": "Извините, что то со связью, можете повторить?"
}
],
[
{
"text": "Извините, не расслышала"
}
],
[
{
"text": "Повторите пожалуйста?"
}
]
]
},
"dont_understand_hangup": [
{
"text": "Что то со связью, плохо вас слышно. Пожалуйста, перезвоните. До свидания!"
}
],
"dont_understand_forward": [
{
"text": "Вы знаете, я вас очень плохо слышу. Я сейчас переключу вас на другого оператора"
}
],
"dont_understand_question": [
{
"text": "Скажите: что Вы хотели?"
}
],
"mhm": [
{
"text": "Ага..."
}
],
"yes_i_am_a_robot": [
{
"text": "Да, я робот. Надеюсь это не повлияет на наш дальнейший диалог"
}
],
"is_that_all": [
{
"text": "Это всё?"
}
],
"end_conversation": [
{
"text": "Благодарю за Ваше обращение. Всего доброго. До свидания."
}
],
"non_work_greetings": [
{
"text": "Вы позвонили в компанию эрброкер, мы работаем по будням с 10 до 19 часов, и, к сожалению, сейчас никто не может ответить на ваш звонок. Но я могу передать ваш запрос менеджеру"
}
],
"non_work_goodbye": [
{
"text": "Передам всё, и постараюсь чтобы менеджер связался с вами как можно быстрее. До свидания!"
}
],
"non_work_short_goodbye": [
{
"text": "Хорошо, просто передам что вы звонили. До свидания!"
}
],
"something_else": [
{
"text": "Ещё что-нибудь?"
}
],
"im_wrighting": {
"first": [
{
"text": "Записываю"
}
],
"repeat": {
"random": [
[
{
"text": "Слушаю"
}
],
[
{
"text": "Я вся внимание"
}
]
]
}
},
"work_greetings": [
{
"text": "Вы позвонили в компанию Р-брокер, меня зовут Надежда, чем я могу помочь?"
}
],
"work_goodbye": [
{
"text": "Ваше обращение принято и будет направлено на соответствующего сотрудника. В ближайшее время сотрудник Вам перезвонит. Благодарю за Ваше обращение. Всего доброго. До свидания."
}
],
"ask_company_name": [
{
"text": "Подскажите, название Вашей организации?"
}
],
"request_accepted": [
{
"text": "Ваше обращение принято и будет направлено на соответствующего сотрудника. В ближайшее время сотрудник Вам перезвонит."
}
],
"get_client_request": [
{
"text": "Опишите, пожалуйста, суть вопроса/ситуации."
}
],
"get_cell_phone": [
{
"text": "Тогда продиктуйте мобильный, что бы мы смогли 100% дозвониться Вам"
}
],
"check_is_shared": [
{
"text": "Подскажите, по этому номеру наш специалист сможет дозвониться напрямую к вам или это общий номер?"
}
],
"get_phone_suffix": [
{
"text": "Подскажите, пожалуйста, ваш добавочный номер, чтобы менеджер мог дозвониться к вам напрямую"
}
],
"get_another_phone": [
{
"text": "Продиктуете ваш контактный номер телефона"
}
],
"hello_propose": [
{
"text": "Меня зовут Аврора. Подкл+ючим домашний высокоскоростной интернет?! Воспользуйтесь эксклюзивным предложением!"
}
],
"internet_tv": [
{
"text": "Всего за 369 рублей в месяц вы получите интернет со скоростью 100 мегабит в секунду, а также 168 интерактивных тв-каналов в высоком качестве!"
}
],
"onlyou": [
{
"text": "Только для вас безлимитный высокоскоростной интернет и интерактивное телевидение с онлайн-кинотеатрами всего за 1 рубль первый месяц!"
}
],
"willcall": [
{
"text": "Оставайтесь на связи, наш менеджер свяжется с вами в течение 15 минут"
}
],
"phone_number": [
{
"text": "Верно я понимаю, что связаться с вами можно по номеру"
}
],
"kontakt_nomer": [
{
"text": "Пожалуйста, скажите ваш контактный номер телефона."
}
],
"thanks_foryour_time": [
{
"text": "Благодарим вас за уделенное время!"
}
],
"otherposib": [
{
"text": "Воспользуйтесь этой, а также другими возможностями, включая услуги видеонаблюдения и виртуальной АТС уже сейчас! "
}
],
"keep_in_touch": [
{
"text": "Благодарим вас за уделенное время! Остаемся на связи!"
}
]
},
"types": {},
"macros": {
"hello": {},
"i_said": {},
"sorry_wont_call": {},
"i_will_wait": {},
"i_can_hear_you": {},
"dont_understand": {},
"dont_understand_hangup": {},
"dont_understand_forward": {},
"dont_understand_question": {},
"mhm": {},
"yes_i_am_a_robot": {},
"is_that_all": {},
"end_conversation": {},
"non_work_greetings":{},
"non_work_goodbye":{},
"non_work_short_goodbye": {},
"something_else":{},
"im_wrighting":{},
"work_greetings": {},
"work_goodbye": {},
"ask_company_name": {},
"request_accepted": {},
"get_client_request": {},
"get_cell_phone": {},
"check_is_shared": {},
"get_phone_suffix": {},
"get_another_phone": {},
"hello_propose": {},
"internet_tv": {},
"onlyou": {},
"willcall": {},
"phone_number": {},
"kontakt_nomer": {},
"thanks_foryour_time": {},
"otherposib": {},
"keep_in_touch": {}
}
}
}
\ No newline at end of file
{
"node::root": {
"common.position": {
"x": 600,
"y": 0
}
},
"node::caller_id": {
"common.position": {
"x": 598.377372534425,
"y": 134.60160992786908
}
},
"node::end_conversation": {
"common.position": {
"x": 600,
"y": 1090.3536507636595
}
},
"node::do_before_exit": {
"common.position": {
"x": 600,
"y": 709.2035244482049
}
},
"node::repeat_or_ping_hangup": {
"common.position": {
"x": 0,
"y": 415
}
},
"node::hello_hangup": {
"common.position": {
"x": 0,
"y": 220
}
},
"node::dont_understand_hangup": {
"common.position": {
"x": 0,
"y": 715
}
},
"node::conversation_done": {
"common.position": {
"x": 1480,
"y": 966.137946142489
}
},
"node::wait_message": {
"common.position": {
"x": 2080,
"y": 644.8260546478509
}
},
"node::get_abonent_name": {
"common.position": {
"x": 1480,
"y": 851.0084920989109
}
},
"node::check_abonent_name": {
"common.position": {
"x": 2080,
"y": 893.0535799922327
}
},
"node::say_wrote": {
"common.position": {
"x": 2080,
"y": 770.7061811030865
}
},
"node::add_message": {
"common.position": {
"x": 1480,
"y": 533.057587652757
}
},
"node::ping": {
"common.position": {
"x": 0,
"y": 315
}
},
"node::repeat": {
"common.position": {
"x": 0,
"y": 515
}
},
"node::repeat_hangup_params": {
"common.position": {
"x": 600,
"y": 530
}
},
"node::repeat_preprocessor": {
"common.position": {
"x": 600,
"y": 475
}
},
"node::hello_preprocessor": {
"common.position": {
"x": 600,
"y": 585
}
},
"node::hello": {
"common.position": {
"x": 0,
"y": 115
}
},
"node::hangup": {
"common.position": {
"x": 0,
"y": 20
}
},
"node::dont_understand_preprocessor": {
"common.position": {
"x": 600,
"y": 370
}
},
"node::dont_understand": {
"common.position": {
"x": 0,
"y": 810
}
},
"node::dont_understand_hangup_params": {
"common.position": {
"x": 600,
"y": 420
}
},
"node::can_hear_you": {
"common.position": {
"x": 600,
"y": 645
}
},
"node::exit_dig": {
"common.position": {
"x": 0,
"y": 615
}
},
"node::no_message": {
"common.position": {
"x": 1480,
"y": 734.0697783815012
}
},
"node::non_work_branch": {
"common.position": {
"x": 1046.6676796891302,
"y": 324.76777774720415
}
},
"node::request_accepted": {
"common.position": {
"x": 2680,
"y": 1029.454349255128
}
},
"node::get_client_questions": {
"common.position": {
"x": 2680,
"y": 868.8603922782834
}
},
"node::get_cell_phone": {
"common.position": {
"x": 3280,
"y": 575.5801672846062
}
},
"node::is_shared_phone": {
"common.position": {
"x": 3280,
"y": 389.5873927822081
}
},
"node::check_shared_phone": {
"common.position": {
"x": 2680,
"y": 679.7473236381277
}
},
"node::get_company_name": {
"common.position": {
"x": 2680,
"y": 224.565654864841
}
},
"node::get_another_phone": {
"common.position": {
"x": 3280,
"y": 10.131652410874324
}
},
"node::phone_confirmation": {
"common.position": {
"x": 2680,
"y": 42.55689227944265
}
},
"node::ask_client_name": {
"common.position": {
"x": 2080,
"y": 306.0375290687854
}
},
"node::check_client_name": {
"common.position": {
"x": 2080,
"y": 148.12143450145916
}
},
"node::by_work_branch": {
"common.position": {
"x": 2080,
"y": 26.98742096578726
}
},
"node::get_alter_company_name": {
"common.position": {
"x": 3280,
"y": 136.54309920643223
}
},
"node::check_mobile_code": {
"common.position": {
"x": 2680,
"y": 425.40569848894876
}
}
}
\ No newline at end of file
File mode changed
const fs = require("fs");
const path = require("path");
class AudioResources
{
constructor()
{
this.resources = {};
}
getResourceKey(text, voiceInfo) {
return [
voiceInfo.lang ?? "",
voiceInfo.speaker ?? "",
voiceInfo.emotion ?? "Neutral",
voiceInfo.speed ?? 1,
voiceInfo.variation ?? 0,
text,
].join("|");
}
async appendJson(folder, pack)
{
const errors = [];
let i = 0;
for (const phrase of pack.phrases ?? []) {
i++;
// валидация
if (phrase.phrase === undefined) {
errors.push(`For ${i} phrase field 'phrase' is undefined`);
continue;
}
if (phrase.audio === undefined) {
errors.push(`For ${i} phrase field 'audio' is undefined`);
continue;
}
const audioFile = path.join(folder, phrase.audio);
if (!fs.existsSync(audioFile)) {
errors.push(`For ${i} phrase "${phrase.phrase}" file not found`);
continue;
}
phrase.voice = { ...pack.voice, ...phrase.voice };
const resourceKey = this.getResourceKey(phrase.phrase, phrase.voice ?? {});
if (resourceKey in this.resources) {
// дубликат - не ошибка
console.warn("Skip", i, "phrase because it's duplicate");
continue;
}
this.resources[resourceKey] = audioFile;
}
if(errors.length > 0)
{
console.error(`Was errors ${JSON.stringify(errors)}`)
}
}
async addFolder(folder)
{
const files = fs.readdirSync(folder);
for (const fileName of files)
{
if (path.extname(fileName) === ".json")
{
const fname = path.join(folder, fileName);
console.log(`Parsing ${fname}`);
await this.appendJson(folder, JSON.parse(fs.readFileSync(fname).toString()));
}
}
}
GetPath(text, voiceInfo)
{
const key = this.getResourceKey(text, voiceInfo);
const fpath = this.resources[key];
if (fpath === undefined)
throw new Error(`Failed to get ${key}`);
return fpath;
}
}
module.exports = AudioResources;
\ No newline at end of file
module.exports = exports = {
mobile_codes() {
return [
"900", "902", "903",
"904", "905", "906",
"908", "909", "950",
"951", "953", "960",
"961", "962", "963",
"964", "965", "966",
"967", "968", "969",
"980", "983", "986",
"901", "910", "911",
"912", "913", "914",
"915", "916", "917",
"918", "919", "978",
"981", "982", "984",
"985", "987", "988",
"989", "920", "921",
"922", "923", "924",
"925", "926", "927",
"928", "929", "930",
"931", "932", "933",
"934", "936", "937",
"938", "939", "999",
"952", "958", "977",
"991", "992", "993",
"994", "995", "996"
];
}
};
\ No newline at end of file
This diff is collapsed. Click to expand it.
*.in
*.pid
*.out
!demo*
\ No newline at end of file
*.txt
*.log
*.debug
{
"name": "megafon-phone-book",
"version": "1.0.0",
"description": "",
"author": "",
"license": "MIT",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"devDependencies": {
"prettier": "^2.3.0"
},
"dependencies": {
"string": "^3.3.3",
"moment": "^2.29.1",
"@dasha.ai/sdk": "^0.8.5"
}
}
const fs = require("fs");
const url = require("url");
const axios = require("axios");
const moment = require("moment");
const strings = require("string");
const dataset = require("./dataset");
const sys = require('child_process');
const cct_api = 'http://cct.r-broker.ru/api/';
const cct_key = 'y8Bzq1C0vIwhcrl98emy04JauUlWd7glhvUo2TcWBSkdMYzrKS'
+ 'KhQNMuoU_NecQJVNLIgRA4eeDTX4QFDA6np1VI0ctrmYJkcIQK'
+ 'muMgCjKzqHVSzZ2-n_0vefeFZPCMZJz4NO8xgrPwQ1OWgn_ACt'
+ 'be9DWhSR-yi_-u2k2NcF3Heg193PSKvov9QPlShLtq_UzdQfmb'
+ 'C9uS1-bukZFdFyQ9M6mO8Qnlyzm95ouQPODwqieKjiXIFkXUIW';
const file_sender = '../../htdocs/uploadgd/up.php';
const api_hook_url = 'https://ai.r-broker.ru/api/api.php';
const api_hook_key = 'kd56h4jfhj54f62hjf6d8YgjL9';
const api_hook = api_hook_url + '?key=' + api_hook_key;
const mobile_codes = dataset.mobile_codes();
function empty (value) {
if (value === undefined) return true;
if (value === null) return true;
const str = strings(value);
if (str == "") return true;
if (str.trim() == "") return true;
return false;
}
async function cct_api_service (service, api_request) {
let post_data = JSON.stringify(api_request);
let headers = {
"Language": "ru-RU",
"Authorization": "Bearer " + cct_key,
"Content-Type": "application/json; charset=utf-8"
};
let config = { headers: headers };
let result = await axios.post(cct_api + service, post_data, config);
let wrong_data = { status: 'error', result: 'axios crashed' };
if (result.data === null) return wrong_data
if (result.data === undefined) return wrong_data;
return result.data;
}
module.exports = exports = {
empty (value) {
return empty (value);
},
async ai_api_hook (action, web_hook_data) {
let api_hook_action = api_hook + '&action=' + action;
let post_data = new url.URLSearchParams(web_hook_data);
let result = {};
let wrong_data = { status: 'error', detail: 'axios crashed' };
try {
result = await axios.post(api_hook_action, post_data);
} catch (err) {
wrong_data.detail = JSON.stringify(err, undefined, 2);
result.data = wrong_data;
}
if (empty(result.data)) return wrong_data
return result.data;
},
get_part_of_the_day() {
ts = Date.now();
let date_ob = new Date(ts);
hours = date_ob.getHours();
if (hours < 4) return 'night';
if (hours < 12) return 'morning';
if (hours < 16) return 'day';
if (hours < 24) return 'evening';
return 'night';
},
human_format(abonent_phone) {
let clean_phone = abonent_phone.replace( /[^\d]/g, '' );
var size = clean_phone.length;
var human_phone = "";
if (size < 4) return clean_phone;
if (size == 11) {
prefix = clean_phone.substring(0, 1);
if (prefix == 8) human_phone = prefix; else human_phone = "+" + prefix;
human_phone = human_phone + " (" + clean_phone.substring(1, 4);
human_phone = human_phone + ") " + clean_phone.substring(4, 7);
human_phone = human_phone + "-" + clean_phone.substring(7, 9);
human_phone = human_phone + "-" + clean_phone.substring(9, 11);
return human_phone;
}
if (size == 10) {
human_phone = "+7";
human_phone = human_phone + " (" + clean_phone.substring(0, 3);
human_phone = human_phone + ") " + clean_phone.substring(3, 6);
human_phone = human_phone + "-" + clean_phone.substring(6, 8);
human_phone = human_phone + "-" + clean_phone.substring(8, 10);
return human_phone;
}
const cuts = [ 2, 2, 3, 3 ];
const divs = [ "-", "-", ") ", "(" ];
let phone = clean_phone;
for (var i = 0; i < 4; i ++) {
if (size > cuts[i]) {
size -= cuts[i];
part = phone.substring(size, size + cuts[i]);
human_phone = divs[i] + part + human_phone;
phone = phone.substring(0, size);
} else {
var div = "";
if (divs[i] == "(") div = divs[i];
return div + phone + human_phone;
}
}
return "+" + phone + " " + human_phone;
},
last_four_digits(abonent_phone) {
let clean_phone = abonent_phone.replace( /[^\d]/g, '' );
var size = clean_phone.length;
let last_four = "";
if (size > 3) {
last_four = clean_phone.substring(size - 2, size);
size -= 2;
return clean_phone.substring(size - 2, size) + "-" + last_four;
}
return clean_phone;
},
async cct_numbers_from_text (text) {
const service = 'markers-data';
request = {
debug: false,
input: "text",
channel: "client",
distance: { "min": 0.166667, "mid": 0.166667, "max": 0.166667 },
language: "russian",
text: text,
triggers: [
{ name: "numbers", markers: [ { type: "number" } ] }
]
};
const response = await cct_api_service(service, request);
let result = "";
if (response.status !== "success") return result;
for (trigger of response.result) {
if (trigger.state === "on") {
if (trigger.name === "numbers") {
for (i in trigger.details) {
found = trigger.details[i];
for (j in found) {
element = found[j];
result = result + " " + element.value;
}
}
}
}
}
result = result.replace( /^\s+/, '' );
return result;
},
async cct_dates_from_text (text) {
const service = 'markers-data';
request = {
debug: false,
input: "text",
channel: "client",
distance: { "min": 0.166667, "mid": 0.166667, "max": 0.166667 },
language: "russian",
text: text,
triggers: [
{ name: "dates", markers: [ { type: "date time" } ] }
]
};
const response = await cct_api_service(service, request);
let result = "";
if (response.status !== "success") return result;
for (trigger of response.result) {
if (trigger.state === "on") {
if (trigger.name === "dates") {
for (i in trigger.details) {
found = trigger.details[i];
for (j in found) {
element = found[j];
pattern = element.pattern??"";
if ((pattern === "%date%") && (result === ""))
result = element.value;
}
}
}
}
}
if (result === "") return result;
moment.locale("ru");
result = moment(result, "YYYY-MM-DD").format("DD.MM.YYYY");
return result;
},
renew_last_log_file(last_text_file) {
let sysCommand = 'cat ' + last_text_file + ' >log.txt';
sys.exec(sysCommand, (error, stdout, stderr) => {
if (error) {
console.error(`error: ${error.message}`);
}
if (stderr) {
console.error(`stderr: ${stderr}`);
}
// console.log(`stdout:\n${stdout}`);
});
},
send_to_google_disk(file_name, file_mime) {
let proc = sys.spawnSync('php', [ file_sender, file_name, file_mime ]);
let exit_code = proc.status;
let look_stdout = proc.stdout.toString();
let check_error = proc.error;
let look_stderr = proc.stderr.toString();
if (check_error)
console.log("error: \n" + JSON.stringify(check_error, undefined, 2));
if (look_stderr) console.log("stderr: \n" + look_stderr);
if (look_stdout) console.log("stdout: \n" + look_stdout);
},
is_mobile_code(abonent_phone) {
let clean_phone = abonent_phone.replace( /[^\d]/g, '' );
var size = clean_phone.length;
let phone_code = "";
if (size > 6) {
phone_code = clean_phone.substring(1, 4);
}
return (mobile_codes.indexOf(phone_code)!=-1);
},
pid_name() {
pidName = process.pid;
if (pidName < 10) pidName = '0000' + pidName;
if (pidName < 100) pidName = '000' + pidName;
if (pidName < 1000) pidName = '00' + pidName;
if (pidName < 10000) pidName = '0' + pidName;
return pidName;
},
make_unique_app(app_suffix) {
let app_suffix_file = './threads/' + app_suffix + '/app.dashaapp'
if (fs.existsSync(app_suffix_file)) return './threads/' + app_suffix;
let proc = sys.spawnSync('cp', [ '-rfp', './app', './threads/' + app_suffix ]);
let exit_code = proc.status;
let exit_data = proc.stdout.toString();
let check_error = proc.error;
let look_stderr = proc.stderr.toString();
if (check_error) {
console.log('error: ' + JSON.stringify(check_error, undefined, 2));
return './app';
}
if (look_stderr) {
console.log('stderr: ' + look_stderr);
return './app';
}
app_data = fs.readFileSync('app/app.dashaapp');
app_info = JSON.parse(app_data);
let app_name = app_info.name + '-' + app_suffix;
app_info.name = app_name;
fs.writeFileSync(app_suffix_file, JSON.stringify(app_info, undefined, 2));
return './threads/' + app_suffix;
},
drop_unique_app(app_suffix) {
let proc = sys.spawnSync('rm', [ '-rf', './threads/' + app_suffix ]);
let exit_code = proc.status;
let exit_data = proc.stdout.toString();
let check_error = proc.error;
let look_stderr = proc.stderr.toString();
if (check_error) {
console.log('error: ' + JSON.stringify(check_error, undefined, 2));
return false;
}
if (look_stderr) {
console.log('stderr: ' + look_stderr);
return false;
}
return true;
},
get_conversation_info(app, conv) {
app_data = fs.readFileSync('app/app.dashaapp');
app_info = JSON.parse(app_data);
let app_name = app_info.name;
app_name_full = app.applicationName;
app_id = app.applicationId;
job_id = conv._jobId;
return {
app_name: app_name,
app_name_full: app_name_full,
app_id: app_id,
job_id: job_id
};
}
};
\ No newline at end of file
File mode changed
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!