summaryrefslogtreecommitdiff
path: root/plugins/Boltun/src/Engine/TalkEngine.cpp
blob: 3fe283c64ae9f3de51d0751c100722d5d4a7dac4 (plain)
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
//***********************************************************
//	Copyright © 2008 Valentin Pavlyuchenko
//
//	This file is part of Boltun.
//
//    Boltun 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.
//
//    Boltun 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 Boltun. If not, see <http://www.gnu.org/licenses/>.
//
//***********************************************************

#include "..\boltun.h"

#ifdef _DEBUG

//#define DEBUG_PREFIXES
//#define DEBUG_SHOW_LEVEL
//#define DEBUG_SHOW_VARIANTS
//#define DEBUG_SHOW_SOLUTION_REASON

#endif

//Enabling next define will make a bot more stupid:
//#define EXCLUDE_SPECIAL_WORDS

#ifdef DEBUG_SHOW_VARIANTS
extern void AddBotMessage(tstring s);
#endif

using namespace std;

void TalkBot::UpdateStartChar(tstring& str)
{
	if (!makeLowercase)
		return;
	size_t l = str.length();
	if (l)
	{
		//Answers starting with ' ' must remain unchanged.
		if (str[0] == _T(' '))
		{
			str = str.substr(1);
			return;
		}
		for (size_t i = 0; i < l; i++)
		{
			TCHAR cl = (TCHAR)CharLower((LPTSTR)(void*)(long)str[i]);
			TCHAR cu = (TCHAR)CharUpper((LPTSTR)(void*)(long)str[i]);
			if (i != l - 1)
			{
				//Do not react to BLONDE ANSWERS
				TCHAR ncl = (TCHAR)CharLower((LPTSTR)(void*)(long)str[i + 1]);
				TCHAR ncu = (TCHAR)CharUpper((LPTSTR)(void*)(long)str[i + 1]);
				if (ncl != ncu && str[i + 1] == ncu)
					break;				
			}
			if (cl != cu)
			{
				str[i] = cl;
				break;
			}
		}
	}
}

TalkBot::TalkBot(const Mind& goodMind)
	:mind(goodMind), beSilent(false), makeLowercase(false), 
	understandAlways(false)
{
	contactDatas = new PerContactData<Mind, ContactData, MCONTACT>(mind);
}

TalkBot::~TalkBot()
{
	delete contactDatas;
}

tstring TalkBot::GetInitMessage(MCONTACT contact)
{
	ContactData* d = contactDatas->GetData(contact);
	tstring s = d->initial.GetString();
	contactDatas->PutData(contact);
	return s;
}

tstring TalkBot::ReplaceAliases(const tstring &message)
{
	const TCHAR dividers[] = _T(" \t\n\r,./?\\|;:'\"~!#^&*()_-+=[{]}—\1");
	tstring sentence = message;
	tstring result;
	int len = (int)sentence.length();
	map<int, tstring> sm;
	//Find smiles
	for (size_t i = 0; i < sentence.length() - 1; i++)
	{
		unsigned max = (int)(sentence.length() - i);
		if (max > mind.GetData()->maxSmileLen)
        	max = mind.GetData()->maxSmileLen;
		for (unsigned j = max; j > 0; j--)
		{
			tstring item = sentence.substr(i, j);
			if (mind.GetData()->smiles.find(item) != mind.GetData()->smiles.end())
			{
				sm[i] = item;
				sentence.replace(i, j, _T("\1"));
				break;
			}
		}
	}
    len = (int)sentence.length();
	bool hadQuestionSigns = false;
	int it = 0;
	while (it != len)
	{
		while (it != len && _tcschr(dividers, sentence[it]))
		{
			if (sentence[it] == _T('?'))
				hadQuestionSigns = true;
			map<int, tstring>::iterator smit;
			if (sentence[it] == '\1')
			{	
				smit = sm.find(it);
				result.append((*smit).second);
			}
			else
				result.push_back(sentence[it]);
			it++;
		}
		if (it == len)
			break;
		int start = it;
		while (true)
		{
			while (it != len && !_tcschr(dividers, sentence[it]))
				it++;
			if (it == len || sentence[it] != _T('-'))
				break;
			//If we have-a-word-with-minus, we shouldn't split it
			if (_tcschr(dividers, sentence[it + 1]))
				break;
			it += 2;
		}
		tstring str = sentence.substr(start, it - start);
		map<tstring, tstring>::const_iterator al = mind.GetData()->aliases.find(str);
		if (al != mind.GetData()->aliases.end())
			result.append((*al).second);
		else
			result.append(str);
	}
	return result;
}

