-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrandom.js
More file actions
71 lines (55 loc) · 1.77 KB
/
random.js
File metadata and controls
71 lines (55 loc) · 1.77 KB
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
let model = require("./model.json");
let tokenize = require("./tokenize.js");
async function markov(startingPhrase, serverId) {
const TIMEOUT_MS = 5000;
const _startTime = Date.now();
function _timedOut() {
return Date.now() - _startTime > TIMEOUT_MS;
}
function getRandomToken(key) {
if (_timedOut()) return null;
if (!model[serverId][key]) return null;
const object = model[serverId][key];
const tokens = Object.keys(object);
let total = 0;
for (const token of tokens) {
if (_timedOut()) return null;
total += object[token];
}
let rand = Math.random() * total;
for (const token of tokens) {
if (_timedOut()) return null;
rand -= object[token];
if (rand <= 0) {
return token;
}
}
return tokens[tokens.length - 1];
}
function generateString(context) {
if (_timedOut()) return null;
let sentence = tokenize(startingPhrase);
while (!sentence.join("").includes("<!end>")) {
if (_timedOut()) return null;
let dynamicContext = Math.min(context, sentence.length);
let seed = sentence.slice(-dynamicContext).join("");
while (!model[serverId][seed] && dynamicContext > 0) {
if (_timedOut()) return null;
dynamicContext -= 1;
seed = sentence.slice(-dynamicContext).join("");
}
if (!model[serverId][seed]) break;
const token = getRandomToken(seed);
if (!token) return null;
sentence.push(token);
}
return sentence;
}
function generateOutput() {
let str = generateString(3);
if (str == null) return null;
return str.join("").replaceAll("<!end>", "");
}
return generateOutput();
}
module.exports = { markov };