-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuberhal.js
344 lines (289 loc) · 8.46 KB
/
uberhal.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
const fs = require('fs')
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
class Chains {
constructor(data) {
if (!data) {
data = {}
}
this.data = data
}
/**
* Increment the incident weight of the adjacent tokens
*/
addInput(current, previous, next) {
// Create the structure if needed
if (!this.data[current]) {
this.data[current] = [{}, {}] // [previousTokens, nextTokens]
}
// Update next token weight
if (next) {
if (this.data[current][1][next]) {
++this.data[current][1][next]
} else {
this.data[current][1][next] = 1
}
}
// Update previous token weight
if (previous) {
if (this.data[current][0][previous]) {
++this.data[current][0][previous]
} else {
this.data[current][0][previous] = 1
}
}
}
/**
* Get a random token in the previous adjacent list given the current one
* @arg string
* @return string
*/
getPrevious(current) {
return this.get(current, 'previous')
}
/**
* Get a random token in the next adjacent list given the current one
* @arg string
* @return string
*/
getNext(current) {
return this.get(current, 'next')
}
get(current, direction) {
const adj = this.getAdjacent(current, direction)
if (adj) {
const ran = getRandomInt(1, this.sumToken(adj))
return this.sumToken(adj, sum => sum >= ran)
}
return false
}
getAdjacent(current, direction) {
if (this.data[current]) {
if (direction === 0 || direction === 'previous') {
direction = 0
} else {
direction = 1
}
return this.data[current][direction]
}
return false
}
/**
* Sum the weight of all the adjacent tokens
* @arg string Current token
* @arg function Return the current token when the callback is true
*/
sumToken(adjacency, cb) {
let nodeSumWeigth = 0
for (let token in adjacency) {
const tokenWeight = adjacency[token]
nodeSumWeigth += tokenWeight
if (cb && cb(nodeSumWeigth, token)) {
return token
}
}
return nodeSumWeigth
}
}
class UberHAL {
constructor(databaseFile) {
this.startToken = '#START#'
this.endToken = '#END#'
this.rules = {
endSymbols: '.?!',
replace: [
[/\.{3}/g, '…'],
[/"/g, ''],
[/ \- /g, ''],
[/`/g, "'"]
],
// secure: [ TODO
// 'M. '
// ]
}
this.ignoreContext = [ // TODO
// 'a', 'the', 'an', 'some', 'those', 'their', 'this', 'to'
// 'le', 'la', 'les', 'l\'', 'des', 'ces', 'ceux', 'ses'
]
this.beautifyRules = {
replace: [
[/ i /g, ' I '],
[/ (\.|:|;)/g, '$1']
]
}
this.dbFile = './db.json'
if (databaseFile) {
this.dbFile = databaseFile
}
const raw = fs.readFileSync(this.dbFile, 'utf8')
if (raw.length > 5) {
this.chains = new Chains(JSON.parse(raw))
} else {
this.chains = new Chains
}
}
/**
* Transform full text to paragraphs
* @arg string text
* @return array
*/
normalize(text) {
text = text.replace("\n", ' ')
// Replace some patterns
this.rules.replace.forEach(replace => {
text = text.replace(replace[0], replace[1])
})
for (let i = 0; i < this.rules.endSymbols.length; ++i) {
const endSymbol = this.rules.endSymbols[i]
const re = new RegExp('\\' + endSymbol, 'g');
text = text.replace(re, ' ' + endSymbol.trim() + "\n")
}
text = text.toLowerCase().trim()
// Return paragraphs
return text.split("\n")
}
/**
* Beautify a paragraph
* @arg string paragraph
* @return string
*/
beautify(paragraph) {
paragraph = paragraph.trim()
this.beautifyRules.replace.forEach(replace => {
paragraph = paragraph.replace(replace[0], replace[1])
})
return paragraph.charAt(0).toUpperCase() + paragraph.slice(1)
}
/**
* Split a paragraph to tokens
* @arg string
* @return array Array of tokens
*/
lexer(str) {
let arr = str.split(/[ _]+/)
// Remove useless spaces, remove empty strings
return arr.map(w => w.trim()).filter(w => w !== '')
}
/**
* Give UberHAL something to learn
* @arg string text
*/
learn(text) {
let paragraphs = this.normalize(text)
paragraphs.forEach(p => this.learnOneParagraph(p))
// console.log(this.chains.data)
}
/**
* Give UberHAL a paragraph to learn
* @arg string A paragraph
*/
learnOneParagraph(paragraph) {
const tokens = this.lexer(paragraph)
tokens.unshift(this.startToken)
tokens.forEach((token, index) => {
let tokenPrevious = null // start
// let tokenPrevious = this.startToken // start
let tokenNext = this.endToken // end
if (tokens[index + 1]) {
tokenNext = tokens[index + 1]
}
if (tokens[index - 1]) {
tokenPrevious = tokens[index - 1]
}
this.chains.addInput(token, tokenPrevious, tokenNext)
})
}
/**
* Get a paragraph
* @arg string
* @return string
*/
getParagraph(startToken) {
let text = ''
let next = startToken
while (next !== false) {
next = this.chains.getNext(next)
if (next && next !== this.endToken) {
text += ' ' + next
}
}
return text
}
/**
* Speaks
* @return string A random paragraph
*/
speak() {
let text = this.getParagraph(this.startToken)
return this.beautify(text)
}
answer(context) {
const tokens = this.lexer(context)
const ran = getRandomInt(0, tokens.length - 1)
// const token = tokens[0]
const token = tokens[ran].toLowerCase()
let lastGood = token
// console.log('SELECTED TOKEN: ' + token)
let previous = token
let reverseText = ''
let firstPrevious
while (previous !== false && previous !== this.startToken) {
previous = this.chains.getPrevious(previous)
if (!firstPrevious) {
firstPrevious = previous
}
if (previous && firstPrevious && previous !== this.startToken) {
lastGood = previous
reverseText = previous + ' ' + reverseText
}
// console.log(' - ' + previous);
}
// console.log('LAST GOOD: ' + lastGood);
// console.log('TOKEN: ' + token);
// console.log('FIRST PREV: ' + firstPrevious);
if (reverseText && reverseText.length > 1) {
let endText = ''
if (Math.random() > 0.5) {
// Use a direct word from the context
endText = ' ' + token + this.getParagraph(token)
} else {
// Use a correlated word from the context
endText = this.getParagraph(firstPrevious)
}
return this.beautify(reverseText.trim() + endText)
}
return false
// return this.speak()
}
/**
* Clear database
*/
clear() {
this.chains = new Chains
}
/**
* Save the database
* @arg function Callback function
*/
save(cb) {
const ser = JSON.stringify(this.chains.data)
fs.writeFile(this.dbFile, ser, err => {
if (err) {
cb(err)
return console.error(err)
}
if (cb) {
cb(null)
}
})
}
// TODO
infos() {
}
}
module.exports = new UberHAL