tstring TalkBot::AllReplies(const tstring &incomingMessage, ContactData *contactData, Level &maxValue, std::multimap<Level, tstring> &mm)
{
	tstring res;
    //Part 1
	if (FindExact(contactData, incomingMessage, mind.GetData()->widelyUsed, res)) //widelyUsed
	{
		return res;
	}
	//Part 2
	if (FindExact(contactData, incomingMessage, mind.GetData()->study, res)) //study
	{
#ifdef DEBUG_PREFIXES
		mm.insert(make_pair(LOOKSLIKE, _T("(study_all) ")+res));
#else
		mm.insert(make_pair(LOOKSLIKE, res));
#endif
		maxValue = LOOKSLIKE;
	}
	//Part 3
	vector<tstring> sentences;
	SplitSectences(incomingMessage, sentences);
	ValueChooser<> ch(sentences, true); //Using random order of sentences.
	while ((res = ch.GetString()) != _T(""))
	{
		//Part 4
		if (FindExact(contactData, res, mind.GetData()->widelyUsed, res)) //widelyUsed
		{
#ifdef DEBUG_PREFIXES
			mm.insert(make_pair(BEST, _T("(widelyused_sent) ")+res));
#else
			mm.insert(make_pair(BEST, res));
#endif
			if (maxValue > BEST)
				maxValue = BEST;
		}
		//Part 5
		if (FindExact(contactData, res, mind.GetData()->study, res)) //study
		{
#ifdef DEBUG_PREFIXES
			mm.insert(make_pair(LOOKSLIKE, _T("(study_sent) ")+res));
#else
			mm.insert(make_pair(LOOKSLIKE, res));
#endif
			if (maxValue > LOOKSLIKE)
				maxValue = LOOKSLIKE;
		}
		//Part 6
		vector<tstring> keywords, otherwords;
		bool isQuestion;
		SplitAndSortWords(res, keywords, otherwords, isQuestion);
		//Part 7, 8
		res = _T("");
		FindByKeywords(contactData, keywords, res/*, ures*/, isQuestion); //keywords
		if (res != _T(""))
		{
#ifdef DEBUG_PREFIXES
			mm.insert(make_pair(LOOKSLIKE, _T("(keywords) ")+res));
#else
			mm.insert(make_pair(LOOKSLIKE, res));
#endif
			if (maxValue > LOOKSLIKE)
				maxValue = LOOKSLIKE;
		}
/*		if (ures != _T(""))
		{
#ifdef DEBUG_PREFIXES
			mm.insert(make_pair(LOOKSLIKE2, _T("(keywords_unstrict) ")+ures));
#else
			mm.insert(make_pair(LOOKSLIKE2, ures));
#endif
			if (maxValue > LOOKSLIKE2)
				maxValue = LOOKSLIKE2;
		}*/
		//Part 9
		if (FindByOthers(contactData, otherwords, res, isQuestion)) //specialEscapes
		{
#ifdef DEBUG_PREFIXES
			mm.insert(make_pair(BAD, _T("(otherwords) ")+res));
#else
			mm.insert(make_pair(BAD, res));
#endif
			if (maxValue > BAD)
				maxValue = BAD;
		}
	}
	if (!beSilent)
	{
		//Part 10
		if (FindAny(contactData->escape, res)) //escape
		{
#ifdef DEBUG_PREFIXES
			mm.insert(make_pair(FAIL, _T("(escape) ") + res));
#else
			mm.insert(make_pair(FAIL, res));
#endif
			if (maxValue > FAIL)
				maxValue = FAIL;
		}
		//Part 11
		if (!understandAlways && FindAny(contactData->failure, res)) //failure
		{
#ifdef DEBUG_PREFIXES
			mm.insert(make_pair(FAIL, _T("(failure) ") + res));
#else
			mm.insert(make_pair(FAIL, res));
#endif
			if (maxValue > FAIL)
				maxValue = FAIL;
		}
	}
	return tstring();
}

