예제 #1
0
def baseTest():
    deepThought = ChatBot("deepThought")
    deepThought.set_trainer(ChatterBotCorpusTrainer)
    # 使用中文语料库训练它
    deepThought.train("chatterbot.corpus.chinese")  # 语料库
    print(deepThought.get_response(u"很高兴认识你"))
    print(deepThought.get_response(u"嗨,最近如何?"))
    print(deepThought.get_response(u"复杂优于晦涩")) #语出 The Zen of Python
    print(deepThought.get_response(u"面对模棱两可,拒绝猜测的诱惑."))
    print(deepThought.get_response(u"你叫什么名字?"))
예제 #2
0
파일: helper.py 프로젝트: xv44586/Chat
class Train(object):
    def __init__(self, chatbot_name='Thought'):
        self.model_name = chatbot_name
        self.model = ChatBot(chatbot_name, trainer='chatterbot.trainers.ChatterBotCorpusTrainer')
        self.model.train('chatterbot.corpus.chinese')
        self.model.train('chatterbot.corpus.english')
        self.model.set_trainer(ListTrainer)

    def train(self, train_data_list):
        assert isinstance(train_data_list, list)
        self.model.train(train_data_list)
예제 #3
0
파일: train.py 프로젝트: xie233/text_mining
def response(a):
    
    chatbot = ChatBot("Ron Obvious")
    chatbot.set_trainer(ChatterBotCorpusTrainer)


    chatbot.train("chatterbot.corpus.english")


    b = str(chatbot.get_response(a))
    return b
예제 #4
0
def testAddTraining():
    from chatterbot.trainers import ListTrainer
    deepThought = ChatBot("Training demo")
    deepThought.set_trainer(ListTrainer)
    deepThought.train([
        u"嗳,渡边君,真喜欢我?",
        u"那还用说?",
        u"那么,可依得我两件事?",
        u"三件也依得",
    ])
    print(deepThought.get_response(u"真喜欢我?")) #不必完全匹配
    print(deepThought.get_response(u"那用说?"))
예제 #5
0
def load_chatbot():
    try:
        chatbot = pickle.load(open(CHATBOT_PKL_PATH, 'rb'))
    except FileNotFoundError:
        print('Chatbot not found at {}, regenerating'.format(CHATBOT_PKL_PATH))
        chatbot = ChatBot("Machine Salesman")

        chatbot.set_trainer(ChatterBotCorpusTrainer)
        chatbot.train('chatterbot.corpus.english')

        # This is taking too long... skip for now
        # chatbot.set_trainer(ListTrainer)
        # for chat in load_chat_histories():
        #     chatbot.train([message.text for message in chat.messages])

        pickle.dump(chatbot, open(CHATBOT_PKL_PATH, 'wb'))
    return chatbot
예제 #6
0
class TalkManager:
	"""
	Class Managing the discussions held by Ariia
	and her training.
	"""

	def __init__(self):
		"""
		Constructor
		"""

		self.ariiaTalker = ChatBot("Ariia")
		self.talk        = None

		self.ariiaTalker.set_trainer(ListTrainer)

		self.ariiaTalker.train([
			"comment vas-tu",
			"ça va bien merci, et toi ?",
			"très bien !",
			"moi ça va.",
			"je suis en pleine forme !",
		])

		self.ariiaTalker.train([
			"comment tu t'appelles",
			"Ariia",
		])

		self.ariiaTalker.train([
			"qui est ton Créateur",
			"un programmeur du dimanche.",
		])

	def getTalk(self, dialog):
		"""
		Specify the speech answering the user's dialog
		
		Parameters :
			dialog - The dialog held by the user
		"""

		self.talk = unicode(self.ariiaTalker.get_response(dialog))
		self.talk = self.talk.encode('utf-8')
		print type(self.talk)
		return self.talk
class ChatterBotCorpusTrainingTestCase(TestCase):
    """
    Test case for training with data from the ChatterBot Corpus.

    Note: This class has a mirror tests/training_tests/
    """

    def setUp(self):
        super(ChatterBotCorpusTrainingTestCase, self).setUp()
        self.chatbot = ChatBot(**settings.CHATTERBOT)
        self.chatbot.set_trainer(ChatterBotCorpusTrainer)

    def tearDown(self):
        super(ChatterBotCorpusTrainingTestCase, self).setUp()
        self.chatbot.storage.drop()

    def test_train_with_english_greeting_corpus(self):
        self.chatbot.train('chatterbot.corpus.english.greetings')

        statement = self.chatbot.storage.find('Hello')

        self.assertIsNotNone(statement)

    def test_train_with_english_greeting_corpus_tags(self):
        self.chatbot.train('chatterbot.corpus.english.greetings')

        statement = self.chatbot.storage.find('Hello')

        self.assertEqual(['greetings'], statement.get_tags())

    def test_train_with_multiple_corpora(self):
        self.chatbot.train(
            'chatterbot.corpus.english.greetings',
            'chatterbot.corpus.english.conversations',
        )

        statement = self.chatbot.storage.find('Hello')
        self.assertIsNotNone(statement)

    def test_train_with_english_corpus(self):
        self.chatbot.train('chatterbot.corpus.english')
        statement = self.chatbot.storage.find('Hello')

        self.assertIsNotNone(statement)
예제 #8
0
class Chatter:
    """ Chatter is the core class involved with the integration with
    ChatterBot. It handles abstracting all interactions with ChatterBot.
    """

    def __init__(self):
        self.chat_bot = ChatBot(
            'JenkiesBot',
            storage_adapter='chatterbot.adapters.storage.JsonDatabaseAdapter',
            logic_adapters=[
                'chatterbot.adapters.logic.ClosestMeaningAdapter',
                'chatterbot.adapters.logic.ClosestMatchAdapter'
            ],
            database='./chat-storage.json')
        # Training
        self.chat_bot.set_trainer(ChatterBotCorpusTrainer)
        self.train_from_corpa()

    def train_from_corpa(self):
        """ Trains the ChatterBot instance."""
        self.chat_bot.train('chatterbot.corpus.english')
        self.chat_bot.train('.corpa')

    def add_axiom(self, statement: str, responses: str):
        """ Adds the user's supplied axiom to the axiom file."""
        def update_axiom_json(json_file_contents: dict) -> dict:
            """ Used as the call back for add_axiom()'s call to update_json_file.
            Describes how we should add a new axiom to our training corpa json
            file.
            """
            json_file_contents['axioms'].append([
                statement
            ] + responses)
            return json_file_contents
        update_json_file('../corpa/training-corpa.json', update_axiom_json)
        # Retraining is required now!
        self.train_from_corpa()

    def get_reply(self, message):
        """ Abstracts away the to our bots method for retrieving a repsonse."""
        return self.chat_bot.get_response(message)
예제 #9
0
from chatterbot import ChatBot
from chatterbot.training.trainers import ListTrainer
import sys
import os
#
# Execution: python chatBot.py Kyle.txt Kyle
#

dfan = ChatBot("DFan")
dfan.set_trainer(ListTrainer)
log = sys.argv[1]     # the name of your chat file (e.g. Kyle.txt)
friend = sys.argv[2]  # first name of friend (matches that in chat file)

script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "Chats/" + log
abs_file_path = os.path.join(script_dir, rel_path)

with open(abs_file_path) as data_file:    
    data = open(abs_file_path, "r")


def createChunk(): # either input or response (indexes 0 or 1 of list fed to train DFan)
    line = '1'  # just initialized to something meaningless that's not empty
    string = ''
    while True:
        line = data.readline().rstrip('\n') # .rstrip is VERY IMPORTANT - avoids appending new line \n to end when parsing
        if line == '':
            break
        group = [string, line]
        string = ''.join(group) # to concatenate mixed ASCII strings with unicode emojis
    return string
