-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
661 lines (502 loc) · 16.1 KB
/
main.cpp
File metadata and controls
661 lines (502 loc) · 16.1 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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cmath>
#include <map>
#include <random>
using namespace std;
class GramModel
{
public:
GramModel();
virtual string formSentence(string firstWord, int sentLen) = 0;
vector<string> returnTokens(string);
void tokenize(string);
vector <string> words;
int wordCount;
};
class BIGRAM : public GramModel
{
public:
BIGRAM();
void makePairs();
string formSentence(string firstWord, int sentLen);
map<pair<string,string>, int> bigramModel;
};
class TRIGRAM : public GramModel
{
public:
TRIGRAM();
void makeTuples();
void makeTuplesWithStops();
string formSentence(string firstWord, int sentLen);
string formSentence(string firstWord);
map<tuple<string,string,string>, int> trigramModel;
};
class NGRAM : public GramModel
{
public:
NGRAM();
void makeNGrams();
string formSentence(string firstWord);
map<vector<string>,int> ngramModel;
};
GramModel::GramModel(){
wordCount = 0;
words.clear();
}
BIGRAM::BIGRAM(){
bigramModel.clear();
}
TRIGRAM::TRIGRAM(){
trigramModel.clear();
}
NGRAM::NGRAM(){
ngramModel.clear();
}
string removeScraps(string word) {
if (word.back() == '"')
word.pop_back();
if(word.substr(word.length()-1, 1)=="”")
word.pop_back();
if (word.front() == '"')
word.erase(0, 1);
if (word.back() == '\'')
word.pop_back();
if (word[0] == '\'') {
//cout << word << "\n";
word.erase(0, 1);
}
if (word.substr(0, 1) == "’") {
//cout << word << "\n";
word.erase(0, 1);
}
if (word.back() == ',') {
word.pop_back();
}
if(word.back()==';')
word.pop_back();
return word;
}
string removeStops(string word){
string newWord = word;
if(word.back()=='.')
newWord.pop_back();
if(word.back()=='!')
newWord.pop_back();
if(word.back()=='?')
newWord.pop_back();
return newWord;
}
vector<string> GramModel::returnTokens(string sentence)
{
vector<string> tokens;
string word;
istringstream ss(sentence);
while(ss >> word)
{
word = removeScraps(word);
tokens.push_back(word);
//cout << word << "\n";
}
return tokens;
}
void GramModel::tokenize(string sentence)
{
string word;
istringstream ss(sentence);
while(ss >> word)
{
word = removeScraps(word);
transform(word.begin(),word.end(),word.begin(), ::tolower);
if(!all_of(word.begin(),word.end(), ::isdigit)) {
words.push_back(word);
wordCount++;
}
//cout << word << "\n";
}
}
void BIGRAM::makePairs(){
//check for one-word sentence
//proceed
for(auto i = words.begin(); i != words.end(); i++ ){
pair<string, string> bigram = make_pair(removeStops(*i),removeStops(*(i+1)));
bigramModel[bigram]++;
//if second word has stop character, skip two ahead to new sentence.
if((i+1)->back()=='.' || (i+1)->back()=='!')
i++;
}
}
string BIGRAM::formSentence(std::string firstWord, int sentLen) {
string sentence;
string current;
transform(firstWord.begin(),firstWord.end(),firstWord.begin(), ::tolower);
current = firstWord;
//random device
random_device rd;
mt19937 gen(rd());
//checks if firstword is in map.
bool validFirstWord = false;
for(auto& entry : bigramModel) {
if (entry.first.first == current) {
validFirstWord = true;
}
}
//if inputted first word not in map, then selects a random one from the corpus
if(!validFirstWord){
//cout << "Invalid word inputted. Random word selected for seed of sentence.\n";
uniform_int_distribution<> distr(0,words.size()-1);
current = removeStops(words[distr(gen)]);
}
for(int i = 0; i<sentLen; i++){
sentence += current + " ";
vector<string> nextWords;
for(auto& entry : bigramModel) {
if(entry.first.first == current) {
//cout << entry.first.first << "\n";
for(int j = 0; j<entry.second; j++)
nextWords.push_back(entry.first.second);
}
}
int randIndex;
if(nextWords.empty()){
//no more valid words
break;
}
else{
uniform_int_distribution<> distr(0,nextWords.size()-1);
randIndex = distr(gen);
current = nextWords[randIndex];
}
}
sentence.pop_back();
sentence += ".";
return sentence;
}
void TRIGRAM::makeTuples() {
for(auto i = words.begin(); i != words.end(); i++){
tuple<string,string,string> trigram = make_tuple(removeStops(*i),removeStops(*(i+1)),removeStops(*(i+2)));
trigramModel[trigram]++;
if((i+2)->back()=='.' || (i+2)->back()=='!')
i+=2;
}
}
void TRIGRAM::makeTuplesWithStops(){
for(auto i = words.begin(); i != words.end(); i++){
tuple<string,string,string> trigram = make_tuple(*i,*(i+1),*(i+2));
trigramModel[trigram]++;
if((i+2)->back()=='.' || (i+2)->back()=='!')
i+=2;
}
}
//TODO: Create function for finding second current word, implement in both form sentence functions
string TRIGRAM::formSentence(std::string firstWord, int sentLen) {
string sentence,current1,current2;
vector <string> sentenceBuilder;
transform(firstWord.begin(),firstWord.end(),firstWord.begin(), ::tolower);
current1 = firstWord;
//random device
random_device rd;
mt19937 gen(rd());
//checks if firstword is in map.
bool validFirstWord = false;
for(auto& entry : trigramModel) {
if (get<0>(entry.first) == current1) {
validFirstWord = true;
}
}
//if inputted first word not in map, then selects a random one from the corpus
if(!validFirstWord){
cout << "Invalid word inputted. Random word selected for seed of sentence.\n";
uniform_int_distribution<> distr(0,words.size()-1);
current1 = removeStops(words[distr(gen)]);
}
//append first word of sentence
//cout << "First word: " << current1 << "\n";
//find second current word
vector<string> nextWords1;
for(auto& entry : trigramModel) {
if(get<0>(entry.first) == current1) {
//cout << entry.first.first << "\n";
for(int j = 0; j<entry.second; j++)
nextWords1.push_back(get<1>(entry.first));
}
}
int randIndex;
if(nextWords1.empty()){
//no more valid words
cout << "sad\n";
}
else{
uniform_int_distribution<> distr(0,nextWords1.size()-1);
randIndex = distr(gen);
current2 = nextWords1[randIndex];
//cout << "Second word: " << current2 << "\n";
}
//BEGIN LOOPING TRIGRAM
string oneBack;
int missCount = 0;
for(int i = 0; i < sentLen-1; i++){
//cout << "Len pos: " << i << " Words: " << current1 << ", " << current2 << "\n";
vector<string> nextWords2;
nextWords2.clear();
for(auto& entry : trigramModel) {
if(get<0>(entry.first) == current1){
if(get<1>(entry.first) == current2){
for(int j = 0; j<entry.second; j++){
nextWords2.push_back(get<2>(entry.first));
}
}
}
}
if(nextWords2.empty() && i<sentLen-2){
missCount++;
if(missCount>10){
for(auto i = sentenceBuilder.begin(); i!=sentenceBuilder.end(); i++){
if(*i!="")
sentence += *i + " ";
}
sentence.pop_back();
sentence += ".";
return "Hit dead end in Trigram, sentence length: " + to_string(i) + "Sentence: " + sentence;
}
//need to back up and pick a new current 2
//cout << "Not in corpus\n";
current2 = current1;
current1 = oneBack;
i-=2;
sentenceBuilder.pop_back();
}
else if(nextWords2.empty()){
sentenceBuilder.push_back(current1);
current1 = current2;
}
else{
sentenceBuilder.push_back(current1);
uniform_int_distribution<> distr2(0, nextWords2.size()-1);
randIndex = distr2(gen);
oneBack = current1;
current1 = current2;
current2 = nextWords2[randIndex];
}
}
sentenceBuilder.push_back(current1);
for(auto i = sentenceBuilder.begin(); i!=sentenceBuilder.end(); i++){
if(*i!="")
sentence += *i + " ";
}
sentence.pop_back();
sentence += ".";
return sentence;
}
string TRIGRAM::formSentence(string firstWord){
string sentence,current1,current2;
vector <string> sentenceBuilder;
transform(firstWord.begin(),firstWord.end(),firstWord.begin(), ::tolower);
current1 = firstWord;
//random device
random_device rd;
mt19937 gen(rd());
//checks if firstword is in map.
bool validFirstWord = false;
for(auto& entry : trigramModel) {
if (get<0>(entry.first) == current1) {
validFirstWord = true;
}
}
//if inputted first word not in map, then selects a random one from the corpus
if(!validFirstWord){
cout << "Invalid word inputted. Random word selected for seed of sentence.\n";
uniform_int_distribution<> distr(0,words.size()-1);
current1 = removeStops(words[distr(gen)]);
}
//find second current word
vector<string> nextWords1;
for(auto& entry : trigramModel) {
if(get<0>(entry.first) == current1) {
for(int j = 0; j<entry.second; j++)
nextWords1.push_back(get<1>(entry.first));
}
}
int randIndex;
if(nextWords1.empty()){
//no more valid words
cout << "sad\n";
}
else{
uniform_int_distribution<> distr(0,nextWords1.size()-1);
randIndex = distr(gen);
current2 = nextWords1[randIndex];
}
//BEGIN LOOPING TRIGRAM
string oneBack;
int missCount = 0;
bool finito = false;
int i = 0;
while(!finito){
i++;
vector<string> nextWords2;
nextWords2.clear();
for(auto& entry : trigramModel) {
if(get<0>(entry.first) == current1){
if(get<1>(entry.first) == current2){
for(int j = 0; j<entry.second; j++){
nextWords2.push_back(get<2>(entry.first));
}
}
}
}
if(nextWords2.empty()){
missCount++;
if(missCount>10){
for(auto i = sentenceBuilder.begin(); i!=sentenceBuilder.end(); i++){
if(*i!="")
sentence += *i + " ";
}
sentence.pop_back();
sentence += ".";
return "Hit dead end in Trigram, sentence length: " + to_string(i) + "Sentence: " + sentence;
}
//need to back up and pick a new current 2
cout << "Not in corpus\n";
current2 = current1;
current1 = oneBack;
sentenceBuilder.pop_back();
}
else if(nextWords2.empty()){
sentenceBuilder.push_back(current1);
current1 = current2;
}
else{
sentenceBuilder.push_back(current1);
uniform_int_distribution<> distr2(0, nextWords2.size()-1);
randIndex = distr2(gen);
oneBack = current1;
current1 = current2;
current2 = nextWords2[randIndex];
if(current2.back()=='.' || current2.back()=='!' || current2.back()=='?')
finito = true;
}
}
sentenceBuilder.push_back(current1);
sentenceBuilder.push_back(current2);
for(auto i = sentenceBuilder.begin(); i!=sentenceBuilder.end(); i++){
if(*i!="")
sentence += *i + " ";
}
//sentence.pop_back();
return sentence;
}
int main(int argc, char **argv)
{
if(argc < 2){
cout << "Invalid input. Must be ./ngram <corpus name>\n";
exit(1);
}
//open command file
ifstream inStream;
inStream.open(argv[1]);
if(inStream.fail()) {
cout << "failed to open file\n";
exit(1);
}
//initialize data structures
BIGRAM *bg = new BIGRAM();
TRIGRAM *tg = new TRIGRAM();
string line;
//tokenize line by line
while(getline(inStream,line)){
bg->tokenize(line);
tg->tokenize(line);
}
//makepairs
bg->makePairs();
tg->makeTuplesWithStops();
//list pairs
//
// cout << "Bigram Model:\n";
// for(const auto& entry : bg->bigramModel){
// cout << "(" << entry.first.first << ", " << entry.first.second << "): " << entry.second << endl;
// }
//list tuples
// cout << "Trigram Model:\n";
// for(const auto& entry : tg->trigramModel){
// cout << "(" << get<0>(entry.first) << ", " << get<1>(entry.first) << ", " << get<2>(entry.first) << "): " << entry.second << "\n";
// }
//basic sentence gen
cout << "Bigram Sentence, first word I: ";
cout << bg->formSentence("I", 6) << "\n";
//basic sentence gen
cout << "Trigram Sentence, first word I: ";
cout << tg->formSentence("I") << "\n\n\n\n\n";
//CLIENT FOR PREDICTIVE TEXT
bool finito = false;
bool autoEngage = false;
string inputWord,currentSentence,inputAuto;
string backOne = " ";
string backTwo = " ";
string currentWord;
int autoCorrectThreshold = 1;
cout << "Trigram Initialized. Begin typing your sentence, returning input after each word. When you have completed your sentence, enter a '.' \n\n";
cout << "Word: ";
cin >> inputWord;
while(!finito){
//check for stop character
if (inputWord == ".") {
cout << "Stop character received.\n";
break;
}
if(inputWord.back() == '.'){
cout << "Stop character received.\n";
currentSentence += inputWord;
break;
}
//update vals for new word
backTwo = backOne;
backOne = currentWord;
currentWord = inputWord;
currentSentence += inputWord + " ";
cout << currentSentence << " _____\n";
if(!backOne.empty() && !backTwo.empty()){
//cout << "Auto correct Engaged.\n";
int mostLikelyWordFreq = 0;
pair<tuple<string,string,string>,int> mostLikelyTrigram;
for(const auto& entry : tg->trigramModel){
if(get<0>(entry.first)==backOne && get<1>(entry.first)==inputWord && entry.second>mostLikelyWordFreq){
mostLikelyTrigram = entry;
mostLikelyWordFreq = entry.second;
//cout << get<0>(mostLikelyTrigram.first) << get<1>(mostLikelyTrigram.first) << get<2>(mostLikelyTrigram.first) << mostLikelyTrigram.second << "\n";
}
}
if(mostLikelyTrigram.second>autoCorrectThreshold){
//cout << "over threshold: \n";
//cout << get<0>(mostLikelyTrigram.first) << get<1>(mostLikelyTrigram.first) << "\n";
cout << "Were you going to type '" << get<2>(mostLikelyTrigram.first) << "' ? If so, input 'x' and hit return. Otherwise, type your next word. \n\n";
cout << "Word: ";
cin >> inputAuto;
if(inputAuto=="x") {
autoEngage = true;
inputWord = get<2>(mostLikelyTrigram.first);
}
else {
inputWord = inputAuto;
autoEngage = false;
}
}
else{
cout << "Word: ";
cin >> inputWord;
}
}
else{
//cout << currentSentence << " _____\n\n";
cout << "Word: ";
cin >> inputWord;
}
}
currentSentence.pop_back();
currentSentence += ".";
cout << "\nFinal Sentence: " << currentSentence << "\n\n";
return 0;
}