TalkBot::MessageInfo* TalkBot::Reply(MCONTACT contact, tstring incomingMessage, bool saveChoice)
{
	TCHAR* str = new TCHAR[incomingMessage.length()+1];
	_tcscpy(str, incomingMessage.c_str());
	CharLower(str);
	incomingMessage = str;
	delete [] str;
	ContactData *contactData = contactDatas->GetData(contact);

	if (incomingMessage == contactData->lastMessage && GetTickCount() < contactData->lastMessageTime + 30*60*1000)
	{
		MessageInfo *info;
		//only 2-3 repeats
		if (contactData->repeatCount < 2 || contactData->repeatCount == 2 && (rand() % 2))
		{
			const vector<tstring>& v = mind.GetData()->repeats;
			tstring res = v[rand() % v.size()];
#ifdef DEBUG_PREFIXES
			info = new MessageInfo(incomingMessage, _T("(repeat_norm) ") + res);
#else
			info = new MessageInfo(incomingMessage, res);
#endif
		}
		else
#ifdef DEBUG_PREFIXES
			info = new MessageInfo(incomingMessage, _T("(repeat_silence)"));
#else
			info = new MessageInfo(incomingMessage, _T(""));
#endif
		if (saveChoice)
			RecordAnswer(contactData, *info);
		contactDatas->PutData(contact);
		return info;
	}

	multimap<Level, tstring> mm;
	Level maxValue = NOTHING;

	tstring res = AllReplies(incomingMessage, contactData, maxValue, mm);
	if (!res.empty())
	{
		UpdateStartChar(res);
#ifdef DEBUG_PREFIXES
		MessageInfo *info = new MessageInfo(incomingMessage, _T("(widelyused_all) ") + res);
#else
		MessageInfo *info = new MessageInfo(incomingMessage, res);
#endif
		if (saveChoice)
			RecordAnswer(contactData, *info);
		contactDatas->PutData(contact);
		return info;
	}

	incomingMessage = ReplaceAliases(incomingMessage);

	res = AllReplies(incomingMessage, contactData, maxValue, mm);
	if (!res.empty())
	{
		UpdateStartChar(res);
#ifdef DEBUG_PREFIXES
		MessageInfo *info = new MessageInfo(incomingMessage, _T("(widelyused_all) ") + res);
#else
		MessageInfo *info = new MessageInfo(incomingMessage, res);
#endif
		if (saveChoice)
			RecordAnswer(contactData, *info);
		contactDatas->PutData(contact);
		return info;
	}

	//Also does Part 12
	tstring final = ChooseResult(contactData, maxValue, mm);
	MessageInfo *info = new MessageInfo(incomingMessage, final);
	UpdateStartChar(final);
	if (saveChoice)
		RecordAnswer(contactData, *info);
	contactDatas->PutData(contact);
	return info;
}

bool TalkBot::FindExact(ContactData *contactData, const tstring &incomingMessage,
	const multimap<tstring, tstring>& map, tstring& res)
{
	int max = (int)map.count(incomingMessage);
	if (!max)
	{
		TCHAR c = incomingMessage[incomingMessage.length() - 1];
		if (c != _T('?') && c != _T('.') && c != _T('!'))
			return FindExact(contactData, incomingMessage + _T('.'), map, res);
		return false;
	}
	pair<mm_cit, mm_cit> range = map.equal_range(incomingMessage);
	for (mm_cit it = range.first; it != range.second; ++it)
		contactData->chooser.AddChoice((*it).second);
	res = contactData->chooser.Choose();
	return true;
}