예제 #10
0
파일: services.py 프로젝트: zero19/FuzzyBot
def getBot():

    chatterbot= ChatBot(
        "Example ChatterBot",
        database='chatterbot-database',
        logic_adapters=[
        "chatterbot.adapters.logic.ClosestMatchAdapter",
        ],
        read_only=True,
    )
    chatterbot.set_trainer(ListTrainer)

    dataList = [
        ["Hi",
         "Hello",
         "Hello",
         "Hello",
         "Hello",
         "hi",
         "How are you?",
         "I am good.",
         "That is good to hear.",
         "Thank you",
         "You are welcome.",
         ],[
            'Will I need to cancel my current JetBlue Card from American Express,and reapply with Barclaycard',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to re apply'
        ], [
            'Do I need to cancel my current JetBlue Card from American Express,and re apply with Barclaycard',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'How to cancel my current JetBlue Card from American Express,and apply with Barclaycard',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'cancel current JetBlue Card from American Express,and re apply with Barclaycard',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'Should i cancel my Jetblue card from American Express',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ],[
            'What is the procedure to cancel my current Jetblue card from American Express and apply for new one from Barclaycard',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'Please suggest , from where can I cancel my Exisiting jetBlue card from American Express and reapply a card from Barclay card',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'From where can I cancel my Exisiting jetBlue card from American Express and reapply a card from Barclay card',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'Cancel my Exisiting jetBlue card from American Express and reapply a card from Barclay card',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'Help me to  cancel my Exisiting jetBlue card from American Express and reapply a card from Barclay card',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ],[
            'Walk me through steps how can I cancel my Exisiting jetBlue card from American Express and reapply a card from Barclay card',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'I don\'t know from where can i cancel my existing Jetblue card from American Express',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'Do i need to cancel my card from American Express or it would be done automatically',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ],[
            'Should I apply for a new JetBlue card from BarclayCard and cancel my existing JetBlue card from American Express',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'How can I cancel my Exisiting jetBlue card from American Express and reapply a card from Barclay card',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ],[
            'Where can I cancel my Exisiting jetBlue card from American Express and reapply a card from Barclay card',
            'We have automatically transferred your account to your new JetBlue Rewards MasterCard,as long as your account was open,in good standing,and in eligible statsu as of March 18,2016. There is no need to cancel or re apply'
        ], [
            'JetBlue Rewards Master Card Payment Ways?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'Can you advice me how to make payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'Help me with making payment with my JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'help me making  payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'Ways I can make payment on  new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'How can I make payments on my  JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'How to pay bill of new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'How can I make payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ],[
            'How can I make payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'How can I make payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'How can I make payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'How can I make payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'How can I make payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'How can I make payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'How can I make payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ], [
            'How can I make payments on my new JetBlue Rewards Master Card?',
            'On March 21,2016 the balance on your JetBlue Card from American Express was transferred to your new account with BarclayCard.You can now pay your credit card bill by visiting JetBlueMasterCard.com to set up payments directly from a checking or savings account.You can also pay by calling 866-749 or you can mail payments to : Card Services, P.O. 13337, Philadelphia, PA 19101-3337'
        ],
        [
            'The credit limit was exceeded',
            'Your Credit limit has exceeded. Kindly make the payment for your card befor initiation any more transaction on the same card.'
        ], [
            'Card limit has exceeded',
            'Your Credit limit has exceeded. Kindly make the payment for your card befor initiation any more transaction on the same card.'
        ], [
            'This transaction cannot be processsedas you creadit card limit was exceeded',
            'Your Credit limit has exceeded. Kindly make the payment for your card befor initiation any more transaction on the same card.'
        ], [
            'Payment Failure. Credit limit exhausted',
            'Your Credit limit has exceeded. Kindly make the payment for your card befor initiation any more transaction on the same card.'
        ], [
            'I get a Messgae my credit limit has exceeded. What Shoud I do?',
            'Your Credit limit has exceeded. Kindly make the payment for your card befor initiation any more transaction on the same card.'
        ], [
            'While trying to make a payment I see a message my Credit limit has exhusted',
            'Your Credit limit has exceeded. Kindly make the payment for your card befor initiation any more transaction on the same card.'
        ], [
            'I cannot complete my transaction. My credit limit has exceeded.Please help',
            'Your Credit limit has exceeded. Kindly make the payment for your card befor initiation any more transaction on the same card.'
        ], [
            'Transaction is failing with message my credit limit exceeded',
            'Your Credit limit has exceeded. Kindly make the payment for your card befor initiation any more transaction on the same card.'
        ], [
            'The card had expired',
            'Your card has expired.You need to renew your card details.Please follow the below link for renewal process:www.barclayscardus.com'
        ], [
            'My card has expired.Please suggest',
            'Your card has expired.You need to renew your card details.Please follow the below link for renewal process:www.barclayscardus.com'
        ], [
            'Cannot make payment with my card. Its expired.',
            'Your card has expired.You need to renew your card details.Please follow the below link for renewal process:www.barclayscardus.com'
        ], [
            'Card expired!',
            'Your card has expired.You need to renew your card details.Please follow the below link for renewal process:www.barclayscardus.com'
        ], [
            'I cannot carry out any transaction.My card has expired',
            'Your card has expired.You need to renew your card details.Please follow the below link for renewal process:www.barclayscardus.com'
        ], [
            'I am getting  messagemy card has expired',
            'Your card has expired.You need to renew your card details.Please follow the below link for renewal process:www.barclayscardus.com'
        ], [
            'Transaction is failing with messagemy credit has expired.',
            'Your card has expired.You need to renew your card details.Please follow the below link for renewal process:www.barclayscardus.com'
        ], [
            'Credit card expired.How can i renew it?',
            'Your card has expired.You need to renew your card details.Please follow the below link for renewal process:www.barclayscardus.com'
        ], [
            'How can I pay my bills online?',
            'To pay your credit card bill online log in to your account and select MAKE A PAYMENT. You may choose to make a single payment or sign up for automatic repeat monthly payments.'
        ], [
            'Is there a way I can make online billl payment for my card',
            'To pay your credit card bill online log in to your account and select MAKE A PAYMENT. You may choose to make a single payment or sign up for automatic repeat monthly payments.'
        ], [
            'Bill payment Issue. Procedure to pay bills online?',
            'To pay your credit card bill online log in to your account and select MAKE A PAYMENT. You may choose to make a single payment or sign up for automatic repeat monthly payments.'
        ], [
            'Can I make online payments of my bill?',
            'To pay your credit card bill online log in to your account and select MAKE A PAYMENT. You may choose to make a single payment or sign up for automatic repeat monthly payments.'
        ], [
            'How can i pay my card bills through website',
            'To pay your credit card bill online log in to your account and select MAKE A PAYMENT. You may choose to make a single payment or sign up for automatic repeat monthly payments.'
        ], [
            'Is there a online way to make my card bill payment?',
            'To pay your credit card bill online log in to your account and select MAKE A PAYMENT. You may choose to make a single payment or sign up for automatic repeat monthly payments.'
        ], [
            'I want to make a online payment of my bills. Where can i do that?',
            'To pay your credit card bill online log in to your account and select MAKE A PAYMENT. You may choose to make a single payment or sign up for automatic repeat monthly payments.'
        ], [
            'I want to make a online payment of my bills. How can i do that?',
            'To pay your credit card bill online log in to your account and select MAKE A PAYMENT. You may choose to make a single payment or sign up for automatic repeat monthly payments.'
        ], [
            'What variety of options do I have to make a payment?',
            'You can make a payment online through the Barclaycard Mobile App by phone at 302-622-8990  or by mail to either of the following address: Card Services P.O. Box 13337 Philadelphia PA...'
        ], [
            'Ways to make my card payments',
            'You can make a payment online through the Barclaycard Mobile App by phone at 302-622-8990  or by mail to either of the following address: Card Services P.O. Box 13337 Philadelphia PA...'
        ], [
            'Payment Options for bill payment',
            'You can make a payment online  through the Barclaycard Mobile App by phone at 302-622-8990  or by mail to either of the following address: Card Services P.O. Box 13337 Philadelphia PA...'
        ], [
            'What are the available options for bill payment?',
            'You can make a payment online  through the Barclaycard Mobile App by phone at 302-622-8990  or by mail to either of the following address: Card Services P.O. Box 13337 Philadelphia PA...'
        ], [
            'How to make my cards bill payment?',
            'You can make a payment online  through the Barclaycard Mobile App by phone at 302-622-8990  or by mail to either of the following address: Card Services P.O. Box 13337 Philadelphia PA...'
        ], [
            'Can you help me with the my cards bill payment?',
            'You can make a payment online  through the Barclaycard Mobile App by phone at 302-622-8990  or by mail to either of the following address: Card Services P.O. Box 13337 Philadelphia PA...'
        ], [
            'Options to make credit card bill payment',
            'You can make a payment online  through the Barclaycard Mobile App by phone at 302-622-8990  or by mail to either of the following address: Card Services P.O. Box 13337 Philadelphia PA...'
        ], [
            'How can i pay my credit cards bill?',
            'You can make a payment online  through the Barclaycard Mobile App by phone at 302-622-8990  or by mail to either of the following address: Card Services P.O. Box 13337 Philadelphia PA...'
        ], [
            'How long does it take to process an online payment?',
            'Want to know when your online mobile or phone payment will be processed and when your available credit will be updated? Find out fast with this handy link.'
        ], [
            'Online payment processing time ?',
            'Want to know when your online mobile or phone payment will be processed and when your available credit will be updated? Find out fast with this handy link.'
        ], [
            'What is the time taken to process an online payment?',
            'Want to know when your online mobile or phone payment will be processed and when your available credit will be updated? Find out fast with this handy link.'
        ], [
            'How long will I have to wait to see online payment status ?',
            'Want to know when your online mobile or phone payment will be processed and when your available credit will be updated? Find out fast with this handy link.'
        ], [
            'Time it takes for process a online payment?',
            'Want to know when your online mobile or phone payment will be processed and when your available credit will be updated? Find out fast with this handy link.'
        ], [
            'Processsing time for a bill payment made online?',
            'Want to know when your online mobile or phone payment will be processed and when your available credit will be updated? Find out fast with this handy link.'
        ], [
            'Can you tell me how long it take to process a online payment?',
            'Want to know when your online mobile or phone payment will be processed and when your available credit will be updated? Find out fast with this handy link.'
        ], [
            'Time require to process a online bill payment?',
            'Want to know when your online mobile or phone payment will be processed and when your available credit will be updated? Find out fast with this handy link.'
        ], [
            'What is my minimum payment amount?',
            'Your minimum payment is the payment thats required each billing period to keep your Credit Card account in good standing. Your monthly billing statement will tell you the minimum payment amount...'
        ], [
            'What is the minimum amount for my card pyment',
            'Your minimum payment is the payment thats required each billing period to keep your Credit Card account in good standing. Your monthly billing statement will tell you the minimum payment amount...'
        ], [
            'The minimum amount that needs to be paid by me for this card',
            'Your minimum payment is the payment thats required each billing period to keep your Credit Card account in good standing. Your monthly billing statement will tell you the minimum payment amount...'
        ], [
            'Minimum transaction value for my card payment',
            'Your minimum payment is the payment thats required each billing period to keep your Credit Card account in good standing. Your monthly billing statement will tell you the minimum payment amount...'
        ], [
            'What is the minimum payment amount I can pay for my card bill?',
            'Your minimum payment is the payment thats required each billing period to keep your Credit Card account in good standing. Your monthly billing statement will tell you the minimum payment amount...'
        ], [
            'Tell mewhat is the minimum payment amount for my card?',
            'Your minimum payment is the payment thats required each billing period to keep your Credit Card account in good standing. Your monthly billing statement will tell you the minimum payment amount...'
        ], [
            'What is the Minimum transaction value for my cards bill payment?',
            'Your minimum payment is the payment thats required each billing period to keep your Credit Card account in good standing. Your monthly billing statement will tell you the minimum payment amount...'
        ], [
            'What is the lower limit for paying my cards bill payment?',
            'Your minimum payment is the payment thats required each billing period to keep your Credit Card account in good standing. Your monthly billing statement will tell you the minimum payment amount...'
        ], [
            'How often can I change my due date?',
            'You can change your payment due date once every 120 days.'
        ], [
            'Can I change my due date for payment',
            'You can change your payment due date once every 120 days.'
        ], [
            'Is there any limitation on number of times I can change my payment due date?',
            'You can change your payment due date once every 120 days.'
        ], [
            'Maximum times I can change my due dates for payment',
            'You can change your payment due date once every 120 days.'
        ], [
            'How many times I can change my due date for bill payment?',
            'You can change your payment due date once every 120 days.'
        ], [
            'I want to change my payment due date?How many times I am allowed to do this?',
            'You can change your payment due date once every 120 days.'
        ], [
            'Is there a limit to number of times i Can change my payment due date?',
            'You can change your payment due date once every 120 days.'
        ], [
            'Can you tell me how many times is it allowed to change the payment due date?',
            'You can change your payment due date once every 120 days.'
        ], [
            'How can I change my payment due date?',
            'You can change your payment due date by clicking on Change Payment Due Date under Account Settings. Note: Changing your payment due date will not affect any payments currently due. Please continue to'
        ], [
            'I want to change my payment due date?Can you help?',
            'You can change your payment due date by clicking on Change Payment Due Date under Account Settings. Note: Changing your payment due date will not affect any payments currently due. Please continue to'
        ], [
            'Whats the procedure to change the payment due date?',
            'You can change your payment due date by clicking on Change Payment Due Date under Account Settings. Note: Changing your payment due date will not affect any payments currently due. Please continue to'
        ], [
            'Way to change payment due date?',
            'You can change your payment due date by clicking on Change Payment Due Date under Account Settings. Note: Changing your payment due date will not affect any payments currently due. Please continue to'
        ], [
            'I want to change my payment due date? How can i do this?',
            'You can change your payment due date by clicking on Change Payment Due Date under Account Settings. Note: Changing your payment due date will not affect any payments currently due. Please continue to'
        ], [
            'Is there a way I can change my payment due date?',
            'You can change your payment due date by clicking on Change Payment Due Date under Account Settings. Note: Changing your payment due date will not affect any payments currently due. Please continue to'
        ], [
            'Help with the process of changing the payment due date',
            'You can change your payment due date by clicking on Change Payment Due Date under Account Settings. Note: Changing your payment due date will not affect any payments currently due. Please continue to'
        ], [
            'Guide me through the process of changing the payment due date?',
            'You can change your payment due date by clicking on Change Payment Due Date under Account Settings. Note: Changing your payment due date will not affect any payments currently due. Please continue to'
        ], [
            'What if I need to make a payment and the website is down or unavailable?',
            'If you need to make a payment during a time when our website and/or Barclaycard Mobile App are down please call 302-622-8990 to make a payment.'
        ], [
            'I want to make a payment but seems website is not working?',
            'If you need to make a payment during a time when our website and/or Barclaycard Mobile App are down please call 302-622-8990 to make a payment.'
        ], [
            'Website is down I need to make a payment please help?',
            'If you need to make a payment during a time when our website and/or Barclaycard Mobile App are down please call 302-622-8990 to make a payment.'
        ], [
            'Is there a way I a can make payment if website is not unavailable or down?',
            'If you need to make a payment during a time when our website and/or Barclaycard Mobile App are down please call 302-622-8990 to make a payment.'
        ], [
            'I am trying to make my cards paymentbut i can see the website is down. Please help',
            'If you need to make a payment during a time when our website and/or Barclaycard Mobile App are down please call 302-622-8990 to make a payment.'
        ], [
            'I am unable to make my bill payment.Site is not working.',
            'If you need to make a payment during a time when our website and/or Barclaycard Mobile App are down please call 302-622-8990 to make a payment.'
        ], [
            'I am not able to make  payments for my bill. Site is unavailable?',
            'If you need to make a payment during a time when our website and/or Barclaycard Mobile App are down please call 302-622-8990 to make a payment.'
        ], [
            'Your site is not working. How can I pay my bills?',
            'If you need to make a payment during a time when our website and/or Barclaycard Mobile App are down please call 302-622-8990 to make a payment.'
        ], [
            'Can I use multiple bank accounts to make payments?',
            'Yes. You can add multiple bank accounts to use to make payments on your account.'
        ], [
            'Can I make paymens using multiple bank account?',
            'Yes. You can add multiple bank accounts to use to make payments on your account.'
        ], [
            'Is it possible to make payment using different bank accounts',
            'Yes. You can add multiple bank accounts to use to make payments on your account.'
        ], [
            'How can I use multiple bank accounts to make payments?',
            'Yes. You can add multiple bank accounts to use to make payments on your account.'
        ], [
            'I want to pay my bills using my two different bank acounts. Is there a way to do it?',
            'Yes. You can add multiple bank accounts to use to make payments on your account.'
        ], [
            'Can i use my different bank accounts to pay bill for my card?',
            'Yes. You can add multiple bank accounts to use to make payments on your account.'
        ], [
            'Is it permissible to pay bills using multiple bank accounts?',
            'Yes. You can add multiple bank accounts to use to make payments on your account.'
        ], [
            'Is it possible to make payment using different bank accounts on your site?',
            'Yes. You can add multiple bank accounts to use to make payments on your account.'
        ],
        [
            'What is my balance',
            'Your balance is {balance}',
        ]
        ,
        [
            'Can you tell me my balance',
            'Your balance is {balance}',
        ]
        ,
        [
            'Please tell me my account balance',
            'Your balance is {balance}',
        ]
        ,
        [
            'What is my account balance',
            'Your balance is {balance}',
        ],
        [
            'What is my account balance',
            'Your balance is {balance}',
        ],
        [
            'What is my balance',
            'Your balance is {balance}',
        ],
        [
            'Tell me my balance',
            'Your balance is {balance}',
        ]
    ]

    for data in dataList:
        chatterbot.train(data)
    return chatterbot
