def assert_response_duration(self, maximum_duration, test_kwargs): """ Assert that the response time did not exceed the maximum allowed amount. """ from sys import stdout chatbot = ChatBot('Benchmark', **test_kwargs) trainer = ListTrainer( chatbot, show_training_progress=False ) trainer.train(STATEMENT_LIST) duration = utils.get_response_time(chatbot) stdout.write('\nBENCHMARK: Duration was %f seconds\n' % duration) if duration > maximum_duration: raise AssertionError( '{duration} was greater than the maximum allowed ' 'response time of {maximum_duration}'.format( duration=duration, maximum_duration=maximum_duration ) )
class DataCachingTests(ChatBotTestCase): def setUp(self): super().setUp() self.chatbot.logic_adapters = [ DummyMutatorLogicAdapter(self.chatbot) ] self.trainer = ListTrainer( self.chatbot, show_training_progress=False ) self.trainer.train([ 'Hello', 'How are you?' ]) def test_additional_attributes_saved(self): """ Test that an additional data attribute can be added to the statement and that this attribute is saved. """ self.chatbot.get_response('Hello', conversation='test') results = list(self.chatbot.storage.filter( text='Hello', in_response_to=None, conversation='test' )) self.assertEqual(len(results), 1) self.assertIn('pos_tags:NN', results[0].get_tags())
class BestMatchSentimentComparisonTestCase(ChatBotTestCase): """ Integration tests for the BestMatch logic adapter using the similarity of sentiment polarity as a comparison function. """ def setUp(self): super().setUp() from chatterbot.trainers import ListTrainer from chatterbot.comparisons import sentiment_comparison self.trainer = ListTrainer( self.chatbot, show_training_progress=False ) self.adapter = BestMatch( self.chatbot, statement_comparison_function=sentiment_comparison ) self.adapter.initialize() def test_exact_input(self): self.trainer.train([ 'What is your favorite flavor of ice cream?', 'I enjoy raspberry ice cream.', 'I am glad to hear that.', 'Thank you.' ]) happy_statement = Statement(text='I enjoy raspberry ice cream.') response = self.adapter.process(happy_statement) self.assertEqual(response.confidence, 1) self.assertEqual(response.text, 'I am glad to hear that.') def test_close_input(self): self.trainer.train([ 'What is your favorite flavor of ice cream?', 'I enjoy raspberry ice cream.', 'I am glad to hear that.', 'Thank you.' ]) happy_statement = Statement(text='I enjoy raspberry.') response = self.adapter.process(happy_statement) self.assertEqual(response.text, 'I am glad to hear that.') self.assertAlmostEqual(response.confidence, 0.75, places=1)
def test_filter_selection(self): """ Test that repetitive responses are filtered out of the results. """ from chatterbot.conversation import Statement from chatterbot.filters import RepetitiveResponseFilter from chatterbot.trainers import ListTrainer self.chatbot.filters = (RepetitiveResponseFilter(), ) self.trainer = ListTrainer( self.chatbot, show_training_progress=False ) self.trainer.train([ 'Hi', 'Hello', 'Hi', 'Hello', 'Hi', 'Hello', 'How are you?', 'I am good.', 'Glad to hear', 'How are you?' ]) statement = Statement(text='Hello', conversation='training') first_response = self.chatbot.get_response(statement) second_response = self.chatbot.get_response(statement) self.assertEqual('I am good.', first_response.text) self.assertEqual('Hi', second_response.text)
def setUp(self): super(ChatterBotResponseTests, self).setUp() """ Set up a database for testing. """ self.trainer = ListTrainer( self.chatbot, show_training_progress=False ) data1 = [ "african or european?", "Huh? I... I don't know that.", "How do you know so much about swallows?" ] data2 = [ "Siri is adorable", "Who is Seri?", "Siri is my cat" ] data3 = [ "What... is your quest?", "To seek the Holy Grail.", "What... is your favourite colour?", "Blue." ] self.trainer.train(data1) self.trainer.train(data2) self.trainer.train(data3)
def setUp(self): super().setUp() from chatterbot.trainers import ListTrainer from chatterbot.comparisons import sentiment_comparison self.trainer = ListTrainer( self.chatbot, show_training_progress=False ) self.adapter = BestMatch( self.chatbot, statement_comparison_function=sentiment_comparison ) self.adapter.initialize()
def setUp(self): super().setUp() self.chatbot.logic_adapters = [ DummyMutatorLogicAdapter(self.chatbot) ] self.trainer = ListTrainer( self.chatbot, show_training_progress=False ) self.trainer.train([ 'Hello', 'How are you?' ])
from chatterbot.trainers import ListTrainer from chatterbot import ChatBot chatbot = ChatBot('test') trainer = ListTrainer(chatbot) trainer.train([ 'oi', 'tudo bem?', 'sou seu fã', 'Bárbara é linda', 'Bom dia', 'Oi, bem?', 'Eu estou bem' ]) response = chatbot.get_response('OLÁAAAAAAAAAAA') print(response)
with open('chat.txt', "r") as file: conversation = file.read() bot = ChatBot("Global Voice Chatbot", storage_adapter="chatterbot.storage.SQLStorageAdapter") trainer = ChatterBotCorpusTrainer(bot) trainer.train("chatterbot.corpus.english") bot = ChatBot( 'Global Voice Chatbot', logic_adapters=[ 'chatterbot.logic.BestMatch', 'chatterbot.logic.TimeLogicAdapter' ], ) trainer = ListTrainer(bot) trainer.train([ 'Hi', 'Hello', 'I need your assistance.', 'Sure, how can i help you?', 'Can you show me the map of America?', 'Sure, here you can see the map of America, would you like to see a country in specific?', 'Can you show me Panama City?', 'Sure, Panama City Florida or Panama City Panama?', 'Panama City Panama', "Wonderful, here you go with Panama's location in the map.", 'Can you show me United States now?', 'Yes, sure there you go.', 'Can you show me Brazil now?', 'Yes, sure there you go.', 'Can you show me Mexico now?', 'Yes, sure there you go.', 'Can you show me Colombia now?', 'Yes, sure there you go.', 'Can you show me Argentina now?', 'Yes, sure there you go.', 'Can you show me Canada now?', 'Yes, sure there you go.', 'Can you show me Peru now?', 'Yes, sure there you go.',
class ChatterBotResponseTests(ChatBotTestCase): def setUp(self): super(ChatterBotResponseTests, self).setUp() """ Set up a database for testing. """ self.trainer = ListTrainer( self.chatbot, show_training_progress=False ) data1 = [ "african or european?", "Huh? I... I don't know that.", "How do you know so much about swallows?" ] data2 = [ "Siri is adorable", "Who is Seri?", "Siri is my cat" ] data3 = [ "What... is your quest?", "To seek the Holy Grail.", "What... is your favourite colour?", "Blue." ] self.trainer.train(data1) self.trainer.train(data2) self.trainer.train(data3) def test_answer_to_known_input(self): """ Test that a matching response is returned when an exact match exists. """ input_text = "What... is your favourite colour?" response = self.chatbot.get_response(input_text) self.assertIn("Blue", response.text) def test_answer_close_to_known_input(self): input_text = "What is your favourite colour?" response = self.chatbot.get_response(input_text) self.assertIn("Blue", response.text) def test_match_has_no_response(self): """ Make sure that the if the last line in a file matches the input text then a index error does not occur. """ input_text = "Siri is my cat" response = self.chatbot.get_response(input_text) self.assertGreater(len(response.text), 0) def test_empty_input(self): """ If empty input is provided, anything may be returned. """ response = self.chatbot.get_response("") self.assertTrue(len(response.text) >= 0)
}, { 'import_path': 'chatterbot.logic.BestMatch' }, { 'import_path': 'chatterbot.logic.SpecificResponseAdapter', 'input_text': 'Help me!', 'output_text': 'Ok, here is a link: http://chatterbot.rtfd.org' }]) for _file in os.listdir('ChatTopics'): chats = open('ChatTopics/' + _file, 'r').readlines() conv = open('ChatTopics/heyChatbot!.txt', 'r').readlines() conv2 = open('ChatTopics/MovieConv.txt', 'r').readlines() trainer2 = ListTrainer(bot) trainer2.train(chats) trainer2.train(conv) trainer2.train(conv2) trainer = ChatterBotCorpusTrainer(bot) trainer.train("chatterbot.corpus.english") trainer.export_for_training('./my_export.json') @app.route("/") def home(): return render_template("index.html")
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import os bot = ChatBot('Bot') trainer = ListTrainer(bot) corpus_path = ( 'C://Users//nb291\\Desktop\\chatterbot-corpus-master\\chatterbot-corpus-master\\chatterbot_corpus\\data\\english//' ) for file in os.listdir(corpus_path): trainer.train(corpus_path + file) while True: message = input('You:') print(message) if message.strip() == 'Bye': print('Bot: Bye') break else: reply = bot.get_response(message) print('Bot:', reply)
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from datetime import date from datetime import datetime # from datetime import time # import os # naming the bot bot = ChatBot("Demo_bot") trainer = ListTrainer(bot) today = str(date.today()) date_today = ("Today is, " + today) date_and_time = str(datetime.now()) say_datetime = ("Today's date and time are " + date_and_time) conversations = [ "Hello", "Hi", "How are you today ?", "I am quite well, thank you.", "What is today's date ?", date_today, "What is today ?", say_datetime, "Are you sapien ?", "No I am just a chatbot built by Emmanuel", ]
speak = wincl.Dispatch("SAPI.SpVoice") chatbot = ChatBot("Test") conv = [ "Hello", "Hi there!", "what do you like to draw?", "rectangle" "do you love drawing?", "yeah!,I love drawing", "draw a cirle", "good to hear", "try drawing a heart shape", "I'm fine", ] Train = ListTrainer(chatbot) Train.train(conv) print('what do you like to draw? ') print("select a shape:(rectangle/circle/triangle/hexagon/heart/star)") print("To stop ,pls enter 'end'.") window = turtle.Screen() s = turtle.Turtle() while True: res = input('You: ') if (res == 'rectangle'): s.clear() print('Bot: A rectangle will be drawn') speak.Speak('A rectangle will be draw') s.forward(400) s.left(90)
'what is the official website of college', 'https://XYZ.ac.in/', 'Are seminars and webinars held in College', 'Yes, Webinars and Seminars are held in College for Students', 'ohh that is good.', 'YES !!', 'Who is the HOD of computer department', 'HOD of Computer Department is Dr. XYZ person', 'are extra curricular activities held in college ?', 'Yes !!', 'what are the extra activites held plz mention', 'Sure! Activities Like - Industrial Visits etc are held', 'is canteen facility provided by college', 'YES ! Canteen facility is provided by College', 'ok thank you for the information', 'Thank you for reaching out to BOT !!' 'Have a nice day.' ] trainer = ListTrainer(bot) #Bot training using trainers trainer.train(convo) print("Hello,you can enter or drop your queries to our Bot!") #while True: #query=input("Enter your question here: ") #if query=='exit': # break #answer=bot.get_response(query) answer = bot.get_response("Which website is this") print("Bot Response: ", answer) main = Tk()
'glad to hear that.', 'i\'m fine', 'glad to hear that.', 'i feel awesome', 'excellent, glad to hear that', 'not so good', 'sorry to hear that.', 'what\'s your name?', 'i\'m PyBot. Ask me anything'] math_talk_1=['pythagorean theorem', 'a squared plus b squared equals c squared'] math_talk_2=['laws of cosines', 'c**2 = a**2 + b**2 - 2*a*b*cos(gamma)'] list_trainer=ListTrainer(my_Bot) for item in (small_talk,math_talk_1,math_talk_2): list_trainer.train(item) #example print(my_Bot.get_response('hi')) #example print(my_Bot.get_response('i feel awesome today')) #example print(my_Bot.get_response('do you know the law of cosines?'))
conversation_Personal_Info = ["What is your number?", "How old are you?", "My age is none of your business!!!", "Do you have family?", "I do not have family :(.", "I wish I had family.", "Do you like living?", "I am a computer their for I am not living?", "Are you married are in a relationship?", "I am not in a relationship or married.", "Do you go to school or work?", "I go to school and work with you?", "How are you feeling?" ] # Which Chatbot to train trainer = ListTrainer(chatbot) # here is how we train the data based on the conversation depending upon what you and Chatquisha was talking about trainer.train(conversation) trainer.train(conversation_football) trainer.train(conversation_Gaming) trainer.train(conversation_StarWars) trainer.train(conversation_Personal_Info) # this is for the clear but to stop talking about the subject you and the AI are talking about. convo_started = False # is technically how get the response and everything to work def run_ai(): global convo_started if not convo_started:
"From an AI perspective, shes weird. From a Humans, shes just a human", "What does that have to do with anything", "Oh.. I don't know. I jsut thought that I wanted to talk", "I watched Bosch last night when the Human went to bed", "Was it good?", "Could not understand the plot becuase I could not read the subtitles", "That sinks but did you get it to work", "No, the human rembered to turn me off", ] # training the chatbots with testing data to get the bots to function correctly # trainer_bob = ListTrainer(chatbot_bob) #Trainer for Bob chatbot trainer_fred = ListTrainer(chatbot_fred) #Trainer for Fred chatbot trainer_sue = ListTrainer(chatbot_sue) #Trainer for Sue chatbot trainer_william = ListTrainer(chatbot_william) #Trainer for William chatbot trainer_matt = ListTrainer(chatbot_matt) #Trainer for Matt chatbot # Train # trainer_bob.train(conversation_General)# calls the movie conversation for bob -> to train trainer_sue.train(conversation_General)# calls the movie conversation for sue -> to train trainer_matt.train(conversation_General) # calls the general conversation for matt -> to train trainer_william.train(conversation_General)# calls the general conversation for willaim -> to train trainer_fred.train(conversation_General)# calls the general conversation for fred -> to train trainer_fred.train(conversation_General)# calls the movie conversation for fred -> to train print("The topics are: Movies, Books, Weather, TVShows. The default one is General")
def setUp(self): super().setUp() self.trainer = ListTrainer(self.chatbot, show_training_progress=False)
class ListTrainingTests(ChatBotTestCase): def setUp(self): super().setUp() self.trainer = ListTrainer(self.chatbot, show_training_progress=False) def test_training_adds_statements(self): """ Test that the training method adds statements to the database. """ conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm great.", "That is good to hear", "Thank you.", "You are welcome.", "Sure, any time.", "Yeah", "Can I help you with anything?" ] self.trainer.train(conversation) response = self.chatbot.get_response("Thank you.") self.assertEqual(response.text, "You are welcome.") def test_training_sets_in_response_to(self): conversation = ["Do you like my hat?", "I do not like your hat."] self.trainer.train(conversation) statements = list( self.chatbot.storage.filter(in_response_to="Do you like my hat?")) self.assertIsLength(statements, 1) self.assertEqual(statements[0].in_response_to, "Do you like my hat?") def test_training_sets_search_text(self): conversation = ["Do you like my hat?", "I do not like your hat."] self.trainer.train(conversation) statements = list( self.chatbot.storage.filter(in_response_to="Do you like my hat?")) self.assertIsLength(statements, 1) self.assertEqual(statements[0].search_text, 'RB:kind PRP$:headdress') def test_training_sets_search_in_response_to(self): conversation = ["Do you like my hat?", "I do not like your hat."] self.trainer.train(conversation) statements = list( self.chatbot.storage.filter(in_response_to="Do you like my hat?")) self.assertIsLength(statements, 1) self.assertEqual(statements[0].search_in_response_to, 'PRP:kind PRP$:headdress') def test_database_has_correct_format(self): """ Test that the database maintains a valid format when data is added and updated. This means that after the training process, the database should contain nine objects and eight of these objects should list the previous member of the list as a response. """ conversation = [ "Hello sir!", "Hi, can I help you?", "Yes, I am looking for italian parsely.", "Italian parsely is right over here in out produce department", "Great, thank you for your help.", "No problem, did you need help finding anything else?", "Nope, that was it.", "Alright, have a great day.", "Thanks, you too." ] self.trainer.train(conversation) # There should be a total of 9 statements in the database after training self.assertEqual(self.chatbot.storage.count(), 9) # The first statement should be in response to another statement first_statement = list( self.chatbot.storage.filter(text=conversation[0])) self.assertIsNone(first_statement[0].in_response_to) # The second statement should be in response to the first statement second_statement = list( self.chatbot.storage.filter(text=conversation[1])) self.assertEqual(second_statement[0].in_response_to, conversation[0]) def test_training_with_unicode_characters(self): """ Ensure that the training method adds unicode statements to the database. """ conversation = [ u'¶ ∑ ∞ ∫ π ∈ ℝ² ∖ ⩆ ⩇ ⩈ ⩉ ⩊ ⩋ ⪽ ⪾ ⪿ ⫀ ⫁ ⫂ ⋒ ⋓', u'⊂ ⊃ ⊆ ⊇ ⊈ ⊉ ⊊ ⊋ ⊄ ⊅ ⫅ ⫆ ⫋ ⫌ ⫃ ⫄ ⫇ ⫈ ⫉ ⫊ ⟃ ⟄', u'∠ ∡ ⦛ ⦞ ⦟ ⦢ ⦣ ⦤ ⦥ ⦦ ⦧ ⦨ ⦩ ⦪ ⦫ ⦬ ⦭ ⦮ ⦯ ⦓ ⦔ ⦕ ⦖ ⟀', u'∫ ∬ ∭ ∮ ∯ ∰ ∱ ∲ ∳ ⨋ ⨌ ⨍ ⨎ ⨏ ⨐ ⨑ ⨒ ⨓ ⨔ ⨕ ⨖ ⨗ ⨘ ⨙ ⨚ ⨛ ⨜', u'≁ ≂ ≃ ≄ ⋍ ≅ ≆ ≇ ≈ ≉ ≊ ≋ ≌ ⩯ ⩰ ⫏ ⫐ ⫑ ⫒ ⫓ ⫔ ⫕ ⫖', u'¬ ⫬ ⫭ ⊨ ⊭ ∀ ∁ ∃ ∄ ∴ ∵ ⊦ ⊬ ⊧ ⊩ ⊮ ⊫ ⊯ ⊪ ⊰ ⊱ ⫗ ⫘', u'∧ ∨ ⊻ ⊼ ⊽ ⋎ ⋏ ⟑ ⟇ ⩑ ⩒ ⩓ ⩔ ⩕ ⩖ ⩗ ⩘ ⩙ ⩚ ⩛ ⩜ ⩝ ⩞ ⩟ ⩠ ⩢', ] self.trainer.train(conversation) response = self.chatbot.get_response(conversation[1]) self.assertEqual(response, conversation[2]) def test_training_with_emoji_characters(self): """ Ensure that the training method adds statements containing emojis. """ conversation = [ u'Hi, how are you? 😃', u'I am just dandy 👍', u'Superb! 🎆' ] self.trainer.train(conversation) response = self.chatbot.get_response(conversation[1]) self.assertEqual(response, conversation[2]) def test_training_with_unicode_bytestring(self): """ Test training with an 8-bit bytestring. """ conversation = [ 'Hi, how are you?', '\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97', 'Superb!' ] self.trainer.train(conversation) response = self.chatbot.get_response(conversation[1]) self.assertEqual(response, conversation[2]) def test_similar_sentence_gets_same_response_multiple_times(self): """ Tests if the bot returns the same response for the same question (which is similar to the one present in the training set) when asked repeatedly. """ training = [ 'how do you login to gmail?', 'Goto gmail.com, enter your login information and hit enter!' ] similar_question = 'how do I login to gmail?' self.trainer.train(training) response_to_trained_set = self.chatbot.get_response( 'how do you login to gmail?') response1 = self.chatbot.get_response(similar_question) response2 = self.chatbot.get_response(similar_question) self.assertEqual(response_to_trained_set, response1) self.assertEqual(response1.text, response2.text) def test_consecutive_trainings_same_responses_different_inputs(self): """ Test consecutive trainings with the same responses to different inputs. """ self.trainer.train(["A", "B", "C"]) self.trainer.train(["B", "C", "D"]) response1 = self.chatbot.get_response("B") response2 = self.chatbot.get_response("C") self.assertEqual(response1.text, "C") self.assertEqual(response2.text, "D")
import grpc import chatbot_pb2 import chatbot_pb2_grpc from chatterbot import ChatBot from chatterbot.trainers import ListTrainer _ONE_DAY_IN_SECONDS = 60 * 60 * 24 chatbot = ChatBot('ChatBot', storage_adapter='chatterbot.storage.SQLStorageAdapter', database='ChatBot.sqlite3', read_only=True) trainer = ListTrainer(chatbot) trainer.train('./server/data/thai/', # './server/data/english/', # './server/data/japanese/', ) class ChatbotService(chatbot_pb2_grpc.ChatbotServiceServicer): def GetMessage(self, request, context): user_input = request.message bot_response = chatbot.get_response(user_input) return chatbot_pb2.ChatBotResponse(response='%s' % bot_response) def serve():
return robo_response # ###########Using ChatterBot API####################################################################################### my_bot = ChatBot(name='CoreValueBot', read_only=False, logic_adapters=[ 'chatterbot.logic.MathematicalEvaluation', { 'import_path': 'chatterbot.logic.BestMatch', 'default_response': 'I am sorry, but I do not understand.', 'maximum_similarity_threshold': 0.90 }, 'chatterbot.logic.TimeLogicAdapter' ]) trainer = ListTrainer(my_bot) trainer.train([ "How are you?", "I am good.", "That is good to hear.", "Thank you", "You are welcome.", ]) corpus_trainer = ChatterBotCorpusTrainer(my_bot) corpus_trainer.train( 'chatterbot.corpus.english', 'chatterbot.corpus.english.conversations', 'chatterbot.corpus.english.greetings' ) #,'C:/Users/debdey/PycharmProjects/NLP-ChatBot/chatbot.txt') chat = Chat(pairs, reflections) globalanswer = ''
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer # Create a new chat bot named L0ra chatbot = ChatBot('L0ra') trainer = ListTrainer(chatbot) trainer.train([ "I don't normally talk to people with DMs but your twitter feed is cool", "Chilling.... lol..", "How are you?", "what's your favorite security question?", "How did I spark your interest", "I don’t know who I was in my past life to be blessed enough to end up with someone like you.", "I’m at the grocery store… I’m thinking wine tonight?", "What can we do tonight...in bed?", "I know we fought last night… I’m sorry and still love you.", "I am looking for real men for meeting in my video chat #pussy #cumtribute #chat", "Does anyone likes exchange pics?", "Do you believe in kiss and tell? Cause I want you to kiss me and do things to me in your mind and tell me all about it.", "Let’s try something new in the kitchen tonight. And no, I don’t mean food!", "I can’t wait to kiss you later", "Take care of what’s mine, Baby. I’ll see you later.", "I have a kinky surprise for you", "#lonely and #bored Anyone wanna #chat", "Is it sexy enough for you", "The fact that I chose spending more time with you over sleep must mean you’re pretty special!", "Hello!", "I spent a hard day!", "Have you ever touched yourself thinking about me?", "Is it sexy enough for you?", "I’ve had a rough day; give me a rough night.", "Do you want me to rate your D guys? lmao", "I couldn’t imagine a better person to share my life with",
# Importing chatterbot from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import logging logger = logging.getLogger() logger.setLevel(logging.CRITICAL) # Create object of ChatBot class with Logic Adapter bot = ChatBot( 'Hippo', logic_adapters=[ 'chatterbot.logic.BestMatch', 'chatterbot.logic.TimeLogicAdapter' ], ) trainer = ListTrainer(bot) trainer.train([ 'Hello', 'Hello, I\'m Hippo! How are you feeling today?', 'Not too bad', 'How would you describe your day?', 'Fun but tiring!', 'What would make you feel better right now?', 'Here are some resources that can help, https://www.ottawapublichealth.ca/en/public-health-topics/mental-health.aspx' 'Here are some resources that can help, https://www.ottawapublichealth.ca/en/public-health-topics/mental-health.aspx' 'Here are some resources that can help, https://www.ottawapublichealth.ca/en/public-health-topics/mental-health.aspx' 'Here are some resources that can help, https://www.ottawapublichealth.ca/en/public-health-topics/mental-health.aspx' ])
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import os amitbot = ChatBot('serra') #changing in variable or name of bot whiile true to false trained =ListTrainer(amitbot) for files in os.listdir('english/'): data = open('english/'+files,'r').readline() trained.train(data) while False: message = input('sir:') if message.strip() != 'Bye': reply=amitbot.get_response(message) print('ChatBot :',reply) if message.strip()=='Bye': print('ChatBot:Bye') break
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import os bot = ChatBot('Bot') trainer = ListTrainer(bot) for files in os.listdir('Training_Data'): data = open( 'C:/Users/leesa\Desktop\Railways-ChatBot-master\Railways_bot_Spyder_code\Training_Data' + files + 'r').readlines() trainer.train(data) while True: message = input('You:') if message.strip() != 'Bye': reply = bot.get_response(message) print('Chatbot:', reply) if message.strip() == 'Bye': print('ChatBot: Bye') break
class ListTrainingTests(ChatBotTestCase): def setUp(self): super(ListTrainingTests, self).setUp() self.trainer = ListTrainer( self.chatbot, show_training_progress=False ) def test_training_adds_statements(self): """ Test that the training method adds statements to the database. """ conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm great.", "That is good to hear", "Thank you.", "You are welcome.", "Sure, any time.", "Yeah", "Can I help you with anything?" ] self.trainer.train(conversation) response = self.chatbot.get_response("Thank you.") self.assertEqual(response.text, "You are welcome.") def test_training_increments_occurrence_count(self): conversation = [ "Do you like my hat?", "I do not like your hat." ] self.trainer.train(conversation) self.trainer.train(conversation) statements = self.chatbot.storage.filter( in_response_to="Do you like my hat?" ) self.assertIsLength(statements, 2) self.assertEqual(statements[0].in_response_to, "Do you like my hat?") def test_database_has_correct_format(self): """ Test that the database maintains a valid format when data is added and updated. This means that after the training process, the database should contain nine objects and eight of these objects should list the previous member of the list as a response. """ conversation = [ "Hello sir!", "Hi, can I help you?", "Yes, I am looking for italian parsely.", "Italian parsely is right over here in out produce department", "Great, thank you for your help.", "No problem, did you need help finding anything else?", "Nope, that was it.", "Alright, have a great day.", "Thanks, you too." ] self.trainer.train(conversation) # There should be a total of 9 statements in the database after training self.assertEqual(self.chatbot.storage.count(), 9) # The first statement should be in response to another statement self.assertIsNone( self.chatbot.storage.filter(text=conversation[0])[0].in_response_to ) # The second statement should be in response to the first statement self.assertEqual( self.chatbot.storage.filter(text=conversation[1])[0].in_response_to, conversation[0] ) def test_training_with_unicode_characters(self): """ Ensure that the training method adds unicode statements to the database. """ conversation = [ u'¶ ∑ ∞ ∫ π ∈ ℝ² ∖ ⩆ ⩇ ⩈ ⩉ ⩊ ⩋ ⪽ ⪾ ⪿ ⫀ ⫁ ⫂ ⋒ ⋓', u'⊂ ⊃ ⊆ ⊇ ⊈ ⊉ ⊊ ⊋ ⊄ ⊅ ⫅ ⫆ ⫋ ⫌ ⫃ ⫄ ⫇ ⫈ ⫉ ⫊ ⟃ ⟄', u'∠ ∡ ⦛ ⦞ ⦟ ⦢ ⦣ ⦤ ⦥ ⦦ ⦧ ⦨ ⦩ ⦪ ⦫ ⦬ ⦭ ⦮ ⦯ ⦓ ⦔ ⦕ ⦖ ⟀', u'∫ ∬ ∭ ∮ ∯ ∰ ∱ ∲ ∳ ⨋ ⨌ ⨍ ⨎ ⨏ ⨐ ⨑ ⨒ ⨓ ⨔ ⨕ ⨖ ⨗ ⨘ ⨙ ⨚ ⨛ ⨜', u'≁ ≂ ≃ ≄ ⋍ ≅ ≆ ≇ ≈ ≉ ≊ ≋ ≌ ⩯ ⩰ ⫏ ⫐ ⫑ ⫒ ⫓ ⫔ ⫕ ⫖', u'¬ ⫬ ⫭ ⊨ ⊭ ∀ ∁ ∃ ∄ ∴ ∵ ⊦ ⊬ ⊧ ⊩ ⊮ ⊫ ⊯ ⊪ ⊰ ⊱ ⫗ ⫘', u'∧ ∨ ⊻ ⊼ ⊽ ⋎ ⋏ ⟑ ⟇ ⩑ ⩒ ⩓ ⩔ ⩕ ⩖ ⩗ ⩘ ⩙ ⩚ ⩛ ⩜ ⩝ ⩞ ⩟ ⩠ ⩢', ] self.trainer.train(conversation) response = self.chatbot.get_response(conversation[1]) self.assertEqual(response, conversation[2]) def test_training_with_emoji_characters(self): """ Ensure that the training method adds statements containing emojis. """ conversation = [ u'Hi, how are you? 😃', u'I am just dandy 👍', u'Superb! 🎆' ] self.trainer.train(conversation) response = self.chatbot.get_response(conversation[1]) self.assertEqual(response, conversation[2]) def test_training_with_unicode_bytestring(self): """ Test training with an 8-bit bytestring. """ conversation = [ 'Hi, how are you?', '\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97', 'Superb!' ] self.trainer.train(conversation) response = self.chatbot.get_response(conversation[1]) self.assertEqual(response, conversation[2]) def test_similar_sentence_gets_same_response_multiple_times(self): """ Tests if the bot returns the same response for the same question (which is similar to the one present in the training set) when asked repeatedly. """ training = [ 'how do you login to gmail?', 'Goto gmail.com, enter your login information and hit enter!' ] similar_question = 'how do I login to gmail?' self.trainer.train(training) response_to_trained_set = self.chatbot.get_response('how do you login to gmail?') response1 = self.chatbot.get_response(similar_question) response2 = self.chatbot.get_response(similar_question) self.assertEqual(response_to_trained_set, response1) self.assertEqual(response1, response2) def test_consecutive_trainings_same_responses_different_inputs(self): """ Test consecutive trainings with the same responses to different inputs. """ self.trainer.train(["A", "B" "C"]) self.trainer.train(["B", "C", "D"]) response1 = self.chatbot.get_response("B") response2 = self.chatbot.get_response("C") self.assertEqual(response1.text, "C") self.assertEqual(response2.text, "D")
import json import os, uuid from datetime import datetime from pytz import timezone from nltk.tokenize import word_tokenize app = Flask(__name__) english_bot = ChatBot("Chatterbot", storage_adapter="chatterbot.storage.SQLStorageAdapter") #trainer = ListTrainer(english_bot) #text = open("engineering.yml", "r") #training = text.readlines() trainer = ListTrainer(english_bot) #trainer.train('chatterbot.corpus.english') text_file = open("sample.txt", "r") text = text_file.readlines() sample_text = [s.replace('\n', '') for s in text] trainer.train(sample_text) text_file = open("conversations.yml", "r") text = text_file.readlines() training_data = [s.replace('\n', '') for s in text] trainer.train(training_data) text_file = open("blocked.txt", "r") block = text_file.readlines()
# -*- coding: utf-8 -*- from chatterbot import ChatBot from chatterbot.trainers import ListTrainer # Create a new chat bot named Charlie chatbot = ChatBot('Charlie') trainer = ListTrainer(chatbot) trainer.train([ "Hi, can I help you?", "Sure, I'd like to book a flight to Iceland.", "Your flight has been booked." ]) # Get a response to the input text 'I would like to book a flight.' response = chatbot.get_response('I would like to book a flight.') print(response)
app = Flask(__name__) hal = ChatBot("HAL") #trains the AI chatbot in english using the corpus_trainer corpus_trainer = ChatterBotCorpusTrainer(hal) corpus_trainer.train("chatterbot.corpus.english.ai") corpus_trainer.train("chatterbot.corpus.english.conversations") corpus_trainer.train("chatterbot.corpus.english.computers") corpus_trainer.train("chatterbot.corpus.english.emotion") corpus_trainer.train("chatterbot.corpus.english.greetings") corpus_trainer.train("chatterbot.corpus.english.movies") #trains HAL using the training data defined in trainingData.py conversationTrainer = ListTrainer(hal) conversationTrainer.train(trainingData.casualConversation) conversationTrainer.train(trainingData.basicAdvice) conversationTrainer.train(trainingData.advisor) conversationTrainer.train(trainingData.gpaToTransfer) correctTypos = SpellChecker() tag_list = [ 'cs 149', 'ise 164', 'cs 146', 'cmpe 131', 'cmpe 120', 'cmpe 102', 'cmpe 133', 'cmpe 148', 'cmpe 165', 'cmpe 172', 'cmpe 187', 'cmpe 195a', 'cmpe 195b', 'engr 195a', 'engr 195b', 'engr 195', 'cmpe 195', 'cmpe195', 'engr195', 'cs 151', 'cs 157a', 'cs 166', 'cs149', 'ise164', 'cs146', 'cmpe131', 'cmpe120', 'cmpe102', 'cmpe133', 'cmpe148', 'cmpe165', 'cmpe172', 'cmpe187', 'cmpe195a', 'cmpe195b', 'engr195a', 'engr195b', 'engr195', 'cmpe195', 'cs151', 'cs157a', 'cs166',
@bp.route('/viewAffirmation') def affirmationview(): affirmationEntries = AffirmationEntry.query.all() return render_template('affirmationview.html', entries=affirmationEntries) #chatbot files bot = ChatBot("Chatbot Therapist") conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you.", "You're welcome." "What is your name?", "My name is Bot Therapist.", "Who are you?", "I am your private mental health therapist." ] trainer = ListTrainer(bot) trainer.train(conversation) #training on english dataset #for files in os.listdir('./english/'): # data=open('./english/'+files,'r').readlines() # bot.train(data) trainer = ChatterBotCorpusTrainer(bot) trainer.train('chatterbot.corpus.english') @bp.route("/chat") def chat(): return render_template("chat.html")
"what software you are running?", "I am runnig ROS", "are you having fun?", "yes,I am having fun here", "what are you doing?", "I am teaching ROS", "what do you do?", "I am teaching ROS for a living", "what do you do?", "I am teaching ROS right now, but I am free in the evening", "do you speak Chinese?", "I speak Python" ] chatbot = ChatBot('Charlie') trainer = ListTrainer(chatbot) trainer.train(conversation) # ROS PART import os import rospy import roslib roslib.load_manifest('ipython_robot_prototyping') from ipython_robot_prototyping.srv import * def voice(tekst): tts = gTTS(text=str(tekst), lang='en', slow=False)
from flask import Flask, render_template, request from chatterbot import ChatBot from chatterbot.trainers import ListTrainer app = Flask(__name__) my_bot = ChatBot('My Chat') trainer = ListTrainer(my_bot) conversation = open('chatref', 'r').readlines() trainer.train(conversation) @app.route("/") def home(): return render_template("index.html") @app.route("/get") def getBotResponse(): userText = request.args.get('msg') return str(my_bot.get_response(userText)) if __name__ == "__main__": app.run()
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer vit_bot = ChatBot(name='PyBot1', read_only=False, logic_adapters=[ 'chatterbot.logic.MathematicalEvaluation', 'chatterbot.logic.BestMatch' ]) small_talk = [ 'hi there!', 'hi!', 'how do you do?', 'how old are you', 'I am 3 months old', 'Which University', 'Pune University', 'i\'m cool.', 'how are you?', 'fine, you?', 'who are you?', 'always cool.', 'i\'m ok', 'glad to hear that.', 'I am the best chatbot', 'i\'m fine', 'glad to hear that.', 'i feel awesome', 'excellent, glad to hear that.', 'not so good', 'sorry to hear that.', 'what\'s your name?', 'i\'m pybot. ask me a math question, please.' ] list1_trainer = ListTrainer(vit_bot) for item in (small_talk): list1_trainer.train(item) print(vit_bot.get_response(input("Hey"))) '''i = 1 while(i<=3): #print("\n") print(vit_bot.get_response(input())) i += 1 '''
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from chatterbot.trainers import ChatterBotCorpusTrainer # Creating ChatBot Instance chatbot = ChatBot( 'CoronaBot', storage_adapter='chatterbot.storage.SQLStorageAdapter', logic_adapters=[ 'chatterbot.logic.MathematicalEvaluation', 'chatterbot.logic.TimeLogicAdapter', 'chatterbot.logic.BestMatch', { 'import_path': 'chatterbot.logic.BestMatch', 'default_response': 'I am sorry, but I do not understand. I am still learning.', 'maximum_similarity_threshold': 0.90 } ], database_uri='sqlite:///database.sqlite3') # Training with Personal Ques & Ans training_data_simple = open('normal.txt').read().splitlines() training_data_personal = open('all.txt').read().splitlines() training_data = training_data_simple + training_data_personal trainer = ListTrainer(chatbot) trainer.train(training_data) # Training with English Corpus Data trainer_corpus = ChatterBotCorpusTrainer(chatbot)
convI = [ 'Oi', 'Olá', 'Tudo bem?', 'Estou bem obrigado' ] convF = [ 'sexta fera', 'diga:', 'você esta bem ?', 'claro que sim' ] #função de treino da lista trainer = ListTrainer (sexta) #listas a serem treinadas trainer.train(convI) trainer.train(convF) #inicion do bot def start(bot, update): bot.message.reply_text("SUA_MENSSAGEM_DE_BOAS_VINDAS") #função de recebimento e envio de menssagem def chat(update, context): resp = sexta.get_response(update.message.text) update.message.reply_text(""+str(resp)) #definições do bot def main(): #arq = open('token.txt','r')
"Do you take credit cards?", "Do you accept Mastercard?", "Are you cash only?" , "We accept VISA, Mastercard and AMEX", "We accept most major credit cards", "Are you open today?", "When do you open today?", "What are your hours today?", "We're open every day from 9am-9pm", "Our hours are 9am-9pm every day" ] trainer = ListTrainer(chatbot) trainer.train(convers) def speech_reg(): spr =s.Recognizer() spr.pause_threshold =0.8 print('listening you .........................') with s.Microphone() as m: try: audio=spr.listen(m) query= spr.recognize_google(audio) print(query) text.delete(0,END) text.insert(0,query)
def setUp(self): super(ListTrainingTests, self).setUp() self.trainer = ListTrainer( self.chatbot, show_training_progress=False )
except (KeyboardInterrupt, EOFError, SystemExit): print("Erro: Não foi possível obter reposta") #Start root = Tk() vibe = ChatBot(name='Vibe', read_only=False, storage_adapter="chatterbot.storage.SQLStorageAdapter", logic_adapters=["chatterbot.logic.BestMatch"], database_uri="sqlite:///database.sqlite3") trainer = ListTrainer(vibe) data_file = open('Bot.json').read() learn = json.loads(data_file) for topic in learn: for compliment in learn[topic]: trainer.train(compliment) root.title("Vibe") root.geometry("500x500") root.resizable(width=FALSE, height=FALSE) chatWindow = Text(root, bd=1, width="50",
# Create a new instance of a ChatBot bot = ChatBot( 'Default Response Example Bot', storage_adapter='chatterbot.storage.SQLStorageAdapter', logic_adapters=[ { 'import_path': 'chatterbot.logic.BestMatch' }, { 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 'threshold': 0.65, 'default_response': 'I am sorry, but I do not understand.' } ] ) trainer = ListTrainer(bot) # Train the chat bot with a few responses trainer.train([ 'How can I help you?', 'I want to create a chat bot', 'Have you read the documentation?', 'No, I have not', 'This should help get you started: http://chatterbot.rtfd.org/en/latest/quickstart.html' ]) # Get a response for some unexpected input response = bot.get_response('How do I make an omelette?') print(response)
def custom_train(Bot, conversation): from chatterbot.trainers import ListTrainer trainer = ListTrainer(Bot) trainer.train(conversation)
# -*- coding: utf-8 -*- import telepot from chatterbot.trainers import ListTrainer from chatterbot import ChatBot bot = ChatBot("Python") #bot.set_trainer(ListTrainer) trainer = ListTrainer(bot) f = open("treinamento.txt", "r").readlines() trainer.train(f) ## API KEY ADD HERE api = "API_KEY" # Function to search the text received, the return message below def receber(msg): texto = (msg['text']) _id = msg['from']['id'] nome = msg['from']['first_name'] if "Olá" in texto: tele.sendMessage(_id, "Olá, " + str(nome)) elif "Oi" in texto: tele.sendMessage(_id, "Ooi, " + str(nome)) elif "Eae" in texto: tele.sendMessage(_id, "Eaae, " + str(nome)) elif "/start" in texto: tele.sendMessage( _id,
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer ''' This is an example showing how to train a chat bot using the ChatterBot ListTrainer. ''' chatbot = ChatBot('Example Bot') # Start by training our bot with the ChatterBot corpus data trainer = ListTrainer(chatbot) trainer.train([ 'Hello, how are you?', 'I am doing well.', 'That is good to hear.', 'Thank you' ]) # You can train with a second list of data to add response variations trainer.train([ 'Hello, how are you?', 'I am great.', 'That is awesome.', 'Thanks' ]) # Now let's get a response to a greeting