-
Notifications
You must be signed in to change notification settings - Fork 2
/
parse.js
264 lines (240 loc) · 9.95 KB
/
parse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
class YouzParser {
constructor() {
this.input_data_string = null;
this.patterns = [];
this.definitions = {};
this.stopWords = [];
this.keywords = [];
this.temp_vars = {};
this.collections = {};
this.collection_patterns = {};
this.lastMatchedPattern = null; // متغیر برای ذخیره پرانتز آخرین دستور
}
parse(input) {
this.discover_collections(input);
this.input_data_string = input;
const definitionRegex = /#(\S+)\s*:\s*(.*?)\s*\./gs;
let match;
while ((match = definitionRegex.exec(input)) !== null) {
const key = match[1].trim();
const value = match[2].trim();
this.definitions[key] = value;
}
const patternRegex = /\(\s*\+\s*(.*?)\s*-\s*(.*?)\s*\)/gs;
while ((match = patternRegex.exec(input)) !== null) {
const userPattern = match[1].trim();
const botResponses = match[2].split('_').map(response => response.trim());
if (userPattern.startsWith('{')) {
// الگوی کلیدواژهها
const keywords = userPattern.slice(1, -1).split('،').map(keyword => keyword.split('/').map(k => k.trim()));
this.keywords.push({ keywords, botResponses });
} else {
this.patterns.push({ userPattern, botResponses });
}
}
const stopWordsRegex = /-\s*\{\s*(.*?)\s*\}/gs;
while ((match = stopWordsRegex.exec(input)) !== null) {
const words = match[1].split('،').map(word => word.trim());
this.stopWords.push(...words);
}
}
getResponse(userMessage) {
userMessage = this.check_for_collections_pattern( userMessage)
const cleanedMessage = this.removeStopWords(userMessage);
this.lastMatchedPattern = null; // ریست کردن متغیر قبل از هر جستجو
for (let pattern of this.patterns) {
const { userPattern, botResponses } = pattern;
const regexPattern = this.createRegex(userPattern);
const match = cleanedMessage.match(regexPattern);
if (match) {
this.lastMatchedPattern = { userPattern, botResponses }; // ذخیره پرانتز
let responses = botResponses;
let response = responses[Math.floor(Math.random() * responses.length)];
if (response.endsWith('!>')) {
response = this.getAdditionalResponses(response.slice(0, -99).trim(), cleanedMessage);
response = response.replace('!>', '');
}
return this.resolveResponse(response, match);
}
}
const messageWords = cleanedMessage.split(' ');
for (let keywordPattern of this.keywords) {
const { keywords, botResponses } = keywordPattern;
if (this.containsKeywords(messageWords, keywords)) {
this.lastMatchedPattern = { keywords, botResponses }; // ذخیره پرانتز
let response = botResponses[Math.floor(Math.random() * botResponses.length)];
if (response.endsWith('!>')) {
response = this.getAdditionalResponses(response.slice(0, -99).trim(), cleanedMessage);
}
return this.resolveResponse(response, []);
}
}
return "متاسفم، متوجه نشدم.";
}
removeStopWords(message) {
let words = message.split(' ');
words = words.filter(word => !this.stopWords.includes(word));
return words.join(' ');
}
createRegex(pattern) {
return new RegExp(`^${pattern.replace(/\*([0-9]*)/g, '(.*?)')}$`);
}
resolveResponse(response, match) {
let resolvedResponse = response;
for (let i = 1; i < match.length; i++) {
resolvedResponse = resolvedResponse.replace(`*${i}`, match[i].trim());
}
return resolvedResponse.replace(/#(\S+)/g, (match, key) => {
return this.definitions[key] || match;
});
}
containsKeywords(messageWords, keywords) {
return keywords.every(keywordGroup => {
return keywordGroup.some(keyword => messageWords.includes(keyword));
});
}
getAdditionalResponses(initialResponse, userMessage) {
let additionalResponses = initialResponse;
for (let pattern of this.patterns) {
const { userPattern, botResponses } = pattern;
const regexPattern = this.createRegex(userPattern);
const match = userMessage.match(regexPattern);
if (match) {
const responses = botResponses;
const randomResponse = responses[Math.floor(Math.random() * responses.length)];
additionalResponses += " " + this.resolveResponse(randomResponse, match);
}
}
return additionalResponses;
}
_is_temp_var_declaration_line(line) {
line = line.trim();
let words_seperated = line.split(' ');
let first_word = words_seperated[0];
let first_char = first_word[0];
let next_word = words_seperated[1];
if (first_char === '=' && next_word === ':') { return true; }
else { return false; }
}
define_temp_vars(text) {
let lines = text.split('\n');
for (let line of lines) {
line = line.trim();
let is_declaration_line = this._is_temp_var_declaration_line(line);
if (is_declaration_line) {
let chunks = line.split(' ');
let first_chunk = chunks[0];
let last_chunk = chunks[2];
let var_name = first_chunk.slice(1, first_chunk.length);
let value = last_chunk.trim();
this.temp_vars[var_name] = value;
}
}
}
replace_temp_vars(response) {
let lines = response.split('\n');
let result_text = '';
for (let line of lines) {
line = line.trim();
let is_declaration_line = this._is_temp_var_declaration_line(line);
if (!is_declaration_line) {
let chunks = line.split(' ');
for (let chunk of chunks) {
let first_char = chunk[0];
if (first_char === '=') {
let var_name = chunk.slice(1, chunk.length);
console.log(var_name);
result_text += this.temp_vars[var_name] + ' ';
}
else { result_text += chunk + ' '; }
}
}
result_text += '\n';
}
return result_text;
}
_is_answer_part(line) {
let first_char = line[0];
if (first_char === '-') { return true; } else { return false; }
}
discover_collections(input) {
let open_parenthis = false;
let outside_text = '';
let parenthis_depth = 0;
for (let i = 0; i < input.length; i++) {
let char = input[i];
if (char === '(') { open_parenthis = true; parenthis_depth++; }
else if (char === ')') {
parenthis_depth--;
if (parenthis_depth === 0) { open_parenthis = false; continue; }
}
if (open_parenthis) { continue; }
else { outside_text += char; }
}
let lines = outside_text.trim().split('\n');
for (let line of lines) {
if (line.includes('{')) {
let start_index = line.indexOf('{');
let end_index = line.indexOf('}');
let between = line.slice(start_index + 1, end_index);
let items = between.split('،');
for (let i = 0; i < items.length; i++) { items[i] = items[i].trim(); }
let collection_name = line.slice(0, start_index).trim();
this.collections[collection_name] = items;
}
}
}
check_for_collections_pattern(messageText) {
let chunks = messageText.trim().split(' ');
let collection_entries = Object.entries(this.collections);
let result_text = '';
for (let chunk of chunks) {
let is_in_collections = false;
for (let [key, vals_arr] of collection_entries) {
if (vals_arr.includes(chunk)) {
is_in_collections = key;
break;
}
}
if (is_in_collections) { result_text += '&' + is_in_collections + ' '; }
else { result_text += chunk + ' '; }
}
return result_text.trim();
}
}
var savedValue;
function saveInputValue() {
var inputValue = document.getElementById("txt-input").value;
savedValue = inputValue;
}
let youzParser = new YouzParser();
let inputCode = '';
function loadFile(callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'number.yooz', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
inputCode = xhr.responseText;
callback(inputCode);
} else {
console.error('خطا در خواندن فایل');
}
}
};
xhr.send();
}
document.getElementById("btn").addEventListener("click", (event) => {
event.preventDefault();
saveInputValue();
loadFile((data) => {
const userMessage = savedValue;
if (!userMessage || typeof userMessage.trim !== 'function') {
console.error("userMessage is not valid:", userMessage);
return;
}
youzParser.parse(inputCode);
const response = youzParser.getResponse(userMessage);
alert(response);
});
});