예제 #11
0
from chatterbot.trainers import ListTrainer  #method to train chatbot
from chatterbot import ChatBot  #import chatbot
import os
from os import listdir

bot = ChatBot('test')  #create the chatbot
bot.set_trainer(ListTrainer)  #set the trainer

chats = open(
    r"C:\Users\I353296\Documents\git VS\python\Python\NLP\1\chatbot\chats.txt",
    "r").readlines()  #read the file
bot.train(chats)  #TRAIN THE BOT
"""
for file in listdir('files'):			#when there are multiple files to read from
	chats=open('files/' , 'r').readlines()
	bot.train(chats)		#TRAIN THE BOT

while True:
	request=input('You: ')
	response=bot.get_response(request)
	print('Bot: ' +response)
"""

#i=True
#while i==True:
#print('Bot: ' +str(bot.get_response(input('You: '))))		#on line statement
#i=False
request = input()
if request != '':
    response = bot.get_response(request)
    print('Bot: ' + str(response))
예제 #12
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os

bot = ChatBot('Bot')
bot.set_trainer(ListTrainer)

for files in os.listdir(
        'C:/Users/Dell\Documents/GitHub/chatterbot-corpus/chatterbot_corpus/data/english/'
):
    data = open(
        'C:/Users/Dell\Documents/GitHub/chatterbot-corpus/chatterbot_corpus/data/english/'
        + files, 'r').readlines()
    bot.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
