Skip to content

Commit

Permalink
Add check for logic adapter agreement
Browse files Browse the repository at this point in the history
  • Loading branch information
gunthercox committed Oct 31, 2016
1 parent 0f55cd9 commit 245b949
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
28 changes: 28 additions & 0 deletions chatterbot/adapters/logic/multi_adapter.py
@@ -1,4 +1,5 @@
from .logic_adapter import LogicAdapter
from collections import Counter


class MultiLogicAdapter(LogicAdapter):
Expand All @@ -21,12 +22,14 @@ def process(self, statement):
:param statement: The input statement to be processed.
"""
results = []
result = None
max_confidence = -1

for adapter in self.adapters:
if adapter.can_process(statement):
confidence, output = adapter.process(statement)
results.append((confidence, output, ))

self.logger.info(
u'{} selected "{}" as a response with a confidence of {}'.format(
Expand All @@ -44,8 +47,33 @@ def process(self, statement):
)
)

# If multiple adapters agree on the same statement,
# then that statement is more likely to be the correct response
if len(results) >= 3:
statements = [s[1] for s in results]
count = Counter(statements)
most_common = count.most_common()
if most_common[0][1] > 1:
result = most_common[0][0]
max_confidence = self.get_greatest_confidence(result, results)

return max_confidence, result

def get_greatest_confidence(self, statement, options):
"""
Returns the greatest confidence value for a statement that occurs
multiple times in the set of options.
:param statement: A statement object.
:param options: A tuple in the format of (confidence, statement).
"""
values = []
for option in options:
if option[1] == statement:
values.append(option[0])

return max(values)

def add_adapter(self, adapter):
"""
Appends a logic adapter to the list of logic adapters being used.
Expand Down
21 changes: 21 additions & 0 deletions tests/logic_adapter_tests/test_multi_adapter.py
@@ -0,0 +1,21 @@
from tests.base_case import ChatBotTestCase
from chatterbot.adapters.logic import MultiLogicAdapter


class MultiLogicAdapterTestCase(ChatBotTestCase):

def setUp(self):
super(MultiLogicAdapterTestCase, self).setUp()
self.adapter = MultiLogicAdapter()
self.adapter.set_context(self.chatbot)

def test_get_greatest_confidence(self):
statement = 'Hello'
options = [
(0.50, 'Hello'),
(0.85, 'Hello'),
(0.42, 'Hello')
]
value = self.adapter.get_greatest_confidence(statement, options)

self.assertEqual(value, 0.85)

0 comments on commit 245b949

Please sign in to comment.