- Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathLearningChatbot.java
More file actions
Latest commit
911 lines (827 loc) · 26.3 KB
/
Copy pathLearningChatbot.java
File metadata and controls
911 lines (827 loc) · 26.3 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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
/* "Zero"-knowledge Learning ChatBot Copyright (C) 2014-2016 Daniel Boston (ProgrammerDan)
*
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
importjava.util.*;
importjava.util.regex.*;
publicclassLearningChatbot {
/**
* Static definition of final word in a statement. It never has
* any descendents, and concludes all statements. This is the only
* "starting knowledge" granted the bot.
*/
publicstaticfinalChatWordENDWORD = newChatWord("\n");
/**
* The Brain of this operation.
*/
privateChatbotBrainbrain;
/**
* Starts LearningChatbot with a new brain
*/
publicLearningChatbot() {
brain = newChatbotBrain();
}
/**
* Starts LearningChatbot with restored brain.
*/
publicLearningChatbot(Stringfilename) {
thrownewUnsupportedOperationException("Not yet implemented");
}
/**
* Invocation method.
*/
publicvoidbeginConversation() {
ChatbotBraincb = newChatbotBrain();
Scannerdialog = newScanner(System.in);
booleanmore = true;
while (more) {
System.out.print(" You? ");
Stringinput = dialog.nextLine();
if (input.equals("++done")) {
System.exit(0);
} elseif (input.equals("++save")) {
System.out.println("Saving not yet implemented, sorry!");
System.exit(0);
} elseif (input.equals("++help")) {
getHelp();
}else {
cb.decay();
cb.digestSentence(input);
}
System.out.print("Chatbot? ");
System.out.println(cb.buildSentence());
}
}
/**
* Help display
*/
publicstaticvoidgetHelp() {
System.out.println("At any time during the conversation, type");
System.out.println(" ++done");
System.out.println("to exit without saving.");
System.out.println("Or type");
System.out.println(" ++save");
System.out.println("to exit and save the brain.");
System.out.println();
}
/**
* Get things started.
*/
publicstaticvoidmain(String[] args) {
System.out.println("Welcome to the Learning Chatbot");
System.out.println();
getHelp();
LearningChatbotlc = null;
if (args.length > 0) {
System.out.printf("Using %s as brain file, if possible.", args[0]);
lc = newLearningChatbot(args[0]);
} else {
lc = newLearningChatbot();
}
lc.beginConversation();
}
/**
* The ChatbotBrain holds references to all ChatWords and has various
* methods to decompose and reconstruct sentences.
*/
staticclassChatbotBrain {
/**
* A tracking of all observed words. Keyed by the String version of
* the ChatWord, to allow uniqueness across all ChatWords
*/
privateMap<String,ChatWord> observedWords;
/**
* This brain is going to be able to keep track of "topics" by way of
* a word frequency map. That way, it can generate sentences based
* on topic-appropriateness.
*/
privateMap<ChatWord, Double> wordFrequencyLookup;
/**
* This holds the actual word frequencies, for quick isolation of
* highest frequency words.
*/
privateNavigableMap<Double, Collection<ChatWord>> wordFrequency;
/**
* This holds the count of words observed total.
*/
privateintwordCount;
/**
* This holds the current "values" of all words.
*/
privatedoublewordValues;
/**
* A "word" that is arbitrarily the start of every sentence
*/
privateChatWordstartWord;
/**
* Rate of decay of "topics".
*/
privatedoubledecayRate;
// These values configure various features of the recursive
// sentence construction algorithm.
/** Nominal (target) length of sentences */
publicstaticfinalintNOMINAL_LENGTH = 10;
/** Max length of sentences */
publicstaticfinalintMAX_LENGTH = 25;
/** Sentence creation timeout */
publicstaticfinallongTIMEOUT = 5000;
/** Topic words to match against */
publicstaticfinalintTOPICS = 7;
/** Topic word split: % of global topic words, remainder sentence */
publicstaticfinaldoubleTOPIC_SPLIT = 0.48;
/** Minimum branches to consider for each word */
publicstaticfinalintMIN_BRANCHES = 2;
/** Maximum branches to consider for each word */
publicstaticfinalintMAX_BRANCHES = 6;
/** % chance as integer out of 100 to skip a word */
publicstaticfinalintSKIP_CHANCE = 30;
/** % chance as integer to skip a word that would cause a loop */
publicstaticfinalintLOOP_CHANCE = 5;
/** % chance that punctuation will happen at all */
publicstaticfinalintPUNCTUATION_CHANCE = 40;
/** % chance that a particular punctuation will be skipped */
publicstaticfinalintPUNCTUATION_SKIP_CHANCE = 50;
/** % of high frequency words to skip, to avoid "the, of" etc. */
publicstaticfinalintTOPIC_SKIP = 1;
/** % chance that we'll examine all words in frequency list again
* if we fail to branch enough times the first time through our list*/
publicstaticfinalintBREADTH_ASSURANCE_CHANCE = 50;
/** The last sentence observed by the bot, as a value map */
privateNavigableMap<Double,Collection<ChatWord>> lastSentence;
/**
* Convenience parameter to use a common random source
* throughout the brain.
*/
privateRandomrandom;
/**
* Gets the Chatbot started, sets up data structures necessary
*/
publicChatbotBrain() {
observedWords = newHashMap<String,ChatWord>();
observedWords.put("\n",ENDWORD);
startWord = newChatWord("");
observedWords.put("",startWord);
wordFrequencyLookup = newHashMap<ChatWord, Double>();
wordFrequency = newTreeMap<Double, Collection<ChatWord>>();
decayRate = 0.10;
wordCount = 0;
wordValues = 0.0;
random = newRandom();
lastSentence = newTreeMap<Double, Collection<ChatWord>>();
}
/**
* More complex digest method (second edition) that takes a sentence,
* cuts it up, and links up the words based on ordering.
* It is sensitive to punctuation, and also simple typos (like
* forgetting to put spaces after punctuation, etc.).
* Note the character class is somewhat complex to deal with
* stupid English things like hyphenation, possessives, and
* abbreviations.
*/
publicvoiddigestSentence(Stringsentence) {
Scannerscan = newScanner(sentence);
ChatWordprior = null;
ChatWordcurrent = null;
StringcurrentStr = null;
StringcurrentPnc = null;
clearLastSentence();
while (scan.hasNext()) {
currentStr = scan.next();
PatternwordAndPunctuation =
Pattern.compile("([a-zA-Z\\-_'0-9]+)([^a-zA-Z\\-_'0-9]?)[^a-zA-Z\\-_'0-9]*?");
MatcherfindWords = wordAndPunctuation.matcher(currentStr);
// Basically this lets us find words-in-word typos like this:
// So,bob left his clothes with me again.
// where "So,bob" becomes "So," "bob"
while (findWords.find()) {
currentStr = findWords.group(1);
currentPnc = findWords.group(2);
if (currentStr != null) {
if (observedWords.containsKey(currentStr)) {
current = observedWords.get(currentStr);
} else {
current = newChatWord(currentStr);
observedWords.put(currentStr, current);
}
addToLastSentence(current);
incrementWord(current);
if (currentPnc != null && !currentPnc.equals("")) {
current.addPunctuation(currentPnc.charAt(0));
}
if (prior != null) {
prior.addDescendent(current);
}
if (prior == null) {
startWord.addDescendent(current);
}
prior = current;
}
}
}
if (prior != null) { // finalize.
prior.addDescendent(ENDWORD);
}
}
/** Helper to clear lastSentence. */
privatevoidclearLastSentence() {
for (Doublekey : lastSentence.keySet()) {
lastSentence.get(key).clear();
}
lastSentence.clear();
}
/** Helper to add a word to the last sentence collection */
privatevoidaddToLastSentence(ChatWordcw) {
Doublevalue = valueWord(cw);
Collection<ChatWord> words;
if (lastSentence.containsKey(value)) {
words = lastSentence.get(value);
} else {
words = newHashSet<ChatWord>();
lastSentence.put(value, words);
}
words.add(cw);
}
/** Helper to value a word using a logarithmic valuation */
privateDoublevalueWord(ChatWordword) {
if (word.getWord().length() > 0) {
return (Math.log(word.getWord().length()) / Math.log(4));
} else {
return0.0; // empty words have no value.
}
}
/**
* Increments the value of a word (catalogues a new sighting).
* I use a logarithmic value function (log base 4) computed against
* the length of the word. In this way, long words are valued slightly
* higher. This is approximate to reality, although truthfully corpus
* frequency is a better measure of word value than word length.
*/
publicvoidincrementWord(ChatWordword) {
DoublecurValue;
DoublenextValue;
Collection<ChatWord> freqMap;
if (wordFrequencyLookup.containsKey(word)) {
curValue = wordFrequencyLookup.get(word);
freqMap = wordFrequency.get(curValue);
freqMap.remove(word);
} else {
curValue = 0.0;
}
nextValue=curValue+valueWord(word);
wordFrequencyLookup.put(word, nextValue);
freqMap = wordFrequency.get(nextValue);
if (freqMap == null) {
freqMap = newHashSet<ChatWord>();
wordFrequency.put(nextValue, freqMap);
}
freqMap.add(word);
wordCount++;
wordValues++;
}
/**
* Decays a particular word by decay rate.
*/
publicvoiddecayWord(ChatWordword) {
DoublecurValue;
DoublenextValue;
Collection<ChatWord> freqMap;
if (wordFrequencyLookup.containsKey(word)) {
curValue = wordFrequencyLookup.get(word);
freqMap = wordFrequency.get(curValue);
freqMap.remove(word);
} else {
return;
}
wordValues-=curValue; // remove old decay value
nextValue=curValue-(curValue*decayRate);
wordValues+=nextValue; // add new decay value
wordFrequencyLookup.put(word, nextValue);
freqMap = wordFrequency.get(nextValue);
if (freqMap == null) {
freqMap = newHashSet<ChatWord>();
wordFrequency.put(nextValue, freqMap);
}
freqMap.add(word);
}
/**
* Decay all word's frequency values. This allows changes
* in the bot's perceptions of conversation topics
*/
publicvoiddecay() {
for (ChatWordcw : wordFrequencyLookup.keySet()) {
decayWord(cw);
}
}
/**
* Gets a set of words that appear to be "top" of the frequency
* list.
*/
publicSet<ChatWord> topicWords(intmaxTopics) {
Set<ChatWord> topics = newHashSet<ChatWord>();
intmaxGlobalTopics = (int) (maxTopics * (double)TOPIC_SPLIT);
intmaxSentenceTopics = maxTopics;
intnTopics = 0;
inttopicSkip = (int)(((float)wordCount * (float)TOPIC_SKIP)/100f);
//System.out.println("Topics:");
for (Doubleweight: wordFrequency.descendingKeySet()) {
for (ChatWordword: wordFrequency.get(weight)) {
if (topicSkip <= 0) {
topics.add(word);
//System.out.printf("\t%2f %s (global)", weight, word.getWord());
nTopics++;
if (nTopics == maxGlobalTopics) break;
} else {
topicSkip--;
}
}
if (nTopics == maxGlobalTopics) break;
}
//System.out.println();
for (Doubleweight: lastSentence.descendingKeySet()) {
for (ChatWordword: lastSentence.get(weight)) {
topics.add(word);
//System.out.printf("\t%2f %s (last)", wordFrequencyLookup.get(word), word.getWord());
nTopics++;
if (nTopics == maxSentenceTopics) break;
}
if (nTopics == maxSentenceTopics) break;
}
//System.out.printf("\nFinal count: %d\n", topics.size());
returntopics;
}
/**
* Uses word frequency records to prefer to build on-topic
* sentences.
* Feature highlights:
* - There is a built-in depth maximum to prevent too much looping
* - Loops are detected directly within the recursive function, and
* while they are technically allowed, there is a high chance that
* loops will be avoided.
* - This is a depth-first search, so the depth maximum and timeout
* together help encourage branch pruning.
* - The maximizing function is on-topic-ness, with a small preference
* for ending sentences. Basically, sentences that don't involve
* topic words are weighted very low, while sentences involving
* as many topic words as possible are weighted high.
* - ChatWords know which ChatWords they precede most often, so
* sentences are constructed making heavy use of this feature
*/
publicStringbuildSentence() {
intmaxDepth = NOMINAL_LENGTH+
random.nextInt(MAX_LENGTH - NOMINAL_LENGTH);
ChatSentencecs = newChatSentence(startWord);
// We don't want to take too long to "think of an answer"
longtimeout = System.currentTimeMillis() + TIMEOUT;
doublebestValue = buildSentence(cs, topicWords(TOPICS), 0.0, 0, maxDepth, timeout);
returncs.toString();
}
/**
* Recursive portion of the buildSentence algorithm.
*/
publicdoublebuildSentence(ChatSentencesentence,
Set<ChatWord> topics, doublecurValue,
intcurDepth, intmaxDepth, longtimeout){
if (curDepth==maxDepth || System.currentTimeMillis() > timeout) {
returncurValue;
}
// Determine how many branches to enter from this node
intmaxBranches = MIN_BRANCHES + random.nextInt(MAX_BRANCHES - MIN_BRANCHES);
// try a few "best" words from ChatWord's descendent list.
ChatWordword = sentence.getLastWord();
NavigableMap<Integer, Collection<ChatWord>> roots =
word.getDescendents();
// Going to keep track of current best encountered sentence
doublebestSentenceValue = curValue;
ChatSentencebestSentence = null;
intcurBranches = 0;
// This is to combat prematurely ended sentences.
while (curBranches < MIN_BRANCHES) {
for (Integerfreq : roots.descendingKeySet()) {
for (ChatWordcurWord : roots.get(freq)) {
intchance = random.nextInt(100);
if (curWord.equals(ENDWORD)) {
if (chance>=SKIP_CHANCE) {
doubleendValue = random.nextDouble() * wordFrequency.lastKey();
/* The endword's value is a random portion of
* the highest frequency word's value, so it's
* comparable, also gives a slight preference
* to ending sentences.*/
if (curValue+endValue > bestSentenceValue) {
bestSentenceValue = curValue+endValue;
bestSentence = newChatSentence(sentence);
// Try to add punctuation if possible.
addPunctuation(bestSentence);
bestSentence.addWord(curWord); // then end.
}
curBranches++;
}
} else {
booleanloop = sentence.hasWord(curWord);
/* Include a little bit of chance in the inclusion
* of any given word, whether a loop or not.*/
if ( (!loop&&chance>=SKIP_CHANCE) ||
(loop&&chance<LOOP_CHANCE)) {
doublewordValue = topics.contains(curWord)?
wordFrequencyLookup.get(curWord):0.0;
ChatSentencebranchSentence = newChatSentence(sentence);
branchSentence.addWord(curWord);
addPunctuation(branchSentence);
doublebranchValue = buildSentence(branchSentence,
topics, curValue+wordValue, curDepth+1,
maxDepth, timeout);
if (branchValue > bestSentenceValue) {
bestSentenceValue = branchValue;
bestSentence = branchSentence;
}
curBranches++;
}
}
if (curBranches == maxBranches) break;
}
if (curBranches == maxBranches) break;
}
if (random.nextInt()>=BREADTH_ASSURANCE_CHANCE) break;
}
if (bestSentence != null) {
sentence.replaceSentence(bestSentence);
}
returnbestSentenceValue;
}
/**
* Adds punctuation to a sentence, potentially.
*/
publicvoidaddPunctuation(ChatSentencesentence) {
ChatWordword = sentence.getLastWord();
NavigableMap<Integer, Collection<Character>> punc = word.getPunctuation();
if (punc.size()>0 && random.nextInt(100)<PUNCTUATION_CHANCE){
IntegerpuncMax = punc.lastKey();
Collection<Character> bestPunc = punc.get(puncMax);
CharacterpuncPick = null;
for (Integerfreq : punc.descendingKeySet()) {
for (CharactercurPunc : punc.get(freq)) {
if (random.nextInt(100)>=PUNCTUATION_SKIP_CHANCE) {
puncPick = curPunc;
break;
}
}
if (puncPick != null) break;
}
if (puncPick != null) {
sentence.addCharacter(puncPick);
}
}
}
@Override
publicStringtoString() {
StringBuildersb = newStringBuilder();
sb.append("ChatBrain[");
sb.append(observedWords.size());
sb.append("]:");
for (Map.Entry<String,ChatWord> cw : observedWords.entrySet()) {
sb.append("\n\t");
sb.append(wordFrequencyLookup.get(cw.getValue()));
sb.append("\t");
sb.append(cw.getValue());
}
returnsb.toString();
}
}
/**
* Useful helper class to construct sentences.
*/
staticclassChatSentenceimplementsCloneable {
/**
* List of words.
*/
privateList<Object> words;
/**
* Quick search construct to have O(ln) lookup times.
*/
privateSet<Object> contains;
/**
* Starts to build a sentence with a single word as anchor
*/
publicChatSentence(ChatWordanchor) {
if (anchor == null) {
thrownewIllegalArgumentException("Anchor must not be null");
}
words = newArrayList<Object>();
contains = newHashSet<Object>();
words.add(anchor);
contains.add(anchor);
}
/**
* Starts a sentence using an existing ChatSentence. Also used for
* cloning.
*/
publicChatSentence(ChatSentencesrc) {
words = newArrayList<Object>();
contains = newHashSet<Object>();
appendSentence(src);
}
/**
* Adds a word to a sentence
*/
publicChatSentenceaddWord(ChatWordword) {
if (word == null) {
thrownewIllegalArgumentException("Can't add null word");
}
words.add(word);
contains.add(word);
returnthis;
}
/**
* Adds a character to a sentence.
*/
publicChatSentenceaddCharacter(Characterpunc) {
if (punc == null) {
thrownewIllegalArgumentException("Can't add null punctuation");
}
words.add(punc);
contains.add(punc);
returnthis;
}
/**
* Replace a sentence with some other sentence.
* Useful to preserve references.
*/
publicChatSentencereplaceSentence(ChatSentencesrc) {
words.clear();
contains.clear();
appendSentence(src);
returnthis;
}
publicChatSentenceappendSentence(ChatSentencesrc) {
words.addAll(src.getWords());
contains.addAll(src.getWords());
returnthis;
}
/**
* Get last word of the sentence.
*/
publicChatWordgetLastWord() {
for (inti=words.size()-1; i>=0; i--) {
if (words.get(i) instanceofChatWord) {
return (ChatWord) words.get(i);
}
}
thrownewIllegalStateException("No ChatWords found!");
}
/**
* Checks if the sentence has a word
*/
publicbooleanhasWord(ChatWordword) {
returncontains.contains(word);
}
/**
* Counts the number of words in a sentence.
*/
publicintcountWords() {
intcnt = 0;
for (Objecto : words) {
if (oinstanceofChatWord) {
cnt++;
}
}
returncnt;
}
/**
* Gets all the words of the sentence
*/
privateList<Object> getWords() {
returnwords;
}
/**
* Returns the sentence as a string.
*/
@Override
publicStringtoString() {
StringBuffersb = newStringBuffer();
for (Objecto : words) {
if (oinstanceofChatWord) {
ChatWordcw = (ChatWord) o;
sb.append(" ");
sb.append( cw.getWord() );
} else {
sb.append(o);
}
}
returnsb.toString().trim();
}
/**
* Clones this sentence.
*/
@Override
publicObjectclone() {
returnnewChatSentence(this);
}
}
/**
* ChatWord allows the creation of words that track how they are
* connected to other words in a forward fashion. In this way it is
* possible to construct arbitrary length sentences involving a set
* of keywords harvested from statements. Trust me, it's possible.
*/
staticclassChatWord {
/** The word. */
privateStringword;
/** Collection of punctuation observed after this word */
privateNavigableMap<Integer, Collection<Character>> punctuation;
/** Lookup linking observed punctuation to where they are in ordering */
privateMap<Character, Integer> punctuationLookup;
/** Punctionation observation count */
privateIntegerpunctuationCount;
/** Collection of ChatWords observed after this word */
privateNavigableMap<Integer, Collection<ChatWord>> firstOrder;
/** Lookup linking observed words to where they are in ordering */
privateMap<ChatWord, Integer> firstOrderLookup;
/** First order antecedent word count */
privateIntegerfirstOrderCount;
/**
* Creates a new ChatWord that is aware of punctuation that
* follows it, and also ChatWords that follow it.
*/
publicChatWord(Stringword){
this.word = word;
this.firstOrder = newTreeMap<Integer, Collection<ChatWord>>();
this.firstOrderLookup = newHashMap<ChatWord, Integer>();
this.firstOrderCount = 0;
this.punctuation = newTreeMap<Integer, Collection<Character>>();
this.punctuationLookup = newHashMap<Character, Integer>();
this.punctuationCount = 0;
}
/**
* Including this for now, but I don't like it -- it returns all
* descendents wholesale. I think what would be better is some
* function that returns a descendent based on some characteristic.
*/
protectedNavigableMap<Integer, Collection<ChatWord>> getDescendents() {
returnfirstOrder;
}
/**
* Returns how many descendents this word has seen.
*/
protectedintgetDescendentCount() {
returnfirstOrderCount;
}
/**
* Gets the lookup map for descendents
*/
protectedMap<ChatWord, Integer> getDescendentsLookup() {
returnfirstOrderLookup;
}
/** As conversation progresses, word orderings will be encountered.
* The descendent style of "learning" basically weights how often
* words are encountered together, and is strongly biased towards
* encountered ordering.
* Thus, when constructing a "reply", the bot can use what it
* has "learned" about precedence and ordering to construct
* phrases that may or may not make sense. It's a grand adventure!
* This function allows recording a new occurence of a word after
* this ChatWord. For word recording purposes, it is recommended
* that all but [-a-zA-Z0-9] be removed. This isn't required, but
* as we're discussing speech and not high forms of communication it
* should be sufficient.
*/
publicvoidaddDescendent(ChatWordnext) {
if(next != null){
firstOrderCount++;
intnextCount = 1;
Collection<ChatWord> obs = null;
// If we've already seen this word, clean up prior membership.
if(firstOrderLookup.containsKey(next)){
nextCount = firstOrderLookup.remove(next);
obs = firstOrder.get(nextCount);
// Remove from prior obs count order
obs.remove(next);
nextCount++;
}
obs = firstOrder.get(nextCount);
if (obs == null) { // we don't have this order yet
obs = newHashSet<ChatWord>();
firstOrder.put(nextCount, obs);
}
firstOrderLookup.put(next, nextCount);
obs.add(next);
}
}
/**
* Some words have punctuation after them more often than not.
* This allows the ChatBrain to record occurrences of punctuation
* after a word.
*/
publicvoidaddPunctuation(Characterpunc) {
if(punc != null){
punctuationCount++;
intpuncCount = 1;
Collection<Character> obs = null;
// If we've already seen this punc, clean up prior membership.
if(punctuationLookup.containsKey(punc)){
puncCount = punctuationLookup.remove(punc);
obs = punctuation.get(puncCount);
// Remove from prior obs count order
obs.remove(punc);
puncCount++;
}
obs = punctuation.get(puncCount);
if (obs == null) { // we don't have this order yet
obs = newHashSet<Character>();
punctuation.put(puncCount, obs);
}
punctuationLookup.put(punc, puncCount);
obs.add(punc);
}
}
/**
* Including this for now, but I don't like it -- it returns all
* punctuation wholesale. I think what would be better is some
* function that returns punctuation based on some characteristic.
*/
protectedNavigableMap<Integer, Collection<Character>> getPunctuation() {
returnpunctuation;
}
/**
* Gets count of punctuation encountered.
*/
protectedintgetPunctuationCount() {
returnpunctuationCount;
}
/**
* Gets lookup of punctuations encountered.
*/
protectedMap<Character, Integer> getPunctuationLookup() {
returnpunctuationLookup;
}
/**
* Gets the String backing this ChatWord.
*/
publicStringgetWord() {
returnword;
}
/**
* ChatWords are equivalent with the String they wrap.
*/
@Override
publicinthashCode() {
returnword.hashCode();
}
/**
* ChatWord equality is that ChatWords that wrap the same String
* are equal, and a ChatWord is equal to the String that it contains.
*/
@Override
publicbooleanequals(Objecto){
if (o == this) {
returntrue;
}
if (oinstanceofChatWord) {
return ((ChatWord)o).getWord().equals(this.getWord());
}
if (oinstanceofString) {
return ((String)o).equals(this.getWord());
}
returnfalse;
}
/**
* Returns this ChatWord as a String.
*/
@Override
publicStringtoString() {
StringBuildersb = newStringBuilder();
sb.append("ChatWord[");
sb.append(word);
sb.append("]desc{");
for (Integerkey : firstOrder.keySet() ) {
Collection<ChatWord> value = firstOrder.get(key);
sb.append(key);
sb.append(":[");
for (ChatWordcw : value) {
sb.append(cw.getWord());
sb.append(",");
}
sb.append("],");
}
sb.append("}punc{");
for (Integerkey : punctuation.keySet() ) {
Collection<Character> value = punctuation.get(key);
sb.append(key);
sb.append(":[");
for (Characterc : value) {
sb.append("\"");
sb.append(c);
sb.append("\",");
}
sb.append("],");
}
sb.append("}");
returnsb.toString();
}
}
}