예제 #13
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os  # since we import os directory

bot = ChatBot('REady For U AI')  #Assign name to chatbot
bot.set_trainer(ListTrainer)  # to train my ChatBot

for files in os.listdir(
        'C:/Users/user\Downloads/chatterbot-corpus-master/chatterbot-corpus-master/chatterbot_corpus/data/english/'
):  #load my files from the system
    data = open(
        'C:/Users/user\Downloads/chatterbot-corpus-master/chatterbot-corpus-master/chatterbot_corpus/data/english/'
        + files, 'r').readlines(
        )  # for opening the data and to read the data from files
    bot.train(data)  #train the bot using data

while True:  # when training is done we input the message
    message = input('You:')
    if message.strip() != 'Bye':
        reply = bot.get_response(message)
        print('ChatBot:', reply)
    if message.strip() == 'Bye':
        print('ChatBot: Bye')
        break
예제 #14
0
import sys
sys.path.insert(0,'../src')
import text_speech
# Uncomment the following line to enable verbose logging
# import logging
# logging.basicConfig(level=logging.INFO)

# Create a new instance of a ChatBot
bot = ChatBot(
    "Terminal",
    storage_adapter="chatterbot.storage.SQLStorageAdapter",
    input_adapter="chatterbot.input.TerminalAdapter",
    output_adapter="chatterbot.output.TerminalAdapter"
)
bot.set_trainer(ChatterBotCorpusTrainer)
# bot.train("chatterbot.corpus.english")

CONVERSATION_ID = bot.storage.create_conversation()

def get_feedback():
    from chatterbot.utils import input_function

    text = input_function()

    if 'yes' in text.lower():
        return False
    elif 'no' in text.lower():
        return True
    else:
        print('Please type either "Yes" or "No"')
예제 #15
0
#-*- coding: utf-8 -*-
import os
from chatterbot.trainers import ListTrainer  # Importa o metodo para treinar o Bot com arquios de texto
from chatterbot import ChatBot

bot = ChatBot(
    'Martha'
)  # Define o "Nome" do Bot e faz com que a variavel "bot" seja equivalente a ele
bot.set_trainer(
    ListTrainer
)  # Faz com que o programa importe listas externas para treinar as suas repostas

for arq in os.listdir('arq'):
    chats = open('arq/' + arq, 'r').readlines(
    )  # Ler o conteudo das listas de frases que estão na pasta "arq"
    bot.train(
        chats
    )  # Treinar as respostas do Bot de acordo com o conteudo das listas

while True:  # Loop para que sempre que o Bot responder algo seja possivel inserir outra frase
    frase = input(
        'Você: '
    )  # Por meio desta variavel o programa ira armazenar o que o usuario digitou
    resp = bot.get_response(
        frase
    )  # Ele irá analizar sua frase com o que disponivel nas listas e irá encontrar uma resposta
    print(
        'Robô: ' + str(resp) + '\n'
    )  # Ele irá mostrar a resposta na tela(podendo ser o terminal, ou caso esteja usando uma API pode ser um aplicativo de menssagens)
예제 #16
0
class ModelChatBot:
	#####################################################################################
	# __bot = ChatBot('PLM BOT', 														#
	# 				#read_only=True,													#
	# 				logic_adapters=[													#
	# 					"chatterbot.logic.BestMatch",									#
	# 					"chatterbot.logic.MathematicalEvaluation",						#
	# 					"chatterbot.logic.LowConfidenceAdapter"							#
	# 				],																	#
	# 				input_adapter='chatterbot.input.VariableInputTypeAdapter',			#
	# 				output_adapter='chatterbot.output.OutputAdapter'					#
	#																					#
	# 	)																				#
	#####################################################################################
	__bot = ChatBot('PLM BOT', 
					#read_only=True,
					filters=["chatterbot.filters.RepetitiveResponseFilter"],
					preprocessors=[
									'chatterbot.preprocessors.clean_whitespace',
									'chatterbot.preprocessors.unescape_html',
									'chatterbot.preprocessors.convert_to_ascii'
								],
					logic_adapters=[
						{
							"import_path": "chatterbot.logic.BestMatch",
							"statement_comparison_function": "chatterbot.comparisons.levenshtein_distance",
							"response_selection_method": "chatterbot.response_selection.get_first_response"
						},
						{
							"import_path": "chatterbot.logic.MathematicalEvaluation",
						},
						{
							'import_path': 'chatterbot.logic.SpecificResponseAdapter',
							'input_text': 'Help me!',
							'output_text': 'Ok, here is a link: http://chatterbot.rtfd.org'
						},
						{
							'import_path': 'chatterbot.logic.LowConfidenceAdapter',
							'threshold': 0.65,
							'default_response': 'I am sorry, but I do not understand.'
						}

					],
					input_adapter='chatterbot.input.VariableInputTypeAdapter',
					output_adapter='chatterbot.output.OutputAdapter'

		)
	__instance = None

	def __init__(self, name):
		print("Init Method is called")

		self.__bot = ChatBot('PLM BOT', 
					#read_only=True,
					filters=["chatterbot.filters.RepetitiveResponseFilter"],
					logic_adapters=[
						{
							"import_path": "chatterbot.logic.BestMatch",
							"statement_comparison_function": "chatterbot.comparisons.levenshtein_distance",
							"response_selection_method": "chatterbot.response_selection.get_first_response"
						},
						{
							"import_path": "chatterbot.logic.MathematicalEvaluation",
						},
						{
							'import_path': 'chatterbot.logic.SpecificResponseAdapter',
							'input_text': 'Help me!',
							'output_text': 'Ok, here is a link: https://www.tcs.com'
						},
						{
							'import_path': 'chatterbot.logic.LowConfidenceAdapter',
							'threshold': 0.65,
							'default_response': 'I am sorry, but I do not understand.'
						}
						

					],
					input_adapter='chatterbot.input.VariableInputTypeAdapter',
					output_adapter='chatterbot.output.OutputAdapter'

		)
		#self.__bot.set_trainer(ListTrainer)
		#self.__bot.train(conversation)
		self.__bot.set_trainer(ChatterBotCorpusTrainer)
		#Now train with corporus
		# Train based on the english corpus
		#self.__bot.train("chatterbot.corpus.english")
		# Train based on english greetings corpus
		self.__bot.train("chatterbot.corpus.english.greetings")
		# Train based on the english conversations corpus
		#self.__bot.train("chatterbot.corpus.english.conversations")
		# Now we can export the data to a file
		#self.__bot.trainer.export_for_training('./chat_op_sample.json')
		#Train on custom dataset which is also a corpus
		self.__bot.train(
			"./train_data/enovia_train.yml",
			"./train_data/bot_profile.yml",
		)



	@classmethod    
	def generate_response(self,request):
		return self.__bot.get_response(request)
		pass
예제 #17
0
            'import path':
            'chatterbot.logic.LowConfidenceAdapter',
            'threshold':
            0.51,
            'default_response':
            'Disculpa no entendi bien, ¿Puedes ser más específic@?'
        },
        {
            'import_path':
            'chatterbot.logic.SpecificResponseAdapter',
            'input_text':
            '¿Quiero saber si quedan cupos?',
            'output_text':
            'Puedes averigualo en la pagina de la Secretaria de Educación: https://www.educacionbogota.edu.co/portal_institucional/'
        },
    ],
    preprocessors=['chatterbot.preprocessors.clean_whitespace'],
    read_only=True,
)
DEFAULT_SESSION_ID = chatbot.default_session.id

