-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
83 lines (71 loc) · 2.27 KB
/
index.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
var trump_speeches = "";
var nlp = window.nlp_compromise;
var tokens = [];
function createTokens() {
var nlp_text = nlp.text(trump_speeches);
var terms = nlp_text.terms();
for (var i = 0; i < terms.length; i++) {
tokens.push(terms[i].text);
}
}
function chooseStartingToken() {
var index = Math.floor(Math.random() * tokens.length);
return tokens[index];
}
function findNextWord(prevWords) {
var nextWords = [];
for (var w = 0; w < tokens.length - 1; w++) {
if (prevWords.length > 0 && w - prevWords.length > 0) {
let matchNgram = true;
for (let i = 0; i < prevWords.length; i++) {
if (tokens[w - i] != prevWords[prevWords.length - 1 -i]) {
matchNgram = false;
break;
}
}
if (matchNgram === true) {
nextWords.push(tokens[w + 1]);
}
}
}
var word = nextWords[Math.floor(Math.random() * nextWords.length)]; // choose a random next word
return word;
}
function generate(len, gramlen) {
var currentWord = chooseStartingToken();
var prev = [];
prev.push(currentWord);
var sentence = currentWord + " ";
var wordcount = 0;
while (wordcount < len || currentWord.indexOf(".") < 0) { // while we haven't found a period
currentWord = findNextWord(prev);
sentence += currentWord + " ";
prev.push(currentWord);
if (prev.length > gramlen) {
prev.shift();
}
wordcount++;
}
// return sentence;
document.getElementById('speech').innerHTML = sentence;
}
function start() {
const url = './speeches.txt';
const GRAM_LEN = 2;
const OUT_MIN_LEN = 20;
fetch(url)
.then(function (resp) {
console.log('loading');
resp.text().then(speech => {
trump_speeches = speech;
createTokens();
generate(OUT_MIN_LEN, GRAM_LEN);
console.log(`loaded, length ${OUT_MIN_LEN}, ${GRAM_LEN}-gram`);
})
document.getElementById("generate").addEventListener("click", () => generate(OUT_MIN_LEN, GRAM_LEN));
})
.catch(function (error) {
console.log(error);
});
}
start();