def process(self, statement, additional_response_selection_parameters=None): """ Returns the forecast for a location (using latitude and longitude). """ import requests url = "http://api.openweathermap.org/data/2.5/weather?q=Ningbo,china&APPID=885aa9eb815b6b6b1b24ce7ade4b78d9" res = requests.get(url) data = res.json() if res.status_code == 404: response = Statement(text='Network Error!') response.confidence = 0 return response else: condition = data["main"] temp = condition["temp"] humidity = condition["humidity"] pressure = condition["pressure"] info = data["weather"] des = info[0] descrip = des["description"] response = Statement( text="The current weather in Ningbo: " + str(descrip) + ", Temperature: " + str(int(temp - 272.15)) + "℃, Humidity: " + str(humidity) + "%, Pressure: " + str(pressure / 1000) + "kpa") response.confidence = 2 return response
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, _): dia = self.obter_dia(statement.text) cliente = MongoClient("mongodb://localhost:27017") db = cliente['chatterbot-database'] aulasInfo = db.aulasInfo result = list(aulasInfo.find({'Dia': dia})) if len(result) == 0: resp = Statement( text='{} não tem aulas, mas aproveite para estudar!'.format( obter_dia_da_semana(dia))) resp.confidence = 1 return resp mensagem = '{} é dia de '.format(obter_dia_da_semana(dia)) for d in result: mensagem = '{} {} às {} para o ciclo {} com {} <br>'.format( mensagem, d['Disciplina'], d['Horario'], d['Ciclo'], d['Professor']) mensagem.replace(',', '.', len(mensagem) - 1) msg = Statement(text=mensagem) msg.confidence = 1 return msg
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 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 perform_query(app_id, query): """Performs the given query and return a statement that's compatible with chatterbot. """ params = { "appid": app_id, "input": query, "output": "json", "includepodid": ["Input", "Result"], "format": "plaintext", } resp = requests.get(query_url, params=params) data = resp.json().get("queryresult", {}) logger.debug("Response body {}".format(data)) statement = Statement("") statement.confidence = 0 if not data.get("success") or int(data.get("numpods")) < 2: return statement pods = data.get("pods", []) input_pod = next(pod for pod in pods if pod["id"] == "Input") result_pod = next(pod for pod in pods if pod["id"] == "Result") parsed_input = input_pod["subpods"][0]["plaintext"] result = result_pod["subpods"][0]["plaintext"] statement.text = f'I understood that as "{parsed_input}" and this is what I know about that: {result}' statement.confidence = 1 return statement
def process(self, statement, additional_response_selection_parameters=None): result = Statement("I have no idea.") result.confidence = 0.9 if statement.text not in self.cache: # this should never happen? return result query = self.cache[statement.text] self.cache = {} text, confidence = None, 0 if query.type == 'is a': text, confidence = solve_isa(*query.match.groups()), 1.0 elif query.type == 'what is': text, confidence = solve_what_is(*query.match.groups()), 1.0 elif query.type == 'examples': text, confidence = solve_examples(*query.match.groups()), 1.0 if text: result = Statement(text) result.confidence = confidence return result
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 process(self, input_statement, additional_response_selection_parameters): """ :param input_statement: input from user :param additional_response_selection_parameters Function to handle returning information message to the user """ from chatterbot.conversation import Statement if input_statement.text == 'display examples': response_statement = Statement(text='1. Maths, What is four plus four? ' '2. Lunch Application, open chrome or open twitter ' '3. Weather, what temperature is it in Galway ' '4. Time, what time is it ' '5. Note, "make a note" followed by what you wish to add "I have a ' 'meeting Tuesday" is very nice today" and to retrieve the note say ' '"read me my note"') confidence = 1 response_statement.confidence = confidence return response_statement else: response_statement = Statement( text='Hey! My name is Nuton! I can give you the weather for any location,' 'I can open applications for you, along with more help! If you like some examples say "display ' 'examples"') confidence = 1 response_statement.confidence = confidence return response_statement
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): """ 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): """ 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 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='') 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.ISO_639.upper()) from_parsed, target_parsed = self.get_valid_units(from_parsed, target_parsed) if from_parsed is None or target_parsed is None: response.confidence = 0.0 else: from_value = self.unit_registry.Quantity(float(n), from_parsed) target_value = from_value.to(target_parsed) response.confidence = 1.0 response.text = str(target_value.magnitude) return response
def call_function(statement): function = statement.text.split()[1] response = functions[function]() if response != None: response_statement = Statement(text=response) response_statement.confidence = 1 else: response_statement = Statement(text="Desculpe") response_statement.confidence = 0 return response_statement
def process(self, statement, additional_response_selection_parameters=None): """ Given an affirmative/negative statement from the user: 1. Detect which question from the bot the user in answering. 2. Return appropriate response to the user. """ # I found the following three lines to be necessary after quite a bit of debugging. # get_last() returns a Statement object with all fields empty except for text and created_at. # When chatbot.storage.filter() is used it returns a generator object, not a Statement object. # Using next() on the generator object gets us the desired Statement object with all needed data. incomplete_direct_question = self.chatbot.get_last() generator_direct_question = self.chatbot.storage.filter(text=incomplete_direct_question.text) direct_question = None try: direct_question = next(generator_direct_question) except StopIteration: pass response_tag = '' response_text = '' generator_response = None if direct_question: if statement.text.strip('.?!/;:\'\"') in constants.AFFIRMATIVES: response_tag = self.get_affirmative_tag(direct_question) elif statement.text.strip('.?!/;:\'\"') in constants.NEGATIVES: response_tag = self.get_negative_tag(direct_question) if response_tag: generator_response = self.chatbot.storage.filter(text=response_tag) try: answer = next(generator_response) answer.confidence = 1 return answer except StopIteration: ''' There were occasional instances during testing where storage.filter() would return a generator object with no items in it, causing a StopIteration error. This happened despite there being a statement in the database with a matching text field. The issue was hard to reproduce. This is a workaround. ''' desired_stmnt = Statement(text=response_tag) desired_stmnt.confidence = 1 return desired_stmnt # Many direct questions are only tagged for AFF or NEG response, not both. # This logic adapter should still choose responses for those cases, since BestMatch will always be guessing. # SUGGEST response causes the chatbot to query the suggestion tree and bring up undiscussed topics. default_response = Statement(text='SUGGEST') default_response.confidence = 1 return default_response
def process(self, input_statement, additional_response_selection_parameters): data = dt.get_environment_data() # Let's base the confidence value on if the request was successful if isinstance(data, str): response_statement = Statement(text='O pico mais alto de thread é {}'.format(data)) response_statement.confidence = 1 else: response_statement = Statement(text='Ocorreu erro ao validar o ambiente.') response_statement.confidence = 0 return response_statement
def process(self, statement, additional_response_selection_parameters=None): filtered_words = self.sentence_filter.filter_sentence_complex( statement.text) if len(filtered_words) == 0: return default_response() db_search_words = list(filtered_words) if contains_synonym(db_search_words): db_search_words.extend(UNIV_SYNONYMS) db_search_words = list(set(db_search_words)) documents_by_tags = self.db.get_docs_from_collection_by_tags_list( self.collection_name, db_search_words) if len(documents_by_tags) == 0: return default_response() result_text, max_conf = choice_algorithm.find_best_tags_response( documents_by_tags, filtered_words) res = Statement(result_text) res.confidence = config.MAX_CONF.value # 1.0 self.db.add_new_doc_to_collection(config.RESPONSES_COLLECTION.value, confidence=res.confidence, response=res.text) return res
def process(self, statement): # process handles general read in logic from chatterbot.conversation import Statement confidence = 1 bot_response = self.Check( ) # default response is game status, as a check() call statement = [x.lower() for x in statement.text.split()] statement = [re.sub(r'\W+', '', x) for x in statement] if "horse" in statement: if "play" in statement: # if user is attempting to start a game r = (random.randrange(2, 13)) # generate a number self.Init(r) # start game with that length word bot_response = "I'm thinking of a word that's " + str( r) + " letters long.\n" bot_response += self.Check( ) # add the game state to the string confidence = 1 elif "guess" in statement: # if user is guessing s = statement # print(s[3]) self.Guess( s[3] ) # guess the letter at index 3, which is the letter/string after guess bot_response = self.Check() # update response with check() # print(str(bot_response)) # debug prints of what bot will say response_statement = Statement( str(bot_response)) # set response to the bot_response response_statement.confidence = 1 # print(str(response_statement)) return response_statement # return this statement out.
def process(self, statement, additional_response_selection_parameters): from chatterbot.conversation import Statement confidence = 0 txt = statement.text if self.hasConfirmation(txt): confidence = 1 response = 'Your address has been changed. Your request number is: ' + self.createincident( ) + self.attachIdleText() else: searchObj = self.getAddressRegex(txt) address = None if searchObj: address = searchObj.group() if ("current address" in txt): confidence = 0.7 response = "I've got your information. What's the new address? " else: confidence = 0.7 response = "Do you confirm your address change to:" + address selected_statement = Statement(text=response) selected_statement.confidence = confidence return selected_statement
def process(self, statement, additional_response_selection_parameters): from chatterbot.conversation import Statement txt = '' if (self.hasOnlyPhoneNumber(statement.text)): confidence = 1 # TODO modify for only phone number stuff txt = "I've opened ticket INC20180402 for you. The time frame for assigning this ticket is 30 min. You should receive a call after that. You also can come back and ask me the status of your ticket if you want providing the ticket number." else: incidentNo = self.getIncident(statement.text) if incidentNo: confidence = 1 incidentStatus = IncidentAdapter.incidentService.getIncidentStatus( incidentNo) if incidentStatus: txt = 'This is the status of your ticket:' + incidentStatus.tostring( ) + self.attachIdleText() else: txt = "Sorry, I can't find this number, please try again on call support 800-555-555" else: confidence = 0 selected_statement = Statement(text=txt) selected_statement.confidence = confidence return selected_statement
def process(self, statement): words = [ 'bitcoin', 'ethereum', 'ripple', 'bitcoin-cash', 'eos', 'cardano', 'litecoin', 'stellar', 'neo', 'tron', 'iota', 'monero', 'dash', 'nem', 'vechain', 'tether', 'ethereum-classic', 'qtum', 'omisego', 'icon', 'binance-coin', 'bitcoin-gold', 'lisk', 'aeternity', 'zcash' ] currency = '' for x in words: if x in statement.text.lower().split(): currency = x break url = "https://api.coinmarketcap.com/v1/ticker/" # Make a request to the coinmarketcap API response = requests.get(url + currency + "/") data = Statement('The current price of ' + currency + ' is $' + response.json()[0]['price_usd']) # Let's base the confidence value on if the request was successful if response.status_code == 200: confidence = 1 else: confidence = 0 data.confidence = confidence return data
def process(self, statement, _): from chatterbot.conversation import Statement import requests cliente = MongoClient("mongodb://localhost:27017") db = cliente['chatterbot-database'] aulasInfo = db.aulasInfo result = aulasInfo.find({}) professores = list( filter(lambda f: f['Professor'].lower() in statement.text.lower(), result)) if len(professores) == 0: return Statement(text='') mensagem = '' for professor in professores: dia = obter_dia_da_semana(professor['Dia']) mensagem += 'O(a) professor(a) {} leciona {} na {} às {} na sala {} <br>'.format( professor['Professor'], professor['Disciplina'], dia, professor['Horario'], professor['Sala']) response_statement = Statement(text=mensagem) response_statement.confidence = 1 return response_statement
def process(self, input_statement, additional_response_selection_parameters): from chatterbot.conversation import Statement #import requests #import randoms # Make a request to the temperature API #response = requests.get('https://api.temperature.com/current?units=celsius') #data = response.json() # Let's base the confidence value on if the request was successful import pandas as pd import numpy as np data = pd.read_csv( 'F:/Chatbot/Chatterbot/Project_v3/Bank_Transactions.csv') print(data) balance = data[(data['DATE'] == max(data['DATE'])) & ( data['Account Type'] == 'Savings')]['BALANCE AMT'].iloc[0] print(balance) if balance > 0: confidence = 1 else: confidence = 0 print('confidence', confidence) response_statement = Statement( text='The current balance in your Savings account is INR {}'. format(balance)) #response_statement = Statement(text='The current balance in your Savings account is 1000.') print('response_statement = ', response_statement) #response_statement = input_statement response_statement.confidence = confidence return response_statement
def process(self, statement): from chatterbot.conversation import Statement import requests, json #api metro bus """ :var url: api de metro bus :self.num.group(): aqui hago referecia al numero obtenido de la busqueda que se hizo mas arriba por medio de self.num = patron.search(statement.text). :var response: se hace el llamado de la api para obtener los valores. """ url = 'http://panamenio.herokuapp.com/api/com/metrobus/' + self.num.group( ) response = requests.get(url) response.text # Let's base the confidence value on if the request was successful """ if response.status_code == 200: valida que la coneccion con la api fue exitosa, si cumple la condicion la confianza para a 1 para que el bot lo agrege a la base de datos y pueda se impreso. """ if response.status_code == 200: confidence = 1 else: confidence = 0 data = json.loads(response.text) saldo = str(data['balance']) """ :response_statement = Statement('Tu saldo es {}'.format(saldo)): de esta manera es que el bot nos lo estuviera mostrando en pantalla. """ response_statement = Statement('Tu saldo es {}'.format(saldo)) response_statement.confidence = confidence return response_statement
def process(self, input_statement, additional_response_selection_parameters): from chatterbot.conversation import Statement confidence = 1 ISSUES = [ 'Slow computer', 'Virus check', 'Software bug', 'Resetting my password', 'Update', 'New software', 'Bluescreen', 'Connecting to bluetooth', 'I\'ve been hacked', 'Broken mouse', 'Broken keyboard', 'Delete files', 'Find a printer', 'Storage', 'Unexpected restart', 'Wi-Fi is slow', 'Spilt coffee', 'Share drive', 'Blocked website', 'CD burner', 'CD reader', 'Tell me a funny joke'] selected_statement = Statement(text='Here are some items I can help with: {}\n'.format(str(ISSUES).strip('[]'))) selected_statement.confidence = confidence return selected_statement
def process(self, statement): from chatterbot.conversation import Statement '''# Make a request to the temperature API''' full_statement = str(statement) top = self.getTop(full_statement) result = '' if top[1] > certainty: data = self.getData() temperature = self.getTemperature(data) wind = self.getWindSpeed(data) wd = self.getWindDirection(data) feelslike = self.getFeelsLike(data) condition = self.getDesc(data).lower() if temperature and wind and wd: confidence = 1 result = 'It\'s currently ' + condition + ' and ' + str( temperature ) + ' degrees outside, but it feels like ' + str( feelslike) + ' degrees. \n The wind is currently ' + str( wind) + ' mph coming from the ' + directions[wd] + '.' else: confidence = 0 else: result = 'Hmm.. There seems to be a problem with my weather circuit! I\'ll phone the weather man.' response_statement = Statement(result) response_statement.confidence = confidence return response_statement
def process(self, statement, _): from chatterbot.conversation import Statement import requests cliente = MongoClient("mongodb://localhost:27017") db = cliente['chatterbot-database'] aulasInfo = db.aulasInfo result = aulasInfo.find({}) disciplinas = list( filter(lambda f: f['Disciplina'].lower() in statement.text.lower(), result)) if len(disciplinas) == 0: return Statement(text='') disciplina = sorted(disciplinas, key=sort_item, reverse=True)[0] dia = obter_dia_da_semana(disciplina['Dia']) mensagem = 'A disciplina {} ocorreu toda(o) {} às {} com o(a) professor(a) {} na sala {}. São {} aulas.'.format( disciplina['Disciplina'], dia, disciplina['Horario'], disciplina['Professor'], disciplina['Sala'], disciplina['Aulas']) response_statement = Statement(text=mensagem) response_statement.confidence = 1 return response_statement
def process(self, statement): from chatterbot.conversation import Statement now = datetime.now() web_features = self.web_question_features(statement.text.lower()) confidence = self.classifier.classify(web_features) response = Statement('classified as web ') response.confidence = confidence #print statement.text result = google_search.getGoogleResult(statement.text) res = Statement(result) res.confidence = confidence return res
def process(self, input_statement, additional_response_selection_parameters): from chatterbot.conversation import Statement import requests # Make a request to the temperature API response = requests.get( 'https://api.hgbrasil.com/weather?woeid=447216') data = response.json() # Let's base the confidence value on if the request was successful if response.status_code == 200: confidence = 1 else: confidence = 0 temperature = data.get('results', 'indisponivel') temperature = temperature['temp'] response_statement = Statement( text='A temperatura atual é de {} graus celsius'.format( temperature)) response_statement.confidence = confidence return response_statement
def process(self, statement, _): mensagem = 'Tenho aqui alguns arquivos que podem ser uteis pra você. Dê uma olhada nos arquivos da Fatec aqui no meu repositório do <a href="https://drive.google.com/drive/folders/1n0GuGD-meSgFtyFqD6r3AH-7_LG4Q72u?usp=sharing">drive</a>' msg = Statement(text=mensagem) msg.confidence = 1 return msg
def process_name_request(self, statement): name_responses = self.db.get_responses_list_by_tags(tag="name_response") if len(name_responses) > 0: name_responses_splitted = list() for name_response in name_responses: tmp = name_response.split(',') if len(tmp) == 2: (request1, request2) = tmp name_responses_splitted.append((request1, request2)) my_name = self.db.get_first_response_by_tags(tag="my_name") (response_text1, response_text2) = name_responses_splitted[random.randint(0, len(name_responses) - 1)] response = [] if not self.robot_name_request: response_text_buff = self.db.get_random_response_by_tags(tag="no_introduction_message") response.append(response_text_buff) response.append(response_text1) response.append(my_name) if not self.robot_name_request: response.append(response_text2) result = Statement(statement_utils.prepare_statement( response), in_response_to=TypeOfOperation.NAME.value) result.confidence = 0.3 self.db.add_new_doc_to_collection(Configuration.RESPONSES_COLLECTION.value, confidence=result.confidence, response=result.text) return result return statement_utils.default_response()
def process(self, input_statement, additional_response_selection_parameters): import random from chatterbot.conversation import Statement """ Calculate confidence: This is probably not the correct way but is sufficient for now. """ input = input_statement.text.split() benefitsKewwords = [ 'benefit', 'benefits', 'medical', 'dental', 'vision', 'insurance', 'help', 'pay' ] wordsInList = 0 for word in benefitsKewwords: if (word in input): wordsInList += 1 confidence = 0 if (wordsInList == 0): confidence = confidence else: confidence = (wordsInList / len(benefitsKewwords)) """ Set statement: We need to find an algorithm to set the statement to an answer from a list of answers. As of now, this adapter only returns one answer if it can process the input statement """ selected_statement = Statement(text=answer) selected_statement.confidence = confidence return selected_statement
def process(self, input_statement, additional_response_selection_parameters): import random from chatterbot.conversation import Statement """ Calculate confidence: """ input = input_statement.text.split() travelKewwords = [ 'time off', 'sick time', 'vacation', 'travel', 'traveling' ] wordsInList = 0 for word in travelKewwords: if (word in input): wordsInList += 1 confidence = 0 if (wordsInList == 0): confidence = confidence else: confidence = (wordsInList / len(travelKewwords)) """ Set statement: We need to find an algorithm to set the statement to an answer from a list of answers. As of now, this adapter only returns one answer if it can process the input statement """ selected_statement = Statement(text=answer) selected_statement.confidence = confidence return selected_statement
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
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 process(self, statement): response = Statement(text='') input_text = statement.text try: # Use the result cached by the process method if it exists if input_text in self.cache: response = self.cache[input_text] self.cache = {} return response for pattern, func in self.patterns: p = pattern.match(input_text) if p is not None: response = func(p) if response.confidence == 1.0: break except Exception: response.confidence = 0.0 finally: return response
def process(self, statement): response = Statement('Good night.') response.confidence = 0.7 return response.confidence, response
def process(self, statement): response = Statement('Good morning.') response.confidence = 0.2 return response.confidence, response