from chatterbot.trainers import chatterbotCorpusTrainer

chatbot.set_trainer(chatterbotCorpusTrainer)
chatbot.train("conchita_ES.yml")

while True:
    input_statement = chatbot.input_process_input_statement()
    statement, response = chatbot.generate_response(input_statement,
                                                    DEFAULT_SESSION_ID)
    print("\n%s\n\n" % response)
예제 #18
0
파일: run.py 프로젝트: mcraphael/RHA
file.write('bot : Hi There! I am a medical chatbot. You can begin conversation by typing in a message and pressing enter.\n')
file.close()

app = Flask(__name__)
                                         
                                              
english_bot = ChatBot('Bot',
             storage_adapter='chatterbot.storage.SQLStorageAdapter',
             logic_adapters=[
   {
       'import_path': 'chatterbot.logic.BestMatch'
   },
   
],
trainer='chatterbot.trainers.ListTrainer')
english_bot.set_trainer(ListTrainer)

@app.route("/")
def home():
    return render_template("index.html")
                                                                                                                                                                    
@app.route("/about")
def about():
    return render_template("about.html")


@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
    response = str(english_bot.get_response(userText))
예제 #19
0
#-*- coding=utf-8 -*-
"""
聊天机器人
"""

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

deepThought = ChatBot("deepThought")
deepThought.set_trainer(ChatterBotCorpusTrainer)
# 使用中文语料库训练它
deepThought.train("chatterbot.corpus.chinese")  # 语料库
예제 #20
0
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot

kronus = ChatBot('Kronus')
playing = True

conversa = [
    'Oi', 'Olá', 'Tudo bem ?', 'Tudo ótimo', 'Quem ganhou as eleições ? ',
    'UH É BOLSONARO, UH É BOLSONARO', 'Posso come sua esposa ?',
    'Claro meu consagrado', 'Você gosta de programar?',
    'Sim, eu programo em Python', 'Qual é o seu nome ?', 'Meu nome é Kronus',
    'Quem é você ?', 'Sou uma IA criado pelo grande sábio Alexandre Beck',
    'Vou muito bem e você ?', 'Estou ótimo'
]

kronus.set_trainer(ListTrainer)
kronus.train(conversa)

user1 = input('Coloque um nome: ')
while playing:
    pergunta = input(user1 + ': ')
    resposta = kronus.get_response(pergunta)
    if float(resposta.confidence) > 0.5:
        print('Kronus: ', resposta)
    else:
        print(
            'Kronus: Não sei do que você esta falando, meu consagrado!, continue conversando comigo para eu aprender'
        )

    if pergunta == 'sair'.startswith('s'):
        break
예제 #21
0
파일: app.py 프로젝트: cyFolder/Python
            'import_path': 'chatterbot.logic.BestMatch',
            "statement_comparison_function": "chatterbot.comparisons.levenshtein_distance",
            "response_selection_method": "chatterbot.response_selection.get_first_response"
        },
        {
            'import_path': 'chatterbot.logic.LowConfidenceAdapter',
            'threshold': 0.65,
            'default_response': 'I am sorry, but I do not understand.'
        } 
    ],
    trainer='chatterbot.trainers.ListTrainer'
	)


#Set the trainer
GreetingBot.set_trainer(ListTrainer)
QuestionaireBot.set_trainer(ListTrainer)
AdvisorBot.set_trainer(ListTrainer)

#Constant
Counter = 0;
Score = 0

"""
for _file in os.listdir('Diabetes Dialog'):
	#Read Training Data
	Greeting = open('Diabetes Dialog/Greeting.txt', 'r' ).readlines()	
	Questionaire = open('Diabetes Dialog/Questionaire.txt', 'r' ).readlines()
	Advises = open('Diabetes Dialog/Advises.txt', 'r' ).readlines()
	
	#Train bot
예제 #22
0
vcal = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:{}
DTSTAMP:20180104T111016Z
DTSTART:{}
DTEND:{}
SUMMARY:{}
END:VEVENT
END:VCALENDAR
"""

# deep thought
deepThought = ChatBot("Training demo")
deepThought.set_trainer(ListTrainer)
deepThought.train("chatterbot.corpus.chinese")

# time NLP
tn = TimeNormalizer()
now = datetime.datetime.now()
now = now.strftime("%Y-%m-%d %H:%M:%S")

uuid = 0

username = '******'
password = '******'

icx = iCloudConnector(username, password)

cal = icx.get_named_calendar('MyCalendar')
예제 #23
0
Do you have a girlfriend?
No one has trained a girl for me. Hopefully my creators will, soon!
Do you have a girl?
No one has trained a girl for me. Hopefully my creators will, soon!
How many languages do you speak?
I speak English, a little French and a lot of binary.
You are bad.
I am sorry! I've only been trained one night, you see.
You are helpful!
Thank you, it's my pleasure."""


# Create your views here.
question_list = []
chatbot = ChatBot("Echo")
chatbot.set_trainer(ChatterBotCorpusTrainer)
chatbot.train("chatterbot.corpus.english")
chatbot.train("chatterbot.corpus.english.greetings")
chatbot.train("chatterbot.corpus.english.conversations")

chatbot.set_trainer(ListTrainer)
data_list = text_blah.split('\n')
chatbot.train(data_list)

current_dir = os.getcwd() + '/echoApp'  #From the location of 'manage.py'
print current_dir

qa = question_similarity.QASimilarityDoc2Vec(model_name=current_dir + '/intuit_temp.doc2vec',filename={'question':current_dir +'/intuit_questions.txt', 'answer':current_dir +'/intuit_answers.txt'})
q_lda = ldamodel.LdaModel.load(current_dir +'/q_LDA_stop_20')
dictionary = Dictionary.load(current_dir +'/q_dictionary')
corpus = corpora.MmCorpus(current_dir + '/corpus')
예제 #24
0
import json
import eventlet

from flask import Flask, render_template, copy_current_request_context
from flask_socketio import SocketIO, send, emit

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

app = Flask(__name__)
socketio = SocketIO(app)

Joe = ChatBot("Joe Bot")
Joe.set_trainer(ChatterBotCorpusTrainer)

pool = eventlet.GreenPool()
pile = eventlet.GreenPile(pool)


@app.route("/")
def index():
    return render_template("index.html")


@socketio.on('my event')
def handle_my_custom_event(data):
    data = json.loads(str(data).replace("\'", "\""))
    emit('chat', data)

    @copy_current_request_context
    def train_bot():
예제 #25
0
from chatterbot.trainers import ChatterBotCorpusTrainer
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot

chatbot = ChatBot('Will Li')
chatbot.set_trainer(ChatterBotCorpusTrainer)
chatbot.train("chatterbot.corpus.english")
chatbot.set_trainer(ListTrainer)

fh = open('sample_data.txt')
lines = [line.rstrip('\n') for line in fh]
fh.close()

for x in range(0, 5):
    chatbot.train(lines[(3 * x):(3 * x + 1)])

print(chatbot.get_response('Where can I find my test'))
예제 #26
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

#注意chatterbot,中文聊天机器人的场景下一定要用python3.X,用python2.7会有编码问题。

#手动设置一些语料
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

Chinese_bot = ChatBot("Training demo")
Chinese_bot.set_trainer(ListTrainer)
Chinese_bot.train([
    '你好',
    '你好',
    '有什么能帮你的?',
    '想买数据科学的课程',
    '具体是数据科学哪块呢?'
    '机器学习',
])

# 测试一下
question = '你好'
print(question)
response = Chinese_bot.get_response(question)
print(response)

print("\n")

question = '请问哪里能买数据科学的课程'
print(question)
response = Chinese_bot.get_response(question)
예제 #27
0
# -*- coding: utf-8 -*-

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer


chatbot = ChatBot("Jiraya")
chatbot.set_trainer(ListTrainer)

conversation = [
    "Hello",
    "Hi there!",
    "Hi there!",
    "Hello",
    "How are you doing?",
    "I'm doing great.",
    "Cool!",
    "^_^"
    "That is good to hear",
    "Thank you.",
    "You're welcome.",
]

chatbot.set_trainer(ListTrainer)
chatbot.train(conversation)

response = chatbot.get_response("Hello")
print(response)

response = chatbot.get_response("I am hungry.")
print(response)
예제 #28
0
#coding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