void TalkBot::AnswerGiven(MCONTACT contact, const TalkBot::MessageInfo& info)
{
	ContactData *contactData = contactDatas->GetData(contact);
	RecordAnswer(contactData, info);
	contactDatas->PutData(contact);
}

void TalkBot::RecordAnswer(ContactData *contactData, const TalkBot::MessageInfo& info)
{
	contactData->chooser.SaveChoice(info.Answer);
	if (contactData->lastMessage == info.Question)
		contactData->repeatCount++;
	else
		contactData->repeatCount = 0;
	contactData->lastMessageTime = GetTickCount();
	contactData->lastMessage = info.Question;
}

bool TalkBot::FindAny(ValueChooser<> &ch, tstring& res)
{
	if (!ch.GetContainer().size())
		return false;
	res = ch.GetString();
	return true;
}

void TalkBot::SplitSectences(const tstring &incomingMessage, vector<tstring>& vec)
{
	//FIXME: (THINK ABOUT IT:-))these chars not always mark the end of sentence.
	const TCHAR symbols[] = _T(".?!");
    int it = 0, len = (int)incomingMessage.length();
	while (it != len)
	{
		while (it != len && _istspace(incomingMessage[it]))
			it++;
		int start = it;
		while (it != len)
		{
			if (_tcschr(symbols, incomingMessage[it++]))
			{
				//Test for a :-! smile
				if (it > 2 && incomingMessage[it-1] == _T('!')
					&& incomingMessage[it-2] == _T('-')
					&& incomingMessage[it-3] == _T(':'))
					continue;
				while (it != len && _tcschr(symbols, incomingMessage[it]))
					it++;
				break;
			}
		}
		vec.insert(vec.end(), incomingMessage.substr(start, it - start));
	}
}

#ifdef _DEBUG
tstring LevelToStr(TalkBot::Level target)
{
    tstring lev;
	switch (target)
	{
		case TalkBot::BEST: lev = _T("BEST(0)"); break;
		case TalkBot::LOOKSLIKE: lev = _T("LOOKSLIKE(1)"); break;
		case TalkBot::BAD: lev = _T("BAD(2)"); break;
		case TalkBot::FAIL: lev = _T("FAIL(3)"); break;
		case TalkBot::NOTHING: lev = _T("NOTHING(4)"); break;
	}
	return lev;
}
#endif

tstring TalkBot::ChooseResult(ContactData *contactData, Level maxValue, const multimap<Level, tstring> &mm)
{
#ifdef DEBUG_SHOW_VARIANTS
	AddBotMessage(_T(">>Availabe:"));
	for (multimap<Level, tstring>::iterator it = mm.begin(); it != mm.end(); it++)
		AddBotMessage(LevelToStr((*it).first) + _T(": ") + (*it).second);
	AddBotMessage(_T(">>Result:"));
#endif
	if (maxValue == NOTHING)
		return _T("");
	Level target = maxValue;
	int num = (int)mm.count(target);
/*	if (!num)
	{
		target = maxValue;
		num = mm.count(target);
	}*/
	typedef multimap<Level, tstring>::const_iterator lt_cit;
	pair<lt_cit,lt_cit> range = mm.equal_range(target);
	for (lt_cit it = range.first; it != range.second; ++it)
		contactData->chooser.AddChoice((*it).second);
#ifdef DEBUG_SHOW_LEVEL
	tstring lev = LevelToStr(target);
	return lev + _T(": ") + contactData->chooser.Choose();
#else
	return contactData->chooser.Choose();
#endif
}

void TalkBot::FindByKeywords(ContactData *contactData, const vector<tstring> &keywords, tstring& res/*, tstring& ures*/, 
	bool isQuestion)
{
	if (keywords.size() == 0)
		return;
	const multimap<WordsList, tstring> &keys = isQuestion ? mind.GetData()->qkeywords : 
		mind.GetData()->keywords;
	for (multimap<WordsList, tstring>::const_iterator it = keys.begin(); it != keys.end(); ++it)
	{
		float prio;
		if ((*it).first.MatchesAll(keywords/*, strict*/, prio))
#ifdef DEBUG_SHOW_SOLUTION_REASON
				contactData->chooser.AddChoice((tstring)(*it).first + _T(": - ") + (*it).second, prio);
#else
				contactData->chooser.AddChoice((*it).second, prio);
#endif
	}
	res = contactData->chooser.Choose();
}

