def process_input(self, statement): new_message = False input_statement = self.context.get_last_input_statement() response_statement = self.context.get_last_response_statement() if input_statement: last_message_id = input_statement.extra_data.get("hipchat_message_id", None) if last_message_id: self.recent_message_ids.add(last_message_id) if response_statement: last_message_id = response_statement.extra_data.get("hipchat_message_id", None) if last_message_id: self.recent_message_ids.add(last_message_id) while not new_message: data = self.get_most_recent_message(self.hipchat_room) if data and data["id"] not in self.recent_message_ids: self.recent_message_ids.add(data["id"]) new_message = True else: pass sleep(3.5) text = data["message"] statement = Statement(text) statement.add_extra_data("hipchat_message_id", data["id"]) return statement
def get_statement(self): from chatterbot.conversation import Statement as StatementObject statement = StatementObject(self.text, extra_data=self.extra_data) for response in self.in_response_to: statement.add_response(response.get_response()) return statement
def handle_matches(self, match): """ Returns a response statement from a matched input statement. :param match: It is a valid matched pattern from the input statement :type: `_sre.SRE_Match` """ response = Statement(text='') try: from_parsed = match.group("from") target_parsed = match.group("target") n_statement = match.group("number") if n_statement == 'a' or n_statement == 'an': n_statement = '1.0' n = mathparse.parse(n_statement, self.language) ureg = UnitRegistry() from_parsed, target_parsed = self.get_valid_units(ureg, from_parsed, target_parsed) if from_parsed is None or target_parsed is None: raise from_value = ureg.Quantity(float(n), from_parsed) target_value = from_value.to(target_parsed) response.confidence = 1.0 response.text = str(target_value.magnitude) except Exception: response.confidence = 0.0 finally: return response
def process(self, statement): """ Takes a statement string. Returns the simplified statement string with the mathematical terms "solved". """ 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}) ) response = Statement(expression) response.confidence = 1 # return a confidence of 1 if the expression could be evaluated return 1, response except: response = Statement(expression) response.confidence = 0 return 0, response
def read_file(files, queue, preprocessors, stemmer): statements_from_file = [] for tsv_file in files: with open(tsv_file, 'r', encoding='utf-8') as tsv: reader = csv.reader(tsv, delimiter='\t') previous_statement_text = None previous_statement_search_text = '' for row in reader: if len(row) > 0: statement = Statement( text=row[3], in_response_to=previous_statement_text, conversation='training', created_at=date_parser.parse(row[0]), persona=row[1] ) for preprocessor in preprocessors: statement = preprocessor(statement) statement.search_text = stemmer.get_bigram_pair_string(statement.text) statement.search_in_response_to = previous_statement_search_text previous_statement_text = statement.text previous_statement_search_text = statement.search_text statements_from_file.append(statement) queue.put(tuple(statements_from_file))
def get_statements(self): """ Returns list of random statements from the API. """ from twitter import TwitterError statements = [] # Generate a random word random_word = self.random_word(self.random_seed_word, self.lang) self.chatbot.logger.info('Requesting 50 random tweets containing the word {}'.format(random_word)) tweets = self.api.GetSearch(term=random_word, count=50, lang=self.lang) for tweet in tweets: statement = Statement(text=tweet.text) if tweet.in_reply_to_status_id: try: status = self.api.GetStatus(tweet.in_reply_to_status_id) statement.in_response_to = status.text statements.append(statement) except TwitterError as error: self.chatbot.logger.warning(str(error)) self.chatbot.logger.info('Adding {} tweets with responses'.format(len(statements))) return statements
def process(self, statement): """ Takes a statement string. Returns the simplified statement string with the mathematical terms solved. """ 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))) response = Statement(text=expression) try: response.text += '= ' + str( eval(expression, {f: self.functions[f] for f in self.functions}) ) # Replace '**' with '^' for evaluated exponents response.text = response.text.replace('**', '^') # The confidence is 1 if the expression could be evaluated response.confidence = 1 except: response.confidence = 0 return response
def process(self, statement): """ Takes a statement string. Returns the equation from the statement with the mathematical terms solved. """ from mathparse import mathparse 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 = mathparse.extract_expression(input_text, language=self.language) response = Statement(text=expression) try: response.text += ' = ' + str( mathparse.parse(expression, language=self.language) ) # The confidence is 1 if the expression could be evaluated response.confidence = 1 except mathparse.PostfixTokenEvaluationException: response.confidence = 0 return response
def process(self, statement, additional_response_selection_parameters=None): now = datetime.now() time_features = self.time_question_features(statement.text.lower()) confidence = self.classifier.classify(time_features) response = Statement(text='The current time is ' + now.strftime('%I:%M %p')) response.confidence = confidence return response
def search(self, input_statement, **additional_parameters): """ Search for close matches to the input. Confidence scores for subsequent results will order of increasing value. :param input_statement: A statement. :type input_statement: chatterbot.conversation.Statement :param **additional_parameters: Additional parameters to be passed to the ``filter`` method of the storage adapter when searching. :rtype: Generator yielding one closest matching statement at a time. """ self.chatbot.logger.info('Beginning search for close text match') input_search_text = input_statement.search_text if not input_statement.search_text: self.chatbot.logger.warn( 'No value for search_text was available on the provided input' ) input_search_text = self.chatbot.storage.tagger.get_bigram_pair_string( input_statement.text ) search_parameters = { 'search_text_contains': input_search_text, 'persona_not_startswith': 'bot:', 'page_size': self.search_page_size } if additional_parameters: search_parameters.update(additional_parameters) statement_list = self.chatbot.storage.filter(**search_parameters) closest_match = Statement(text='') closest_match.confidence = 0 self.chatbot.logger.info('Processing search results') # Find the closest matching known statement for statement in statement_list: confidence = self.compare_statements(input_statement, statement) if confidence > closest_match.confidence: statement.confidence = confidence closest_match = statement self.chatbot.logger.info('Similar text found: {} {}'.format( closest_match.text, confidence )) yield closest_match
class StatementIntegrationTestCase(TestCase): """ Test case to make sure that the Django Statement model and ChatterBot Statement object have a common interface. """ def setUp(self): super().setUp() from datetime import datetime from pytz import UTC now = datetime(2020, 2, 15, 3, 14, 10, 0, UTC) self.object = StatementObject(text='_', created_at=now) self.model = StatementModel(text='_', created_at=now) # Simulate both statements being saved self.model.save() self.object.id = self.model.id def test_text(self): self.assertTrue(hasattr(self.object, 'text')) self.assertTrue(hasattr(self.model, 'text')) def test_in_response_to(self): self.assertTrue(hasattr(self.object, 'in_response_to')) self.assertTrue(hasattr(self.model, 'in_response_to')) def test_conversation(self): self.assertTrue(hasattr(self.object, 'conversation')) self.assertTrue(hasattr(self.model, 'conversation')) def test_tags(self): self.assertTrue(hasattr(self.object, 'tags')) self.assertTrue(hasattr(self.model, 'tags')) def test__str__(self): self.assertTrue(hasattr(self.object, '__str__')) self.assertTrue(hasattr(self.model, '__str__')) self.assertEqual(str(self.object), str(self.model)) def test_add_tags(self): self.object.add_tags('a', 'b') self.model.add_tags('a', 'b') self.assertIn('a', self.object.get_tags()) self.assertIn('a', self.model.get_tags()) def test_serialize(self): object_data = self.object.serialize() model_data = self.model.serialize() self.assertEqual(object_data, model_data)
def process(self, statement): from chatterbot.conversation import Statement now = datetime.now() time_features = self.time_question_features(statement.text.lower()) confidence = self.classifier.classify(time_features) response = Statement(text='The current time is ' + now.strftime('%I:%M %p')) response.confidence = confidence return response
def test_getting_and_updating_statement(self): statement = Statement("Hi") self.adapter.update(statement) statement.add_response(Response("Hello")) statement.add_response(Response("Hello")) self.adapter.update(statement) response = self.adapter.find(statement.text) self.assertEqual(len(response.in_response_to), 1) self.assertEqual(response.in_response_to[0].occurrence, 2)
def test_update_does_not_modify_existing_statement(self): statement = Statement("New statement") self.adapter.update(statement) self.adapter.read_only = True statement.add_response(Response("New response")) self.adapter.update(statement) statement_found = self.adapter.find("New statement") self.assertEqual(statement_found.text, statement.text) self.assertEqual(len(statement_found.in_response_to), 0)
def test_update_does_not_modify_existing_statement(self): statement = Statement("New statement") self.adapter.update(statement) self.adapter.read_only = True statement.update_occurrence_count() self.adapter.update(statement) statement_found = self.adapter.find("New statement") self.assertEqual(statement_found.text, statement.text) self.assertEqual(statement.occurrence, 2) self.assertEqual(statement_found.occurrence, 1)
def model_to_object(self, statement_model): """ Convert a Django model object into a ChatterBot Statement object. """ statement = Statement(statement_model.text) for response_object in statement_model.in_response_to.all(): statement.add_response(Response( response_object.response.text, occurrence=response_object.occurrence )) return statement
def get_statement(self): from chatterbot.conversation import Statement as StatementObject from chatterbot.conversation import Response as ResponseObject statement = StatementObject( self.text, tags=[tag.name for tag in self.tags], extra_data=self.extra_data ) for response in self.in_response_to: statement.add_response( ResponseObject(text=response.text, occurrence=response.occurrence) ) return statement
def test_update_does_not_modify_existing_statement(self): statement = Statement(text="New statement") self.adapter.update(statement) self.adapter.read_only = True statement.in_response_to = "New statement" self.adapter.update(statement) results = self.adapter.filter(text="New statement") self.assertEqual(len(results), 1) self.assertEqual(results[0].text, statement.text) self.assertEqual(results[0].in_response_to, None)
def test_update_modifies_existing_statement(self): statement = Statement("New statement") self.adapter.update(statement) # Check the initial values found_statement = self.adapter.find(statement.text) self.assertEqual(len(statement.in_response_to), 0) # Update the statement value statement.add_response(Statement("A response")) self.adapter.update(statement) # Check that the values have changed found_statement = self.adapter.find(statement.text) self.assertEqual(len(found_statement.in_response_to), 1)
def test_update_modifies_existing_statement(self): statement = Statement("New statement") self.adapter.update(statement) # Check the initial values found_statement = self.adapter.find(statement.text) self.assertEqual(found_statement.occurrence, 1) # Update the statement value statement.update_occurrence_count() self.adapter.update(statement) # CHeck that the values have changed found_statement = self.adapter.find(statement.text) self.assertEqual(found_statement.occurrence, 2)
def train(self, *corpus_paths): from chatterbot.corpus import load_corpus, list_corpus_files data_file_paths = [] # Get the paths to each file the bot will be trained with for corpus_path in corpus_paths: data_file_paths.extend(list_corpus_files(corpus_path)) for corpus, categories, file_path in load_corpus(*data_file_paths): statements_to_create = [] # Train the chat bot with each statement and response pair for conversation_count, conversation in enumerate(corpus): if self.show_training_progress: utils.print_progress_bar( 'Training ' + str(os.path.basename(file_path)), conversation_count + 1, len(corpus) ) previous_statement_text = None previous_statement_search_text = '' for text in conversation: statement_search_text = self.stemmer.get_bigram_pair_string(text) statement = Statement( text=text, search_text=statement_search_text, in_response_to=previous_statement_text, search_in_response_to=previous_statement_search_text, conversation='training' ) statement.add_tags(*categories) statement = self.get_preprocessed_statement(statement) previous_statement_text = statement.text previous_statement_search_text = statement_search_text statements_to_create.append(statement) self.chatbot.storage.create_many(statements_to_create)
class UtilityTests(TestCase): def setUp(self): self.statement = Statement("A test statement.") def test_now_timestamp(self): """ Tests that the correct datetime is returned """ import datetime fmt = "%Y-%m-%d-%H-%M-%S" time = self.statement.now(fmt) now = datetime.datetime.now().strftime(fmt) self.assertEqual(time, now) def test_add_signature(self): # TODO self.assertTrue(True) def test_serializer(self): # TODO self.assertTrue(True)
def model_to_object(self, statement_model): """ Convert a Django model object into a ChatterBot Statement object. """ statement = Statement( statement_model.text, extra_data=json.loads(statement_model.extra_data, encoding='utf8') ) for response_object in statement_model.in_response_to.all(): statement.add_response(Response( response_object.response.text, occurrence=response_object.occurrence )) return statement
class StatementTests(TestCase): def setUp(self): self.statement = Statement(text="A test statement.") def test_string_equality(self): """ It should be possible to check if a statement is the same as the statement text that another statement lists as a response. """ self.assertEqual(self.statement, "A test statement.") def test_string_equality_unicode(self): """ Test that it is possible to check if a statement is in a list of other statements when the statements text is unicode. """ self.statement.text = "我很好太感谢" self.assertEqual(self.statement, "我很好太感谢") def test_serializer(self): data = self.statement.serialize() self.assertEqual(self.statement.text, data["text"])
def deserialize_responses(self, response_list): """ Takes the list of response items and returns the list converted to Response objects. """ proxy_statement = Statement('') for response in response_list: text = response['text'] del response['text'] proxy_statement.add_response( Response(text, **response) ) return proxy_statement.in_response_to
def deserialize_responses(self, response_list): """ Takes the list of response items and returns the list converted to Response objects. """ proxy_statement = Statement('') for response in response_list: data = response.copy() text = data['text'] del(data['text']) proxy_statement.add_response( Response(text, **data) ) return proxy_statement.in_response_to
class StatementTests(TestCase): def setUp(self): self.statement = Statement(text='A test statement.') def test_serializer(self): data = self.statement.serialize() self.assertEqual(self.statement.text, data['text'])
def setUp(self): super(ChatterBotResponseTestCase, self).setUp() response_list = [ Response('Hi') ] self.test_statement = Statement('Hello', in_response_to=response_list)
def setUp(self): super(ChatterBotResponseTests, self).setUp() response_list = [ Response("Hi") ] self.test_statement = Statement("Hello", in_response_to=response_list)
def test_update_modifies_existing_statement(self): statement = Statement(text="New statement") self.adapter.update(statement) # Check the initial values results = list(self.adapter.filter(text=statement.text)) self.assertEqual(len(results), 1) self.assertEqual(results[0].in_response_to, None) # Update the statement value statement.in_response_to = "New response" self.adapter.update(statement) # Check that the values have changed results = list(self.adapter.filter(text=statement.text)) self.assertEqual(len(results), 1) self.assertEqual(results[0].in_response_to, "New response")
def process(self, statement): response = Statement('Good night.') response.confidence = 0.7 return response
def setUp(self): super(ChatterBotResponseTestCase, self).setUp() self.test_statement = Statement('Hello', in_response_to='Hi')
def test_pi_constant(self): statement = Statement('What is pi plus one ?') response = self.adapter.process(statement) self.assertEqual(response.text, '3.141693 + ( 1 ) = 4.141693') self.assertEqual(response.confidence, 1)
def test_log_function(self): statement = Statement('What is log 100 ?') response = self.adapter.process(statement) self.assertEqual(response.text, 'log ( 100 ) = 2.0') self.assertEqual(response.confidence, 1)
def test_exponent_operator(self): statement = Statement('What is 2 ^ 10') response = self.adapter.process(statement) self.assertEqual(response.text, '( 2 ^ 10 ) = 1024') self.assertEqual(response.confidence, 1)
def test_negative_decimal_multiplication(self): statement = Statement('What is -100.5 * 20?') confidence, response = self.adapter.process(statement) self.assertEqual(response.text, '( -100.5 * 20 ) = -2010.0')
def test_negative_multiplication(self): statement = Statement('What is -105 * 5') confidence, response = self.adapter.process(statement) self.assertEqual(response.text, '( -105 * 5 ) = -525')
def test_can_process(self): statement = Statement('What is 10 + 10 + 10?') self.assertTrue(self.adapter.can_process(statement))
def test_get_random_returns_statement(self): statement = Statement("New statement") self.adapter.update(statement) random_statement = self.adapter.get_random() self.assertEqual(random_statement.text, statement.text)
def test_can_process_pattern_x_unit_to_y_unit(self): statement = Statement('0 Celsius to fahrenheit') self.assertTrue(self.adapter.can_process(statement))
def test_can_not_convert_inches_to_kilometer(self): statement = Statement('How many inches are in blue kilometer?') self.assertFalse(self.adapter.can_process(statement))
def test_constants(self): statement = Statement('What is pi plus e ?') confidence, response = self.adapter.process(statement) self.assertEqual(response.text, '3.141693 + 2.718281 = 5.859974')
def test_can_not_process(self): statement = Statement('What is love?') self.assertFalse(self.adapter.can_process(statement))
def test_math_functions(self): statement = Statement('What is log ( 5 + 6 ) * sqrt ( 12 ) ?') confidence, response = self.adapter.process(statement) self.assertEqual(response.text, 'log ( ( 5 + ( 6 ) * sqrt ( ( 12 ) ) ) ) = 3.24977779033')
def test_can_process(self): statement = Statement('How many inches are in two kilometers?') self.assertTrue(self.adapter.can_process(statement))
def test_can_not_process(self): statement = Statement('What is your favorite song?') self.assertFalse(self.adapter.can_process(statement))
def test_square_root_function(self): statement = Statement('What is the sqrt 144 ?') response = self.adapter.process(statement) self.assertEqual(response.text, 'sqrt ( 144 ) = 12.0') self.assertEqual(response.confidence, 1)
def test_addition_operator(self): statement = Statement('What is 100 + 54?') confidence, response = self.adapter.process(statement) self.assertEqual(response.text, '( 100 + 54 ) = 154')
def test_e_constant(self): statement = Statement('What is e plus one ?') response = self.adapter.process(statement) self.assertEqual(response.text, '2.718281 + ( 1 ) = 3.718281') self.assertEqual(response.confidence, 1)
def test_subtraction_operator(self): statement = Statement('What is 100 - 58?') confidence, response = self.adapter.process(statement) self.assertEqual(response.text, '( 100 - 58 ) = 42')
def train(self): import csv import glob # Download and extract the Ubuntu dialog corpus if needed corpus_download_path = self.download(self.data_download_url) # Extract if the directory does not already exist if not self.is_extracted(self.extracted_data_directory): self.extract(corpus_download_path) extracted_corpus_path = os.path.join(self.extracted_data_directory, '**', '**', '*.tsv') BATCH_SIZE = 1000 statements_to_create = [] batch_count = 0 statement_count = 0 for tsv_file in glob.iglob(extracted_corpus_path): with open(tsv_file, 'r', encoding='utf-8') as tsv: reader = csv.reader(tsv, delimiter='\t') previous_statement_text = None for row in reader: if len(row) > 0: text = row[3] statement = self.get_preprocessed_statement( Statement(text=text, in_response_to=previous_statement_text, conversation='training')) statement.add_tags('datetime:' + row[0]) statement.add_tags('speaker:' + row[1]) if row[2].strip(): statement.add_tags('addressing_speaker:', row[2]) previous_statement_text = statement.text statements_to_create.append({ 'text': statement.text, 'in_response_to': statement.in_response_to, 'conversation': statement.conversation, 'tags': statement.tags }) statement_count += 1 if statement_count >= BATCH_SIZE: batch_count += 1 print( 'Training with batch {} containing {} statements.'.format( batch_count, statement_count)) self.chatbot.storage.create_many(statements_to_create) statements_to_create = [] statement_count = 0 # Insert the remaining statements self.chatbot.storage.create_many(statements_to_create)
def test_multiplication_operator(self): statement = Statement('What is 100 * 20') confidence, response = self.adapter.process(statement) self.assertEqual(response.text, '( 100 * 20 ) = 2000')
def test_no_choices(self): possible_choices = [] statement = Statement("Hello") with self.assertRaises(EmptyDatasetException): self.adapter.get(statement, possible_choices)
def test_parenthesized_multiplication_and_addition(self): statement = Statement('What is 100 + ( 1000 * 2 )?') confidence, response = self.adapter.process(statement) self.assertEqual(response.text, '( 100 + ( ( 1000 * ( 2 ) ) ) ) = 2100')
class ChatterBotResponseTestCase(ChatBotTestCase): def setUp(self): super(ChatterBotResponseTestCase, self).setUp() self.test_statement = Statement('Hello', in_response_to='Hi') def test_empty_database(self): """ If there is no statements in the database, then the user's input is the only thing that can be returned. """ response = self.chatbot.get_response('How are you?') self.assertEqual('How are you?', response) def test_statement_saved_empty_database(self): """ Test that when database is empty, the first statement is saved and returned as a response. """ statement_text = 'Wow!' response = self.chatbot.get_response(statement_text) results = self.chatbot.storage.filter(text=statement_text) self.assertIsLength(results, 1) self.assertEqual(response, statement_text) def test_statement_added_to_conversation(self): """ An input statement should be added to the recent response list. """ statement = Statement(text='Wow!', conversation='test') response = self.chatbot.get_response(statement) self.assertEqual(statement.text, response) self.assertEqual(response.conversation, 'test') def test_response_known(self): self.chatbot.storage.update(self.test_statement) response = self.chatbot.get_response('Hi') self.assertEqual(response, self.test_statement.text) def test_response_format(self): self.chatbot.storage.update(self.test_statement) response = self.chatbot.get_response('Hi') results = self.chatbot.storage.filter(text=response.text) self.assertEqual(response, self.test_statement.text) self.assertIsLength(results, 1) self.assertEqual(results[0].in_response_to, 'Hi') def test_second_response_format(self): self.chatbot.storage.update(self.test_statement) response = self.chatbot.get_response('Hi') self.assertEqual(response.text, 'Hello') second_response = self.chatbot.get_response('How are you?') results = self.chatbot.storage.filter(text=second_response.text) # Make sure that the second response was saved to the database self.assertIsLength(self.chatbot.storage.filter(text='How are you?'), 1) self.assertEqual(second_response, self.test_statement.text) self.assertIsLength(results, 1) self.assertEqual(results[0].in_response_to, 'Hi') def test_get_response_unicode(self): """ Test the case that a unicode string is passed in. """ response = self.chatbot.get_response(u'سلام') self.assertGreater(len(response.text), 0) def test_get_response_emoji(self): """ Test the case that the input string contains an emoji. """ response = self.chatbot.get_response(u'💩 ') self.assertGreater(len(response.text), 0) def test_get_response_non_whitespace(self): """ Test the case that a non-whitespace C1 control string is passed in. """ response = self.chatbot.get_response(u'') self.assertGreater(len(response.text), 0) def test_get_response_two_byte_characters(self): """ Test the case that a string containing two-byte characters is passed in. """ response = self.chatbot.get_response(u'田中さんにあげて下さい') self.assertGreater(len(response.text), 0) def test_get_response_corrupted_text(self): """ Test the case that a string contains "corrupted" text. """ response = self.chatbot.get_response( u'Ṱ̺̺̕h̼͓̲̦̳̘̲e͇̣̰̦̬͎ ̢̼̻̱̘h͚͎͙̜̣̲ͅi̦̲̣̰̤v̻͍e̺̭̳̪̰-m̢iͅn̖̺̞̲̯̰d̵̼̟͙̩̼̘̳.̨̹͈̣' ) self.assertGreater(len(response.text), 0) def test_response_with_tags_added(self): """ If an input statement has tags added to it, that data should saved with the input statement. """ self.test_statement.add_tags('test') self.chatbot.get_response(self.test_statement) results = self.chatbot.storage.filter(text=self.test_statement.text) self.assertIsLength(results, 1) self.assertIn('test', results[0].get_tags()) def test_generate_response(self): statement = Statement( 'Many insects adopt a tripedal gait for rapid yet stable walking.') response = self.chatbot.generate_response(statement) self.assertEqual(response, statement) self.assertEqual(response.confidence, 1) def test_learn_response(self): previous_response = Statement('Define Hemoglobin.') statement = Statement( 'Hemoglobin is an oxygen-transport metalloprotein.') self.chatbot.learn_response(statement, previous_response) results = self.chatbot.storage.filter(text=statement.text) self.assertIsLength(results, 1) def test_get_response_does_not_add_new_statement(self): """ Test that a new statement is not learned if `read_only` is set to True. """ self.chatbot.read_only = True self.chatbot.get_response('Hi!') results = self.chatbot.storage.filter(text='Hi!') self.assertIsLength(results, 0) def test_get_latest_response_from_zero_responses(self): response = self.chatbot.get_latest_response('invalid') self.assertIsNone(response) def test_get_latest_response_from_one_responses(self): self.chatbot.storage.create(text='A', conversation='test') self.chatbot.storage.create(text='B', conversation='test', in_response_to='A') response = self.chatbot.get_latest_response('test') self.assertEqual(response.text, 'A') def test_get_latest_response_from_two_responses(self): self.chatbot.storage.create(text='A', conversation='test') self.chatbot.storage.create(text='B', conversation='test', in_response_to='A') self.chatbot.storage.create(text='C', conversation='test', in_response_to='B') response = self.chatbot.get_latest_response('test') self.assertEqual(response.text, 'B') def test_get_latest_response_from_three_responses(self): self.chatbot.storage.create(text='A', conversation='test') self.chatbot.storage.create(text='B', conversation='test', in_response_to='A') self.chatbot.storage.create(text='C', conversation='test', in_response_to='B') self.chatbot.storage.create(text='D', conversation='test', in_response_to='C') response = self.chatbot.get_latest_response('test') self.assertEqual(response.text, 'C')
def test_parenthesized_with_words(self): statement = Statement('What is four plus 100 + ( 100 * 2 )?') confidence, response = self.adapter.process(statement) self.assertEqual(response.text, '( 4 + ( 100 + ( ( 100 * ( 2 ) ) ) ) ) = 304')
def process(self, statement): response = Statement('Good morning.') response.confidence = 0.5 return response
def test_word_numbers_addition(self): statement = Statement('What is one hundred + four hundred?') confidence, response = self.adapter.process(statement) self.assertEqual(response.text, '( 100 + 400 ) = 500')
if 'yes' in text.lower(): return True elif 'no' in text.lower(): return False else: print('Please type either "Yes" or "No"') return get_feedback() print('Type something to begin...') # The following loop will execute each time the user enters input while True: try: input_statement = Statement(text=input()) response = bot.generate_response( input_statement ) print('\n Is "{}" a coherent response to "{}"? \n'.format( response.text, input_statement.text )) if get_feedback(): print('please input the correct one') correct_response = Statement(text=input()) bot.learn_response(correct_response, input_statement) print('Responses added to bot!') # Press ctrl-c or ctrl-d on the keyboard to exit
def test_can_process_x_unit_is_how_many_y_unit(self): statement = Statement('2 TB is how many GB?') self.assertTrue(self.adapter.can_process(statement))