deepThought = ChatBot("deepThought")
deepThought.set_trainer(ChatterBotCorpusTrainer)
# 使用中文语料库训练它
deepThought.train("chatterbot.corpus.chinese")  # 语料库
print(deepThought.get_response(u"很高兴认识你"))
print(deepThought.get_response(u"嗨,最近如何?"))
print(deepThought.get_response(u"复杂优于晦涩")) #语出 The Zen of Python
print(deepThought.get_response(u"面对模棱两可,拒绝猜测的诱惑."))
print(deepThought.get_response(u"你叫什么名字?"))
예제 #29
0
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

app = Flask(__name__)

english_bot = ChatBot("Chatterbot",
                      storage_adapter="chatterbot.storage.SQLStorageAdapter")

english_bot.set_trainer(ChatterBotCorpusTrainer)
english_bot.train("chatterbot.json")


@app.route("/")
def home():
    return render_template("index.html")


@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
    return str(english_bot.get_response(userText))


if __name__ == "__main__":
    app.run()
예제 #30
0
from django.views.generic import View
from django.http import JsonResponse
from chatterbot import ChatBot
from chatterbot.training.trainers import ListTrainer


chatterbot = ChatBot(
    'Example ChatterBot',
    input_adapter='chatterbot.adapters.input.VariableInputTypeAdapter',
    output_adapter='chatterbot.adapters.output.OutputFormatAdapter',
    output_format='json'
)

chatterbot.set_trainer(ListTrainer)

chatterbot.train([
    "Hi",
    "Hello",
    "How are you?",
    "I am good.",
    "That is good to hear.",
    "Thank you",
    "You are welcome.",
])