bool TalkBot::FindByOthers(ContactData *contactData, const vector<tstring> &otherwords, tstring& res, bool isQuestion)
{
	//vector<tstring> results;
	const multimap<WordsList, tstring> &specs = isQuestion ? mind.GetData()->qspecialEscapes : 
		mind.GetData()->specialEscapes;
	for (multimap<WordsList, tstring>::const_iterator it = specs.begin(); 
		it != specs.end(); ++it)
		if ((*it).first.MatchesAny(otherwords))
		{
#ifdef DEBUG_SHOW_SOLUTION_REASON
			contactData->chooser.AddChoice((tstring)(*it).first + _T(": - ") + (*it).second);
#else
			contactData->chooser.AddChoice((*it).second);
#endif
		}
	res = contactData->chooser.Choose();
	if (res.empty())
		return false;
	return true;
}

const Mind& TalkBot::GetMind() const
{
	return mind;
}

void TalkBot::SplitAndSortWords(tstring sentence, vector<tstring>& keywords,
	vector<tstring>& otherwords, bool& isQuestion)
{
	const TCHAR dividers[] = _T(" \t\n\r,./?\\|;:'\"~!#^&*()_-+=[{]}—");
	int len = (int)sentence.length();
	vector<tstring> words;
	map<int, tstring> sm;
	//Find smiles
	for (size_t i = 0; i < sentence.length() - 1; i++)
	{
		unsigned max = (int)(sentence.length() - i);
		if (max > mind.GetData()->maxSmileLen)
        	max = mind.GetData()->maxSmileLen;
		for (unsigned j = max; j > 0; j--)
		{
			tstring item = sentence.substr(i, j);
			if (mind.GetData()->smiles.find(item)
				!= mind.GetData()->smiles.end())
			{
				sm[i] = item;
				sentence.replace(i, j, _T(" "));
				break;
			}
		}
	}
    len = (int)sentence.length();
	bool hadQuestionSigns = false;
	int it = 0;
	while (it != len)
	{
		while (it != len && _tcschr(dividers, sentence[it]))
		{
			if (sentence[it] == _T('?'))
				hadQuestionSigns = true;
			map<int, tstring>::iterator smit;
			if (_istspace(sentence[it]) && (smit = sm.find(it)) != sm.end())
				words.push_back((*smit).second);
			it++;
		}
		if (it == len)
			break;
    	hadQuestionSigns = false;
		int start = it;
		while (true)
		{
			while (it != len && !_tcschr(dividers, sentence[it]))
				it++;
			if (it == len || sentence[it] != _T('-'))
				break;
			//If we have-a-word-with-minus, we shouldn't split it
			if (_tcschr(dividers, sentence[it + 1]))
				break;
			it += 2;
		}
		tstring str = sentence.substr(start, it - start);
		words.push_back(str);
	}
	isQuestion = hadQuestionSigns;
	for (vector<tstring>::iterator it = words.begin(); it != words.end(); ++it)
	{
		if (!isQuestion)
		{
			if (mind.GetData()->question.find(*it) != mind.GetData()->question.end())
				isQuestion = true;
		}
		if (mind.GetData()->special.find(*it) != mind.GetData()->special.end())
			otherwords.push_back(*it);
#ifdef EXCLUDE_SPECIAL_WORDS
		else
#endif
			keywords.push_back(*it);
	}
}

void TalkBot::SetSilent(const bool isSilent)
{
	beSilent = isSilent;
}

void TalkBot::SetLowercase(const bool isLowercase)
{
	makeLowercase = isLowercase;
}

void TalkBot::SetUnderstandAlways(const bool understandAlways)
{
	this->understandAlways = understandAlways;
}