if 'yes' in text.lower(): return False elif 'no' in text.lower(): return True 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 = bot.input.process_input_statement() statement, response = bot.generate_response(input_statement, CONVERSATION_ID) bot.output.process_response(response) print('\n Is "{}" a coherent response to "{}"? \n'.format(response, input_statement)) if get_feedback(): print("please input the correct one") response1 = bot.input.process_input_statement() bot.learn_response(response1, input_statement) bot.storage.add_to_conversation(CONVERSATION_ID, statement, response1) print("Responses added to bot!") # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
table = str.maketrans('', '', string.punctuation) stripped = [w.translate(table) for w in words] for w in stripped: if w == "": stripped.remove(w) elif w == " ": stripped.remove(w) filtered_sen_pun = ' '.join(stripped) print('Punc :', filtered_sen_pun) # Lowering the case #filtered_sent=filtered_sen_pun.lower() input_statement = Statement(filtered_sen_pun) print('-' * 100) print('input_statement ==>', input_statement) response = bot.generate_response(input_statement) print('=' * 100) print("Chatbot :", response.text) 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 except (KeyboardInterrupt, EOFError, SystemExit): break
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 = bot.input.process_input() statement, response = bot.generate_response( input_statement, CONVERSATION ) print('\n Is "{}" this a coherent response to "{}"? \n'.format(response, input_statement)) if get_feedback(): bot.learn_response(CONVERSATION, response, input_statement) bot.output.process_response(response) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
class NLG_unit(object): """ This object contains tools to answer in natural language any message non-Fib related Attributes: chatterbot_bot(:class:`chatterbot.ChatBot`): chatterbot bot to process the non-fib-Related questions train_queue(:obj:`dict`): dictionary that act as a queue of training concepts conversation_id(:obj:`int` or None): Identifier that keeps track of the diferent amounts of conversations learnt """ def __init__(self): self.chatterbot_bot = ChatBot( "Fibot", storage_adapter="chatterbot.storage.SQLStorageAdapter", ) self.train_queue = {} self.conversation_id = None """ This function load the learnt model for chatterbot """ def load(self): self.conversation_id = self.chatterbot_bot.storage.create_conversation() """ Parameters: chat_id (:obj:`str`): chat_id of the person to get feedback from correct (:obj:`bool`): tells whether the prediction was correct_statement correct_statement (:obj:`str` or None): Correction if there is This function enables the chatterbot bot to learn if he predicted good and allows him to learn new responses. """ def give_feedback(self, chat_id, correct = True, correct_statement = None): if not correct: message = self.train_queue[chat_id]['message'] correct_statement = Statement(correct_statement) self.chatterbot_bot.learn_response(correct_statement, message) self.chatterbot_bot.storage.add_to_conversation(self.conversation_id, message, correct_statement) self.send_message(chat_id, "Aprendido!. Mándame más si quieres, o desactívame usando /train_off") else: self.send_message(chat_id, "Bien. Mándame más si quieres, o desactívame usando /train_off") """ Parameters: chat_id (:obj:`str`): chat_id of the person to process the answer for message (:obj:`str`): message the user introduced to be processed This function makes the bot predict the following message, and asks for checks. """ def process_answer_training(self, chat_id, message): print("Query de %s con mensaje %s"%(chat_id, message)) self.send_chat_action(chat_id) input_statement = Statement(message) statement, response = self.chatterbot_bot.generate_response(input_statement, self.conversation_id) self.send_message(chat_id,'Es "{}" una respuesta coherente a "{}"? (Sí/No)'.format(response, message)) self.train_queue[chat_id] = { 'message': input_statement, 'response': response } """ Parameters: message (:obj:`str`): message the user introduced to be processed debug (:obj:`bool`): indicates the level of verbosity This function returns the predicted responses for message """ def get_response(self, message, debug = False): input_statement = Statement(message) _, response = self.chatterbot_bot.generate_response(input_statement, self.conversation_id) if debug: return "%s, confidence = %d"%(response['text'], response['confidence']) else: return str(response) """ Parameters: chat_id (:obj:`str`): chat_id of the person to process the answer for message (:obj:`str`): content of the messages This function allows nlg class to send messages for the training duties """ def send_message(self, chat_id, message): params = { 'chat_id': chat_id, 'text': message } bot_token = os.getenv('FibotTOKEN') base_url = 'https://api.telegram.org/bot%s/sendMessage'%bot_token response = requests.get(base_url, params = params) """ Parameters: chat_id (:obj:`str`): chat_id of the person to process the answer for action (:obj:`str`): action to send of the messages This function allows nlg class to send chat_action for the training duties """ def send_chat_action(self, chat_id, action = ChatAction.TYPING): params = { 'chat_id': chat_id, 'action': action } bot_token = os.getenv('FibotTOKEN') base_url = 'https://api.telegram.org/bot%s/sendChatAction'%bot_token response = requests.get(base_url, params = params)
elif 'maybe' in text.lower(): print('ok') 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 = bot.input.process_input_statement() statement, response = bot.generate_response(input_statement, CONVERSATION_ID) bot.output.process_response(response) print('\n Is "{}" a coherent response to "{}"? \n'.format( response, input_statement)) if get_feedback(): print("please input the correct one") response1 = bot.input.process_input_statement() bot.learn_response(response1, input_statement) bot.storage.add_to_conversation(CONVERSATION_ID, statement, response1) print("Responses added to bot!") # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
elif 'No' in text: 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 = bot.input.process_input_statement() statement, response, confidence = bot.generate_response(input_statement) print('\n Is "{}" this a coherent response to "{}"? \n'.format(response, input_statement)) if get_feedback(): bot.learn_response(response) bot.output.process_response(response, confidence) # Update the conversation history for the bot # It is important that this happens last, after the learning step bot.recent_statements.append( (statement, response, ) ) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
return get_feedback() print('Type something to begin...') # The following loop will execute each time the user enters input while True: try: input_statement = bot.input.process_input_statement() statement, response, confidence = bot.generate_response( input_statement) print('\n Is "{}" this a coherent response to "{}"? \n'.format( response, input_statement)) if get_feedback(): bot.learn_response(response) bot.output.process_response(response, confidence) # Update the conversation history for the bot # It is important that this happens last, after the learning step bot.recent_statements.append(( statement, response, )) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
], preprocessors=['chatterbot.preprocessors.clean_whitespace'], ) trainer = ChatterBotCorpusTrainer(chatbot) trainer.train('./soporte.yml') levenshtein_distance = LevenshteinDistance() #synset_distance = SynsetDistance() #sentiment_comparison = SentimentComparison() #jaccard_similarity = JaccardSimilarity() disparate = Statement( 'Te has equivocado') #convertimos una frase en un tipo statement entradaDelUsuario = "" #variable que contendrá lo que haya escrito el usuario while entradaDelUsuario != "adios": entradaDelUsuario = Statement(text=input()) #leemos la entrada del usuario respuesta = chatbot.generate_response(entradaDelUsuario) try: fecha = datetime_parsing(entradaDelUsuario.text) fecha = fecha[0] print(fecha[0]) except: pass if levenshtein_distance.compare(entradaDelUsuario, disparate) > 0.51: print('¿Qué debería haber dicho?') entradaDelUsuarioCorreccion = Statement(input()) chatbot.learn_response(entradaDelUsuarioCorreccion, entradaDelUsuario) print("He aprendiendo que cuando digas {} debo responder {}".format( entradaDelUsuario.text, entradaDelUsuarioCorreccion.text)) print(respuesta)
class Chatterbot: def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json('data/chatterbot/settings.json') self.chatterbot = ChatBot('Athena', database='LanLogFour', storage_adapter='chatterbot.storage.' 'MongoDatabaseAdapter', input_adapter='chatterbot.input.' 'VariableInputTypeAdapter', output_adapter='chatterbot.output.' 'OutputAdapter', output_format='text', logic_adapters=[ {'import_path': 'chatterbot.logic.' 'BestMatch', 'statement_comparison_function': 'chatterbot.comparisons.' 'levenshtein_distance', 'response_selection_method': 'chatterbot.response_selection.' 'get_most_frequent_response'}, 'chatterbot.logic.MathematicalEvaluation' ] ) self.conversations = {} self.previous_statement = {} @commands.command(pass_context=True) async def chat(self, ctx): """Reads messages from chat""" message = ctx.message.content[6:] conversation_id = self._get_conversation(ctx.message.channel.id) response = await self._get_response(message, conversation_id) await self.bot.say(response) @commands.command() @checks.serverowner_or_permissions(manage_server=True) async def chattertraindocs(self): """Runs training on the docs""" self.chatterbot.set_trainer(ListTrainer) with open('data/chatterbot/doc1.txt') as f: doc1 = f.readlines() with open('data/chatterbot/doc2.txt') as f: doc2 = f.readlines() docData = doc1 + doc2 docData = [x.strip(',') for x in docData] docData = [x.strip('\'') for x in docData] docData = [x.strip('\n') for x in docData] self.chatterbot.train(docData) await self.bot.say("Training complete.") @commands.command() @checks.serverowner_or_permissions(manage_server=True) async def chattertrain(self): self.chatterbot.set_trainer(ChatterBotCorpusTrainer) self.chatterbot.train("chatterbot.corpus.english") await self.bot.say("Training complete") @commands.command(no_pm=True, pass_context=True) @checks.serverowner_or_permissions(manage_server=True) async def chatchannel(self, context, channel: discord.Channel = None): """ Set the channel to which the bot will sent its continues updates. Example: [p]chatchannel #talk """ if channel: self.settings['CHANNEL_ID'] = str(channel.id) dataIO.save_json('data/chatterbot/settings.json', self.settings) message = 'Channel set to {}'.format(channel.mention) elif not self.settings['CHANNEL_ID']: message = 'No Channel set' else: channel = discord.utils.get( self.bot.get_all_channels(), id=self.settings['CHANNEL_ID']) if channel: message = 'Current channel is {}'.format(channel.mention) else: self.settings['CHANNEL_ID'] = None message = 'No channel set' await self.bot.say(message) @commands.command(pass_context=True) @checks.serverowner_or_permissions(manage_server=True) async def chatterignore(self, context, channel: discord.Channel = None): if channel: self.settings['BLOCKED_CHANNELS'].append(channel.id) # TODO: Check if already in list dataIO.save_json('data/chatterbot/settings.json', self.settings) message = '{} added to blocked channels.'.format(channel.mention) elif not self.settings['BLOCKED_CHANNELS']: message = 'No channels blocked' # else: # channel = discord.utils.get( # self.bot.get_all_channels(), # id=self.settings['BLOCKED_CHANNELS']) # if channel: # message = 'Current channel is {}'.format(channel.mention) # else: # self.settings['CHANNEL_ID'] = None # message = 'No channel set' await self.bot.say(message) async def listener(self, message): if message.author.id == self.bot.user.id: pass elif message.content == '': pass elif message.content[0] == '!': # Kludge pass elif message.mention_everyone is True: pass elif message.mentions != []: pass elif message.role_mentions != []: pass elif message.channel.id == self.settings['CHANNEL_ID']: conversation_id = self._get_conversation(message.channel.id) response = await self._get_response(message.content, conversation_id) await self.bot.send_message(message.channel, response) elif message.channel.id not in self.settings['BLOCKED_CHANNELS']: conversation_id = self._get_conversation(message.channel.id) input_statement = self.chatterbot.input.process_input_statement( message.content) if conversation_id in self.previous_statement: self.chatterbot.learn_response( input_statement, self.previous_statement[conversation_id]) self.previous_statement[conversation_id] = input_statement else: self.previous_statement[conversation_id] = input_statement else: pass async def _get_response(self, input_item, conversation_id): input_statement = self.chatterbot.input.process_input_statement( input_item) # Preprocess the input statement for preprocessor in self.chatterbot.preprocessors: input_statement = preprocessor(self.chatterbot, input_statement) statement, response = self.chatterbot.generate_response( input_statement, conversation_id) # Learn that the user's input was a valid response to the chat bot's # previous output if not self.chatterbot.read_only: if conversation_id in self.previous_statement: prev = self.previous_statement[conversation_id] else: prev = None self.chatterbot.learn_response(statement, prev) self.chatterbot.storage.add_to_conversation(conversation_id, statement, response) self.previous_statement[conversation_id] = response # Process the response output with the output adapter return str(response) def _get_conversation(self, channel_id): try: conversation_id = self.conversations[channel_id] except KeyError: conversation_id = self.chatterbot.storage.create_conversation() self.conversations[channel_id] = conversation_id return conversation_id
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 except (KeyboardInterrupt, EOFError, SystemExit): break
class AIChatBot: def __init__(self, bot_name, self_training, low_confidence_threshold, low_confidence_responses, random_response=True, premoderation_callback=None, db_file=None, db_uri=None): """Create new AIChatBot instance. Args: bot_name (str): Bot name. db_uri (str): Database URI. db_file (str): Database file (should not be used, left for backward compatibility) self_training (bool): Will bot train itself. low_confidence_threshold (float): Confidence threshold, if lower - low_confidence_responses will be used. low_confidence_responses (list): Responses that will be used if confidence is lower than threshold. random_response (bool): If true, choose random response instead of the most frequent. premoderation_callback (function): Premoderation function, set None to disable. """ # Backward compatibility if db_uri is None and db_file is not None: db_uri = 'sqlite:///{}'.format(db_file) warnings.warn( 'use db_uri instead of deprecated db_file, it will be removed in the future', DeprecationWarning) self.__chatbot = ChatBot( bot_name, logic_adapters=['chatterbot.logic.BestMatch'], response_selection_method=get_random_response if random_response else get_most_frequent_response, filters=['chatterbot.filters.RepetitiveResponseFilter'], database_uri=db_uri) self.__conversation_id = self.__chatbot.storage.create_conversation() self.previous_response = None self.__self_training = self_training self.__low_confidence_threshold = low_confidence_threshold self.__low_confidence_responses = low_confidence_responses self.__premoderation_callback = premoderation_callback def get_response(self, question, premoderation_payload=None): """Get response to the message. Args: question (str): Message. premoderation_payload: Data to pass to premoderation_callback. Returns: str: Response. """ # Get supposed response question = Statement(question) response = self.__chatbot.generate_response(question, self.__conversation_id)[1] """:type : Response""" # Choose random response if confidence is lower than threshold if response.confidence < self.__low_confidence_threshold and self.__low_confidence_responses: response = Statement(choice(self.__low_confidence_responses)) if self.__premoderation_callback: response = self.__premoderation_callback(question.text, response.text, premoderation_payload) if not response: return response = Statement(response) response.confidence = 1 self.__chatbot.learn_response(response, question) self.__chatbot.storage.add_to_conversation(self.__conversation_id, question, response) if self.__self_training and self.previous_response and '?' in self.previous_response.text and \ self.previous_response.confidence >= self.__low_confidence_threshold: self.__chatbot.learn_response(question, self.previous_response) self.__chatbot.storage.add_to_conversation(self.__conversation_id, self.previous_response, question) self.previous_response = response return response.text def learn(self, question, response): """Learn a response. Args: question (str): Question. response (str): Response """ question = Statement(question) response = Statement(response) self.__chatbot.learn_response(response, question) self.__chatbot.storage.add_to_conversation(self.__conversation_id, question, response) def statement_exists(self, statement_text): """Check if statement exists. Args: statement_text (str): Statement text. Returns: bool """ return True if self.__chatbot.storage.find(statement_text) else False def remove_statement(self, statement_text): """Remove statement from database. Args: statement_text (str): Statement text. """ self.__chatbot.storage.remove(statement_text)
class Bott: def quitaNoAlfaNum(self, texto): import re tmp = re.compile(r'\W+', re.UNICODE).split(texto) return ''.join(str(e + " ") for e in tmp) def __init__(self, nombre_db): self.nombre_db = self.quitaNoAlfaNum(nombre_db) + "db" print "*" + self.nombre_db + "*" self.chatbot = ChatBot( "Chat", storage_adapter='chatterbot.storage.MongoDatabaseAdapter', database_uri='mongodb://localhost:27017/', database='chat_2', #TRAINING trainer='chatterbot.trainers.ListTrainer', #input_adapter="chatterbot.input.TerminalAdapter", #output_adapter="chatterbot.output.TerminalAdapter", logic_adapters=[ { "import_path": "chatterbot.logic.BestMatch", "statement_comparison_function": "chatterbot.comparisons.levenshtein_distance", "response_selection_method": "chatterbot.response_selection.get_most_frequent_response" }, { 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 'threshold': 0.51, 'default_response': 'Disculpa, no he entendido lo que ha querido decir. Puede replantearlo.' }, { 'import_path': 'chatterbot.logic.SpecificResponseAdapter', 'input_text': 'Quiero guardar una cita', 'output_text': 'Puede guardar una cita en http://google.com' }, ], preprocessors=['chatterbot.preprocessors.clean_whitespace'], #read_only=True, ) #DEFAULT_SESSION_ID = chatbot.default_conversation_id from chatterbot.trainers import ChatterBotCorpusTrainer self.chatbot.set_trainer(ChatterBotCorpusTrainer) self.chatbot.train("./cruises_es.yml") # Start by training our bot with the ChatterBot corpus data self.chatbot.train('chatterbot.corpus.spanish') ''' conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you.", "You're welcome." ] chatbot.set_trainer(ListTrainer) chatbot.train(conversation) ''' #request = raw_input("Escriba su pregunta: ") ''' response = chatbot.get_response(None) response = u' '.join((response.text, '')).encode('utf-8').strip() imprimir 'Bot: '+response ''' #ORIGINAL def responder(self, pregunta): #imprimir("Pregunta..."+pregunta) #imprimir("Estamos en chatbot") #pregunta = pregunta.replace('á','ã').replace('é','&etilde;').replace('í','ĩ').replace('ó','õ').replace('ú','ũ').replace('ñ','ñ') pregunta = u' '.join((pregunta, '')).encode('utf-8').strip() response = self.chatbot.get_response(pregunta) response = response.text.replace('ã', 'á').replace( '&etilde;', 'é').replace('ĩ', 'í').replace('õ', 'ó').replace( 'ũ', 'ú').replace('ñ', 'ñ') #response = response.encode("utf-8",'replace') response = u' '.join((response, '')).decode('utf-8').strip() #imprimir response return response #drop database.... #mongo chat_2 --eval "db.dropDatabase()" #entrenando #http://chatterbot.readthedocs.io/en/stable/examples.html #pregunta = raw_input("Ingrese su respuesta y luego su pregunta\n ") #response = chatbot.get_response("Si, como todos") #imprimir "Su respuesta:"+response ''' while True: pregunta = raw_input("Human: ") response = responder(pregunta) imprimir "Bot: "+response ''' #CONVERSATION_ID = self.chatbot.storage.create_conversation() #training #HUMAN:BOT def training(self, input_): #FIJARSE EN FUNCIONES->ENVIAR_MENSAJE tmp = input_.split("lll") human = tmp[0] bot = tmp[1] human_ = Statement(human) #statement, response = chatbot.generate_response(input_statement, CONVERSATION_ID) bot_ = Statement(bot) self.chatbot.learn_response(bot_, human_) #chatbot.storage.add_to_conversation(CONVERSATION_ID, statement, response1) exists = self.chatbot.storage.find(bot_.text) print("Human: " + human_.text) print("Bot: " + bot_.text) return exists.text
text = input() 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 = bot.input.process_input() statement, response = bot.generate_response(input_statement, CONVERSATION) print('\n Is "{}" this a coherent response to "{}"? \n'.format( response, input_statement)) if get_feedback(): bot.learn_response(CONVERSATION, response, input_statement) bot.output.process_response(response) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
#get ansewers from lara bot bot_input = lara.get_response(question) if (bot_input.text == "I am sorry, but I do not understand."): print("Lara :", bot_input.text) print( "Lara: Could you please suggest a response for your question here") proposition = input("Your proposition :") new_response = Statement(proposition, in_response_to=question) new_response.search_text = lara.storage.tagger.get_bigram_pair_string( proposition.lower()) new_response.conversation = str('training') new_response.search_in_response_to = lara.storage.tagger.get_bigram_pair_string( question.lower()) lara.learn_response(new_response) #conn = sqlite3.connect("db.sqlite3") """ Once we have a Connection object, we can then create a Cursor object. Cursors allow us to execute SQL queries against a database. """ #df = pd.read_sql_query("select * from statement;", conn) #print(df.shape) #df.loc[len(df)] = [len(df)+1, question,question,"training","",question,proposition, ""] #df["conversation"].loc[df.in_response_to == question] = "training" #df["search_in_response_to"].loc[df.in_response_to == question] = question #df["persona"].loc[df.in_response_to == question] = "" #print(df.shape) #df.to_sql("statement", conn, if_exists="replace",index = False) #if_exists='append'