class ChatterBotView(View):

    def get(self, request, *args, **kwargs):
        data = {
            'detail': 'You should make a POST request to this endpoint.'
예제 #31
0
class Simple_bot:
    """
    Constructor for the chatbot. Sets up the relevant adapters and loads up data managers to 
    handle the knowledge banks. 
    """
    def __init__(self, ratio, testing=True):
        self.__tr = float(ratio)
        self.__q_bank = DataManager('questions')
        self.__k_bank = DataManager('knowledge')

        if testing:
            self.__chatbot = ChatBot(
                "UKDA Bot",
                storage_adapter="chatterbot.storage.JsonFileStorageAdapter",
                logic_adapters=[
                    #                    "chatterbot.logic.MathematicalEvaluation",
                    #                    "chatterbot.logic.TimeLogicAdapter",
                    "chatterbot.logic.BestMatch"
                ],
                input_adapter="chatterbot.input.VariableInputTypeAdapter",
                silence_performance_warning=True,
                output_adapter="chatterbot.output.OutputAdapter",
                database="../data/database.db",
            )

        else:
            self.__chatbot = ChatBot(
                "UKDA Bot",
                storage_adapter="chatterbot.storage.JsonFileStorageAdapter",
                logic_adapters=[
                    #                    "chatterbot.logic.MathematicalEvaluation",
                    #                    "chatterbot.logic.TimeLogicAdapter",
                    "chatterbot.logic.BestMatch"
                ],
                input_adapter="chatterbot.input.TerminalAdapter",
                silence_performance_warning=True,
                output_adapter="chatterbot.output.TerminalAdapter",
                database="../data/database.db",
            )
        self.__convos = self.load_conversations(self.__q_bank, self.__k_bank)
        self.__chatbot.set_trainer(ListTrainer)
        self.train()
        print("Chatbot created")

    def load_conversations(self, q, k):
        """
        Loads conversations from the knowledge base using a CSV file which has a 
        question and an answer.

        Args:
            q (Data_manager): This is the datamanager for the questions. 
            k (Data_manager): This is the datamanager for the knowledge base. 
        """
        path = "../data/qa.csv"
        conversations = []
        csvfile = open(path, 'r')
        for line in csvfile:
            stripped = line.strip("\n")
            value = stripped.split(",")
            conversation = [q.get_page(value[0]), k.get_page(value[1])]
            conversations.append(conversation)
        csvfile.close()
        return conversations

    def train(self):
        """
        Trains the chatbot on the questions and answers loaded from it's CSV file. 
        By changing the conversations to a class variable, the program has sped up 
        by factor of 10. 
        """
        value = int(len(self.__convos) * self.__tr)
        conversations = self.__convos[:value]
        i = 0
        t0 = time()
        for c in range(1):
            for conversation in conversations:
                i += 1
                try:
                    self.__chatbot.train(conversation)
                except KeyError:
                    print("error has occurred on line ", i, "in qa.csv")
                # print(conversation[1])
        print("trained on", i, "examples in", round(time() - t0, 3), "s")

    def __build_corpus(self, conversations):
        corpus = []
        for c in conversations:
            corpus.append(c[0])
        return corpus

    def test(self):
        value = int(len(self.__convos) * self.__tr)
        conversations = self.__convos[value:]
        corpus = self.__build_corpus(conversations)
        n_features = 2000
        vectorizer = CountVectorizer(min_df=1)
        X = vectorizer.fit_transform(corpus)
        print(X)

    def test2(self):
        value = int(len(self.__convos) * self.__tr)
        conversations = self.__convos[value:]
        tp = 0
        t0 = time()
        i = 0
        correct = 0
        for c in conversations:
            i += 1
            question = c[0]
            answer = c[1]
            guess = str(self.__chatbot.get_response(question))
            fname = '../data/output/' + str(i) + '.txt'
            f = open(fname, 'w')
            f.write(guess + "/n" + answer)
            f.close()
            if guess == answer:
                correct += 1

        print("tested on", len(conversations), "examples in",
              round(time() - t0, 3), "s")
        print("Accuracy: ", round(tp / len(conversations) * 100, 2), "%")
        print("True positives: ", tp)

    def chat(self):
        """
        Runs the chatbot in terminal mode.
        """
        while True:
            try:
                self.__bot_input = self.__chatbot.get_response(None)
            except (KeyboardInterrupt, EOFError, SystemExit):
                break
            print(
                "================================================================="
            )
예제 #32
0
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
import telepot
import os
import tweepy
import sys
from textblob import TextBlob
from googlesearch import search
from settings import TWITTER
import logging

logging.basicConfig(level=logging.INFO)
TelBot = telepot.Bot("587254001:AAFmCdn_YI8s79td4t48WFeXSXmLtpJFP2c")

Bot = ChatBot('Bast')
Bot.set_trainer(ListTrainer)
for arq in os.listdir('Bast_arq'):
    print("AAA")
    chats = open('Bast_arq/' + arq, 'r').readlines()
    Bot.train(chats)

filterQuest = [
    'como', 'porque', 'por', 'que', ',', '.', '?', '!', 'meu', 'esta'
]
filterBad = ['foder', 'vadia', 'negro', 'cu', 'arrombado', 'vadio', 'pênis']
notresponse = "Desculpe, ainda não há uma resposta"
print("\nSTART\n")


def twitter(quest, msg_id):
    TwiBot = ChatBot(
#-*- coding: utf-8 -*-
#Chatbot
import os
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot

bot = ChatBot('Robô do Vitão')

bot.set_trainer(ListTrainer)  # aqui eu estou definindo o metodo de trainamento

for arq in os.listdir('arq'):
    chats = open('arq/' + arq, 'r').readlines()
    bot.train(chats)

while True:
    request = input('Você: ')
    response = bot.get_response(request)
    print('Bot: ', response)
예제 #34
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os

intello = ChatBot('intl')
intello.set_trainer(ListTrainer)

for files in os.listdir(
        'C:/Users/User/Desktop/py Projects/datasets chatbott/chatterbot-corpus/chatterbot_corpus/data/english/'
):
    f = open(
        'C:/Users/User/Desktop/py Projects/datasets chatbott/chatterbot-corpus/chatterbot_corpus/data/english/'
        + files, 'r').readlines()

    intello.train(f)
while 1:
    username = input("Enter Your Name: \t")
    message = input(username + ': ')
    if message.strip() != 'Bye' or message.strip() != "See You":
        reply = intello.get_response(message)
        print("Intello :", reply)
    if message.strip() == 'Bye' or message.strip() == "See You":
        print("Intello : Bye " + username)
        break
예제 #35
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os

bot = ChatBot('Evans')
bot.set_trainer(ListTrainer)  #to train the bot

#first time running you will need to uncomment bellow

# for files in os.listdir('C:/Users/admin/chatbot/conversations'):
# 	data = open('C:/Users/admin/chatbot/conversations/' + files ,'r').readlines()
# 	bot.train(data)

#comments are to prevent it from keeping on training when running

while True:
    message = input('You: ')
    if message.strip() != 'Bye':
        reply = bot.get_response(message)
        print('ChatBot: ', reply)
    else:
        print('ChatBot: Bye')
        break
예제 #36
0
from chatterbot.training.trainers import ListTrainer


# Create a new instance of a ChatBot
bot = ChatBot("Terminal",
    storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
    logic_adapters=[
        "chatterbot.adapters.logic.MathematicalEvaluation",
        "chatterbot.adapters.logic.TimeLogicAdapter",
        "chatterbot.adapters.logic.ClosestMatchAdapter"
    ],
    input_adapter="chatterbot.adapters.input.TerminalAdapter",
    output_adapter="chatterbot.adapters.output.TerminalAdapter",
    database="../database.db"
)
bot.set_trainer(ListTrainer)
bot.train([
    "hello",
    "hi",
    "how are you",
    "i am fine",
    "that is good to hear",
    "thank you",
    "you are welcome",
    "sorry",
    "its okay", 
    "what is your name",
    "my name is HURO",
])
print("Type something to begin...")
예제 #37
0
파일: main.py 프로젝트: tekkay/Hawk
import speech_recognition as sr
import pyttsx3

speaker = pyttsx3.init()

voices = speaker.getProperty('voices')

for voice in voices:
    if voice.name == 'brazil':
        speaker.setProperty('voice', voice.id)

bot = ChatBot('Hawk', read_only=True)


"""
bot.set_trainer(ListTrainer)

for _file in os.listdir('Chats'):
    lines = open('Chats/' + _file, 'r').readlines()
    
    bot.train(lines) """

def speak(text):
    speaker.say(text)
    speaker.runAndWait()

    
from pocketsphinx import LiveSpeech

speech = LiveSpeech(
예제 #38
0
파일: app.py 프로젝트: dlpazs/JC
def chat_bot():

	df = pd.read_csv('./new.csv', encoding = "ISO-8859-1")
	count_vect = CountVectorizer()
	tfidf_transformer = TfidfTransformer()

	text_clf = Pipeline([('vect', CountVectorizer()),
                      ('tfidf', TfidfTransformer()),
                      ('clf', SGDClassifier(loss='hinge', penalty='l2',
                                            alpha=1e-3, random_state=42,
                                            max_iter=5, tol=None)),])

	x2 = df['TEXT']

	yEXT = df['cEXT']  
	yNEU = df['cNEU']
	yAGR = df['cAGR']
	yCON = df['cCON']
	yOPN = df['cOPN']

	#
	X_train, X_test, y_train, y_test = train_test_split(x2, yEXT, random_state = 0)
	X_train2, X_test2, y_train2, y_test2 = train_test_split(x2, yNEU, random_state = 0)
	X_trainAGR, X_testAGR, y_trainAGR, y_testAGR = train_test_split(x2, yAGR, random_state = 0)
	X_trainCON, X_testCON, y_trainCON, y_testCON = train_test_split(x2, yCON, random_state = 0)
	X_trainOPN, X_testOPN, y_trainOPN, y_testOPN = train_test_split(x2, yOPN, random_state = 0)

	# One-hot encoding (CountVectorizing)
	#Transforming words into victors by count occurrence of each word in a document
	X_train_counts = count_vect.fit_transform(X_train)
	X_train_counts2 = count_vect.fit_transform(X_train2)
	X_train_countsAGR = count_vect.fit_transform(X_trainAGR)
	X_train_countsCON = count_vect.fit_transform(X_trainCON)
	X_train_countsOPN = count_vect.fit_transform(X_trainOPN)

	# TfidfTransformer
	#the goal of tf-idf instead of raw frequencies of occurence of a token in a given document is to scale down the impact
	#of tokens that occur very frequently in a given corpus and that are hence empirically less informative than features
	#that occur in a small fraction of the training corpus
	X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
	X_train_tfidf2 = tfidf_transformer.fit_transform(X_train_counts2)
	X_train_tfidfAGR = tfidf_transformer.fit_transform(X_train_countsAGR)
	X_train_tfidfCON = tfidf_transformer.fit_transform(X_train_countsCON)
	X_train_tfidfOPN = tfidf_transformer.fit_transform(X_train_countsOPN)
	#
	clf = MultinomialNB().fit(X_train_tfidf, y_train)
	clf2 = MultinomialNB().fit(X_train_tfidf2, y_train2)
	clfAGR = MultinomialNB().fit(X_train_tfidfAGR, y_trainAGR)
	clfCON = MultinomialNB().fit(X_train_tfidfCON, y_trainCON)
	clfOPN = MultinomialNB().fit(X_train_tfidfOPN, y_trainOPN)
	#

	chat_text = request.form['rawtext']
	bot = ChatBot('Bot')
	bot.set_trainer(ListTrainer)

	#ex = count_vect.fit_transform([chat_text])
	example = count_vect.transform([chat_text])

	predicted = clf.predict(example)
	predicted2 = clf2.predict(example)
	predictedAGR = clfAGR.predict(example)
	predictedCON = clfCON.predict(example)
	predictedOPN = clfOPN.predict(example)

	chat = TextBlob(chat_text)
	chat_Sentiment = chat.sentiment.polarity
	reply = bot.get_response(chat_text)
#	while True:
#		message = request.form['rawtext']
		
	#	if message.strip() != 'Bye':
	#		reply = bot.get_response(message)
#		if message.strip() == 'Bye':
	#		break

	return render_template('chat-bot.html',received_text = chat_text, bot_response = reply, chat_sent = chat_Sentiment, pers_response = predictedAGR, EXT = predicted, NEU = predicted2,
		CON = predictedCON, OPN = predictedOPN)
예제 #39
0
    "Let's play DOTA2",
    "I am the carry of this team.",
    "You are the support",
    "Stop",
    "Hannah",
    "Brent",
    "Brittany",
    "Luis",
    "Help. Help. Plz Help.",
    "Matt",
    "Eli",
    "Katie",
]

# Chatbot training
chatbot.set_trainer(ListTrainer)

chatbot.train(ChatStuff)
# chatbot.set_trainer(ChatterBotCorpusTrainer)
# chatbot.train("chatterbot.corpus.english")

# Bot action responding
@bot.message_handler(func=lambda m:(random.random() < frequency))
# @bot.message_handler(commands=['test'])
def chatterbot_us(message):
    inp = str(message.text)
    print(message.text)
    response = chatbot.get_response(inp)
    print(response)
    # Send a message in group
    bot.send_message(message.chat.id, response)
예제 #40
0
#!/usr/bin/env python3
#
#by Eduardo"

import re
import os
import twitter
import urllib
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

trillian = ChatBot('Trillian',
	storage_adapter='chatterbot.storage.SQLStorageAdapter',
	database_url='./trillian.db')

trillian.set_trainer(ListTrainer)

'''
Get list of twitter accounts, and ignore the \n character
'''
f = open('twitter_accounts.txt')
accounts = [a[:-1] for a in f.readlines()]

max_tweets = 100

api = twitter.Api(consumer_key=os.environ['TWITTER_API_KEY'],
consumer_secret=os.environ['TWITTER_API_SECRET'],
access_token_key=os.environ['TWITTER_ACCESS_TOKEN'],
access_token_secret=os.environ['TWITTER_ACCESS_TOKEN_SECRET'],
sleep_on_rate_limit=True)
예제 #41
0
def talk():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Say something!")
        beeping.beep()
        r.dynamic_energy_threshold=True
        #r.energy_threshold = 200
        r.adjust_for_ambient_noise(source, 0.5)     # listen for 0.5 second to calibrate the energy threshold for ambient noise levels
        r.pause_threshold = 0.5
        r.dynamic_energy_adjustment_ratio = 2.5     # speech is louder than ambient noise by a factor of 2.5
        audio = r.listen(source)
        beeping.beep()
           
    # write audio to a WAV file
    #with open("microphone-results.wav", "wb") as f:
    #    f.write(audio.get_wav_data())
    ans = r.recognize_sphinx(audio)
    # recognize speech using Sphinx

    try:
        print("Sphinx thinks you said = " + ans)
    except sr.UnknownValueError:
        print("Sphinx could not understand audio")
    except sr.RequestError as e:
        print("Sphinx error; {0}".format(e))

    command = '0'

    if ans=='' :
    	return command

    if 'START' in ans:
        if 'FORWARD' in ans:
            print("Moving Forward")
            command='f'
        elif 'LEFT' in ans:
            print("Moving left" )
            command='m'
        elif 'NAME' in ans:
            print("Moving left" )
            command='m'
        elif 'GOOD' in ans:
            print("Moving left" )
            command='m'
        elif 'QUIT' in ans:
            print("Moving left" )
            command='m'
        elif 'RIGHT' in ans:
            print("Moving right")
            command='n'
        elif 'HEIGHT' in ans:
            print("Moving right")
            command='n'
        elif 'BYE' in ans:
            print("Moving right")
            command='n'
        elif 'BACK' in ans:
            print("Moving back")
            command='b'
        elif 'LINE' in ans and 'FOLLOW' in ans:
            print("Going to follow a line")
            command='t'
        elif 'OBJECT' in ans and 'TRACK' in ans:
            print("Going for object tracking")
            command='o'
        elif 'FOLLOW' in ans:
            print("Moving Forward")
            command='f'
        return command           
    # elif 'TURN' in ans:
    #     if 'LEFT' in ans:
    #         print("Moving left" )
    #         command='m'
    #     elif 'NAME' in ans:
    #         print("Moving left" )
    #         command='m'
    #     elif 'GOOD' in ans:
    #         print("Moving left" )
    #         command='m'
    #     elif 'RIGHT' in ans:
    #         print("Moving right")
    #         command='n'
    #     elif 'HEIGHT' in ans:
    #         print("Moving right")
    #         command='n'
    #     elif 'BYE' in ans:
    #         print("Moving right")
    #         command='n'
    #     return command
    elif 'STRAIGHT' in ans:
        print("Moving Forward")
        command='f'
        return command
    elif 'COME BACK' in ans:
        print("Moving back")
        command='b'
        return command
    elif 'STOP' in ans:
        command='s'
        return command
    elif 'HELLO' in ans or 'GOOD' in ans :
        command = 'g'
    elif 'MUSIC' in ans:
        music.music()
        return command
    elif 'PLAY' in ans:
        music.music()
        return command
    # elif 'EXIT' in ans:
    #     command='q'
    #     return command
    elif 'FINISH' in ans:
        command='q'
        return command
    elif 'QUIT' in ans:
        command='q'
        return command
    # elif 'HELLO' in ans or 'GOOD' in ans :
    # 	command = 'g'
    	# return command
        
    from chatterbot import ChatBot
    from chatterbot.training.trainers import ListTrainer

    if os.path.isfile("./database.db"):
    	os.remove("./database.db")
    # Create a new instance of a ChatBot
    bot = ChatBot("Terminal",
        storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
        logic_adapters=[
            "chatterbot.adapters.logic.MathematicalEvaluation",
            "chatterbot.adapters.logic.TimeLogicAdapter",
            "chatterbot.adapters.logic.ClosestMatchAdapter"
        ],
        input_adapter="chatterbot.adapters.input.VariableInputTypeAdapter",
        #output_adapter="chatterbot.adapters.output.OutputFormatAdapter",
        format='text',
        database="./database.db"
    )

    bot.set_trainer(ListTrainer)
    bot.train([
        "hello",
        "hi",
        "how are you",
        "i am fine",
        "that is good to hear",
        # "thank you",
        # "you are welcome",
        # "sorry",
        # "its okay", 
        "what is your name",
        "my name is HURO",
        "bye",
        "bye bye",
        "see you later",
        "take care",
        "you too",
        "good morning",
        "very good morning",
        "good afternoon",
        "very good afternoon",
        "good evening",
        "charming evening",
        "good night",
        "sweet dreams",
        "same to you",
        # "tell me about yourself",
        # "I am HURO. I am 60 centimeters tall and weighs 3 kilograms. I have 8 degrees of freedom, 2 in head and 3 in each arm. I am using ODroid and Arduino UNO.",
        # "what is your height",
        # "I am 60 centimeters tall",
        # "what is your weight",
        # "3 kilograms",
        "team members",
        "Ujjwal, Rijak, Abhishek, Saurabh, Mrinaal, Bhuvi, Shruti, Nitish",
        "what is ",
        "Ask a better question"

    ])

    response = bot.get_response(ans)
    print(response)

    import pyttsx

    engine = pyttsx.init()
    engine.setProperty('rate', 135)
    engine.say(response)
    engine.runAndWait()
    return command
예제 #42
0
#Import packages
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

#Import data to train the chatbot
bot = ChatBot('CHOTTU')  #define chatbot
bot.set_trainer(ChatterBotCorpusTrainer)  #define trainer - set algorithm
bot.train('chatterbot.corpus.english')  #Train the chatbot

#write code for interacting with chatbot

while (True):
    message = input('You: ')
    if (message == 'Bye' or message == 'bye'):
        #print('ChatBot: Bye. See you soon.')
        #print(bot.name,': Bye. See you soon')
        print('{}: Bye. See you soon.'.format(bot.name))
        break
    if (message != 'Bye' or message != 'bye'):
        #print('ChatBot: ',bot.get_response(message))
        print('{}: {}'.format(bot.name, bot.get_response(message)))
from flask import Flask, jsonify, request
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
import json
from flask_cors import CORS
import cantonese

app = Flask(__name__)
CORS(app)

amicia = ChatBot("Amica")
amicia.set_trainer(ListTrainer)
amicia.train(cantonese.cantonese_conversation)


@app.route("/conversation", methods=['POST'])
def conversation():
    user_input = request.get_json()
    print(user_input)
    question = user_input['question']
    response = amicia.get_response(question).text
    print(response)
    output = {'data': response}
    return json.dumps(output)


if __name__ == "__main__":
    app.run(host='0.0.0.0', port='5080')
예제 #44
0
# -*- coding: utf-8 -*-
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot(
    'Charlie',  # ชื่อแชตบ็อต
    storage_adapter=
    'chatterbot.storage.SQLStorageAdapter',  # กำหนดการจัดเก็บ ในที่นี้เลือก chatterbot.storage.SQLStorageAdapter เก็บเป็น Sqllite
    database='Charlie.sqlite3'  # ที่ตั้งฐานข้อมูล
)
chatbot.set_trainer(
    ChatterBotCorpusTrainer)  # กำหนดให้ Train จากชุดข้อมูลของ Chatterbot

chatbot.train(
    "chatterbot.corpus.english")  # เรียกใช้ชุดข้อมูล chatterbot.corpus.english
text = ""
while True:
    text = input("Text : ")
    if text == "exit":
        break
    response = chatbot.get_response(text)
    print(response)
예제 #45
0
from flask import Flask, Response, request
from chatterbot import ChatBot
from chatterbot.training.trainers import ChatterBotCorpusTrainer
app = Flask(__name__)
global AI
AI = ChatBot("papajohns")
AI.set_trainer(ChatterBotCorpusTrainer)
AI.train("chatterbot.corpus.english")

@app.route("/")
def hello():
        return "Hello World!"

@app.route("/chatbot/", methods=['POST'])
def bot():
    context = request.get_json()
    global AI
    r = AI.get_response(context['text'])
    resp = Response(response=str(r), status=200, mimetype="application/json")
    return resp

if __name__ == "__main__":
    app.run()
예제 #46
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

chatbot = ChatBot('My Chatbot',
                  trainer='chatterbot.trainers.ChatterBotCorpusTrainer')

chatterbot = ChatBot("My Personal Assistant",
                     storage_adapter="chatterbot.storage.SQLStorageAdapter")
chatterbot.set_trainer(ListTrainer)

chatterbot.train([
    "Hi!",
    "Hello!",
])

chatterbot.train([
    "Test!",
    "Test Answer!",
])

# Quick Testing
print("Hi!")
response = chatterbot.get_response("Hi!")
print(response)

# Quick Testing
print("Test!")
response = chatterbot.get_response("Test!")
print(response)
예제 #47
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer


# Uncomment the following line to enable verbose logging
# import logging
# logging.basicConfig(level=logging.INFO)

# Create a new instance of a ChatBot
bot = ChatBot(
    "Terminal",
    storage_adapter="chatterbot.storage.SQLStorageAdapter",
    input_adapter="chatterbot.input.TerminalAdapter",
    output_adapter="chatterbot.output.TerminalAdapter"
)
bot.set_trainer(ChatterBotCorpusTrainer)

bot.train("chatterbot.corpus.english")


CONVERSATION_ID = bot.storage.create_conversation()


def get_feedback():
    from chatterbot.utils import input_function

    text = input_function()

    if 'yes' in text.lower():
        return False
    elif 'no' in text.lower():
예제 #48
0
                     input_adapter="chatterbot.input.VariableInputTypeAdapter",
                     output_adapter="chatterbot.output.OutputAdapter")

# Print an example of getting one math based response
response = chatterbot.get_response("What is 4 + 9?")
print(response)

# Print an example of getting one time based response
response = chatterbot.get_response("What time is it?")
print(response)

# Print an example of getting one time based response
response = chatterbot.get_response("I am going to train you...")
print(response)

chatterbot.set_trainer(ChatterBotCorpusTrainer)

#chatterbot.train(
#    "chatterbot.corpus.english"
#)

chatterbot.train("./bot_project_knowledge/basic_overview/ProjectInfo.yml")

# Print an example of getting one time based response
response = chatterbot.get_response("What is Luke's PhD project?")
print(response)
"""
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer