Skip to content

Commit

Permalink
Cache results from can_process method in math adapter (gunthercox#461)
Browse files Browse the repository at this point in the history
This makes changes so that if a value is processed
by the 'can_process' method of the math adapter, the
result can be reused when the 'process' method is called.

This reduces redundant operations and increases the efficiency
of this method.
  • Loading branch information
gunthercox authored and vkosuri committed Dec 10, 2016
1 parent f78828f commit b60f7d6
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions chatterbot/logic/mathematical_evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ def __init__(self, **kwargs):

language = kwargs.get('math_words_language', 'english')
self.math_words = self.get_language_data(language)
self.cache = {}

def get_language_data(self, language):
"""
Expand Down Expand Up @@ -59,6 +60,7 @@ def can_process(self, statement):
adapter to respond to the user input.
"""
confidence, response = self.process(statement)
self.cache[statement.text] = (confidence, response)
return confidence == 1

def process(self, statement):
Expand All @@ -69,12 +71,20 @@ def process(self, statement):
"""
input_text = statement.text

# Use the result cached by the process method if it exists
if input_text in self.cache:
cached_result = self.cache[input_text]
self.cache = {}
return cached_result

# Getting the mathematical terms within the input statement
expression = str(self.simplify_chunks(self.normalize(input_text)))

# Returning important information
try:
expression += "= " + str(eval(expression, {f: getattr(numpy, f) for f in self.functions}))
expression += "= " + str(
eval(expression, {f: getattr(numpy, f) for f in self.functions})
)

# return a confidence of 1 if the expression could be evaluated
return 1, Statement(expression)
Expand Down Expand Up @@ -231,9 +241,7 @@ def substitute_words(self, string):
return ' '.join(condensed_string)

class UnrecognizedLanguageException(Exception):

def __init__(self, value='The specified language was not recognized'):
self.value = value

def __str__(self):
return repr(self.value)
"""
Exception raised when the specified language is not known.
"""
pass

0 comments on commit b60f7d6

Please sign in to comment.