コード例 #1
1
ファイル: server.py プロジェクト: vijaysharmay/Teemo
 def open(self):
     chatbot = ChatBot(
         'Captain Phasma',
         trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
     )
     chatbot.train("chatterbot.corpus.english")
     self.chatbot = chatbot
コード例 #2
1
ファイル: reply_engine.py プロジェクト: ParadoxZero/Lisa
 def init(self):
     self.bot = ChatBot(
         "Lisa",
         storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
         logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter",
         io_adapter="chatterbot.adapters.io.NoOutputAdapter",
         database="database/database.db",
     )
コード例 #3
0
ファイル: bot.py プロジェクト: wenqingyu/chatbot-platform
class Bot:

    def __init__(self, session):
        self.session = session
        self.chatbot = ChatBot(session)
        self.training()
        print session, " Initialized!"

    def training(self):
        # Train based on the english corpus
        print "Training . . ."
        self.chatbot.train("chatterbot.corpus.english")
        self.chatbot.train("chatterbot.corpus.italian")


    def getSession(self):
        print self.session
        return self.session

    # def getCreateDate():
    #     return self.createDate

    def getResponse(self, msg):
        response = self.chatbot.get_response(msg)
        return response
コード例 #4
0
    def test_training_with_unicode_characters(self):
        """
        Ensure that the training method adds unicode statements
        to the database.
        """
        import os

        bot = ChatBot("Test Bot2", database="unicode-database.db")

        conversation = [
            u"¶ ∑ ∞ ∫ π ∈ ℝ² ∖ ⩆ ⩇ ⩈ ⩉ ⩊ ⩋ ⪽ ⪾ ⪿ ⫀ ⫁ ⫂ ⋒ ⋓",
            u"⊂ ⊃ ⊆ ⊇ ⊈ ⊉ ⊊ ⊋ ⊄ ⊅ ⫅ ⫆ ⫋ ⫌ ⫃ ⫄ ⫇ ⫈ ⫉ ⫊ ⟃ ⟄",
            u"∠ ∡ ⦛ ⦞ ⦟ ⦢ ⦣ ⦤ ⦥ ⦦ ⦧ ⦨ ⦩ ⦪ ⦫ ⦬ ⦭ ⦮ ⦯ ⦓ ⦔ ⦕ ⦖ ⟀",
            u"∫ ∬ ∭ ∮ ∯ ∰ ∱ ∲ ∳ ⨋ ⨌ ⨍ ⨎ ⨏ ⨐ ⨑ ⨒ ⨓ ⨔ ⨕ ⨖ ⨗ ⨘ ⨙ ⨚ ⨛ ⨜",
            u"≁ ≂ ≃ ≄ ⋍ ≅ ≆ ≇ ≈ ≉ ≊ ≋ ≌ ⩯ ⩰ ⫏ ⫐ ⫑ ⫒ ⫓ ⫔ ⫕ ⫖",
            u"¬ ⫬ ⫭ ⊨ ⊭ ∀ ∁ ∃ ∄ ∴ ∵ ⊦ ⊬ ⊧ ⊩ ⊮ ⊫ ⊯ ⊪ ⊰ ⊱ ⫗ ⫘",
            u"∧ ∨ ⊻ ⊼ ⊽ ⋎ ⋏ ⟑ ⟇ ⩑ ⩒ ⩓ ⩔ ⩕ ⩖ ⩗ ⩘ ⩙ ⩚ ⩛ ⩜ ⩝ ⩞ ⩟ ⩠ ⩢",
        ]

        bot.train(conversation)

        response = bot.get_response(conversation[1])

        os.remove("unicode-database.db")

        self.assertEqual(response, conversation[2])
コード例 #5
0
ファイル: chat.py プロジェクト: vitorossi103/main_bot
    async def talk(self, ctx):

        """Command that implements the talk to the bot function.
        It uses ChatterBot, is a machine-learning based
        conversational dialog engine build in Python which makes
        it possible to generate responses based on collections of
        known conversations

        **Dependencies**: pip install chatterbot

        **Keyword arguments**:
        chatbot -- stores chatbot object
        ctx     -- Context reference to get message
        tts     -- Set to true for text to speed implementation
        """

        chatbot = ChatBot("Ron Obvious")
        chatbot.train("chatterbot.corpus.english")
        msg = ctx.message.content
        print(msg)
        if msg.startswith('$talk'):
            msg = msg[6:]
            print(msg)
            reply = chatbot.get_response(msg)

        await self.bot.send_message(ctx.message.channel, reply, tts=True)
コード例 #6
0
    def test_training_adds_statements(self):
        """
        Test that the training method adds statements to the database.
        """
        import os

        bot = ChatBot("Test Bot2", database="test-database-2")

        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?"
        ]

        bot.train(conversation)

        response = bot.get_response("Thank you.")

        os.remove("test-database-2")

        self.assertEqual(response, "You are welcome.")
コード例 #7
0
ファイル: views.py プロジェクト: ravid7000/gente
def gente_reply(request):
    if request.is_ajax():
        a = "sa"
        chatbot = ChatBot("Robbo")
        message = request.POST["message"]
        if message[0:6]=="#info ":
            ulter_message = message[6:len(message)]
            if ulter_message != "" and ulter_message != " ":
                url = "https://en.wikipedia.org/wiki/" + ulter_message
                data = requests.get(url)
                soup = BeautifulSoup(data.content)
                send_data = soup.find("p")
                reply = send_data.text
            else:
                reply = "#info message"
        else:
            reply = chatbot.get_response(message)
        print reply

        response_data = {}
        response_data["message"] = reply
        print response_data

        return HttpResponse(json.dumps(response_data))
    else:
        return HttpResponse("Error")
コード例 #8
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"你叫什么名字?"))
コード例 #9
0
ファイル: run.py プロジェクト: davidtwco/discord-chatbot
def run(password, name='Black Jesus', username='******', learn_mentions=True):
    chatbot = ChatBot(name,
                      storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
                      logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter",
                      io_adapter="chatterbot.adapters.io.NoOutputAdapter",
                      database="database.db")
    chatbot.train('chatterbot.corpus.english')

    print('\nInitializing Discord Chatbot')
    print('Logging in as {}.'.format(name))
    print('Username: {}'.format(username))
    print('Password: {}\n'.format(password))

    logger = logging.getLogger('discord')
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
    handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
    logger.addHandler(handler)

    client = discord.Client()
    client.login(username, password)

    def process_message(message):
        message = message.replace('<@{}>'.format(client.user.id), '') # remove the bot's id.

        if not learn_mentions:
            for match in re.finditer('(<@\d+>)', message, re.IGNORECASE): # remove mentions
                message = message.replace(match.groups(1), '')

        return message.strip()

    def should_skip_message(message):
        return False

    @client.event
    def on_message(message):
        if message.author == client.user: # learning from yourself is an exercise in futility
            return

        processed_message = process_message(message.content)
        if should_skip_message(message.content):
            return

        bot_response = chatbot.get_response(processed_message) # learn everything!

        if client.user in message.mentions:
            client.send_message(message.channel, bot_response)

    print('Running...')
    client.run()
コード例 #10
0
ファイル: reply_engine.py プロジェクト: gintu/Lisa
class reply_engine:
    bot = None

    def init(self):
        self.bot = ChatBot(
            "Lisa",
            storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
            logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter",
            io_adapter="chatterbot.adapters.io.NoOutputAdapter",
            database="../database.db",
        )
        self.bot.train("chatterbot.corpus.english")

    def get_reply(self, data):
        return self.bot.get_response(data)
コード例 #11
0
ファイル: talk_manager.py プロジェクト: Pandhariix/ARIIA
	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.",
		])
コード例 #12
0
ファイル: chat.py プロジェクト: Gab0/dZAP
class Chatbrain ():
    def __init__(self):
        
        self.brain = ChatBot("Adolfo",
                storage_adapter = "chatterbot.adapters.storage.MongoDatabaseAdapter",
                   logic_adapters=["chatterbot.adapters.logic.EvaluateMathematically",
                                  #"chatterbot.adapters.logic.TimeLogicAdapter"])
                                  "chatterbot.adapters.logic.ClosestMatchAdapter"],
                    io_adapter="chatterbot.adapters.io.SelectiveAdapter")
        
        self.brain.train("chatterbot.corpus.Portuguese.conversations_pt-BR")

    def respond(self, textin):
        return self.brain.get_response(textin)
    def read(self, inputc):
        self.brain.io.process_input(statement=inputc)
コード例 #13
0
ファイル: chatter.py プロジェクト: luksireiku/polaris
 def __init__(self, bot):
     self.bot = bot
     self.commands = [
         {
             'command': '@%s' % self.bot.info.username,
             'parameters': [],
             'hidden': True
         },
         {
             'command': '^%s' % self.bot.info.first_name.split()[0],
             'parameters': [],
             'hidden': True
         }
     ]
     self.chatter = ChatBot(
         self.bot.info.first_name,
         trainer='chatterbot.trainers.ChatterBotCorpusTrainer',
         storage_adapter="chatterbot.adapters.storage.JsonFileStorageAdapter",
         database='polaris/data/%s.chatter.json' % self.bot.name,
         logic_adapters=[
             "chatterbot.adapters.logic.MathematicalEvaluation",
             "chatterbot.adapters.logic.TimeLogicAdapter",
             "chatterbot.adapters.logic.ClosestMatchAdapter"
         ],
         filters=["chatterbot.filters.RepetitiveResponseFilter"]
     )
     if self.bot.config.translation != 'default':
         self.chatter.train("chatterbot.corpus.spanish")
     else:
         self.chatter.train("chatterbot.corpus.english")
コード例 #14
0
ファイル: base_case.py プロジェクト: virdi/ChatterBot
    def setUp(self):
        """
        Set up a database for testing.
        """
        import os

        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.chatbot = ChatBot("Test Bot")
        self.chatbot.database.set_path("test-database.db")

        self.chatbot.train(data1)
        self.chatbot.train(data2)
        self.chatbot.train(data3)
コード例 #15
0
    def setUp(self):
        self.test_data_directory = 'test_data'
        self.test_database_name = self.random_string() + ".db"

        if not os.path.exists(self.test_data_directory):
            os.makedirs(self.test_data_directory)

        database_path = os.path.join(
            self.test_data_directory,
            self.test_database_name
        )

        self.chatbot = ChatBot(
            "Test Bot",
            input_adapter="chatterbot.adapters.input.VariableInputTypeAdapter",
            output_adapter="chatterbot.adapters.output.OutputFormatAdapter",
            logic_adapters=[
                "tests.logic_adapter_tests.test_data_cache.DummyMutatorLogicAdapter"
            ],
            database=database_path
        )

        self.chatbot.train([
            "Hello",
            "How are you?"
        ])
コード例 #16
0
ファイル: chatbot.py プロジェクト: lkmnds/jose
    def __init__(self, bot):
        super().__init__(bot)
        self.whitelist = self.config.jose_db['chatbot_whitelist']

        self.chatbot = ChatBot(
            'José',
            trainer='chatterbot.trainers.ListTrainer',

            preprocessors=[
                'chatterbot.preprocessors.clean_whitespace',
                'chatterbot.preprocessors.unescape_html',
            ],

            logic_adapters=[
                'chatterbot.logic.BestMatch',
                'chatterbot.logic.MathematicalEvaluation',
                {
                    'import_path': 'chatterbot.logic.LowConfidenceAdapter',
                    'threshold': 0.2,
                    'default_response': 'I do not understand.'
                }
            ],

            input_adapter="chatterbot.input.VariableInputTypeAdapter",
            output_adapter="chatterbot.output.OutputAdapter",
            logger=log
        )

        # Dict[int] -> str
        self.sessions = {}

        self.train_lock = asyncio.Lock()
        self.chat_lock = asyncio.Lock()
コード例 #17
0
ファイル: chat.py プロジェクト: jdanlewis/yobot
 def create_chatter_bot(self):
     logging.info('Creating ChatBot...')
     chatterbot = ChatBot(
         self.config['botname'],
         # TODO move to config
         database="/var/lib/yobot/chatterbot.db",
         storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
         logic_adapters=[
             # "chatterbot.adapters.logic.EvaluateMathematically",
             "chatterbot.adapters.logic.ClosestMatchAdapter"
         ],
         io_adapter="chatterbot.adapters.io.NoOutputAdapter",
     )
     chatterbot.train("chatterbot.corpus.english")
     logging.info('ChatBot initialized')
     return chatterbot
コード例 #18
0
ファイル: train.py プロジェクト: AugustoQueiroz/ChatterBot
    def handle(self, *args, **options):
        from chatterbot import ChatBot
        from chatterbot.ext.django_chatterbot import settings

        chatterbot = ChatBot(**settings.CHATTERBOT)

        chatterbot.train(chatterbot.training_data)

        # Django 1.8 does not define SUCCESS
        if hasattr(self.style, "SUCCESS"):
            style = self.style.SUCCESS
        else:
            style = self.style.NOTICE

        training_class = chatterbot.trainer.__class__.__name__
        self.stdout.write(style('ChatterBot trained using "%s"' % training_class))
コード例 #19
0
ファイル: chatbot.py プロジェクト: sherodtaylor/goodfoodbot
class GoodFoodBot: 
  def __init__(self):
    self.bot = ChatBot('Good Food Bot')

    print 'start training'

    # Train based on the english conversations corpus

    print 'finished training'

  def train_bot(self):
    chunks = self.get_chunks(self.clean_dataset, 100)
    print 'start chunk training'
    for chunk, i in chunks:
      self.bot.train(chunk)
      print 'finished chunk %s' % i


    print 'finished training with movie_lines'
  def clean_dataset(self):
    n = path.join(path.dirname(__file__), 'data/movie_lines.txt')
    file = open(n, 'r')
    array = file.read().split('\n')
    mapped_arr = map(lambda txt: txt.split(' +++$+++ ')[-1:][0], array[0:1000])
    return mapped_arr

  def format_data(self, arr):
    return map(lambda txt: txt.split(' +++$+++ ')[-1:][0], arr)

  def get_response(self, text):
    return self.bot.get_response(text) 

  def get_chunks(self, arr, n):
    # Declare some empty lists
    chunk = []
    chunks = []
   
    # Step through the data n elements
    # at a time
    for x in range(0, len(arr), n):
      # Extract n elements
      chunk = arr[x:x+n]
      # Add them to list
      chunks.append(chunk)
   
    # Return the new list
    return chunks
コード例 #20
0
ファイル: bot.py プロジェクト: feynmanliang/gigster-chat-bot
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
コード例 #21
0
ファイル: chatbot.py プロジェクト: sherodtaylor/goodfoodbot
  def __init__(self):
    self.bot = ChatBot('Good Food Bot')

    print 'start training'

    # Train based on the english conversations corpus

    print 'finished training'
コード例 #22
0
ファイル: tkinter_gui.py プロジェクト: wwj718/ChatterBot
class TkinterGUIExample(tk.Tk):

    def __init__(self, *args, **kwargs):
        '''
        Create & set window variables.
        '''
        tk.Tk.__init__(self, *args, **kwargs)

        self.chatbot = ChatBot("No Output",
            storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
            logic_adapters=[
                "chatterbot.adapters.logic.ClosestMatchAdapter"
            ],
            input_adapter="chatterbot.adapters.input.VariableInputTypeAdapter",
            output_adapter="chatterbot.adapters.output.OutputFormatAdapter",
            database="../database.db"
        )

        self.title("Chatterbot")

        self.initialize()

    def initialize(self):
        '''
        Set window layout.
        '''
        self.grid()

        self.respond = ttk.Button(self, text='Get Response', command=self.get_response)
        self.respond.grid(column=0, row=0, sticky='nesw', padx=3, pady=3)

        self.usr_input = ttk.Entry(self, state='normal')
        self.usr_input.grid(column=1, row=0, sticky='nesw', padx=3, pady=3)

        self.conversation_lbl = ttk.Label(self, anchor=tk.E, text='Conversation:')
        self.conversation_lbl.grid(column=0, row=1, sticky='nesw', padx=3, pady=3)

        self.conversation = ScrolledText.ScrolledText(self, state='disabled')
        self.conversation.grid(column=0, row=2, columnspan=2, sticky='nesw', padx=3, pady=3)

    def get_response(self):
        '''
        Get a response from the chatbot &
        display it.
        '''
        user_input = self.usr_input.get()
        self.usr_input.delete(0, tk.END)

        response = self.chatbot.get_response(user_input)

        self.conversation['state'] = 'normal'
        self.conversation.insert(
            tk.END, "Human: " + user_input + "\n" + "ChatBot: " + str(response.text) + "\n"
        )
        self.conversation['state'] = 'disabled'

        time.sleep(0.5)
コード例 #23
0
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)
コード例 #24
0
ファイル: views.py プロジェクト: heejun8609/Project
    def post(self, request, *args, **kwargs):
        """
        Return a response to the statement in the posted data.
        """
        input_data = json.loads(request.read().decode('utf-8'))

        #self.validate(input_data)

        #print "******* input_data : " + json.dumps(input_data)
        print "******* input_data : " + input_data.get("text")

        chatbot = ChatBot(
            'tony bot 01',
            logic_adapters=[
                {
                    'import_path': 'chatterbot.logic.BestMatch'
                },
                {
                    'import_path': 'chatterbot.logic.LowConfidenceAdapter',
                    'threshold': 0.33,
                    'default_response': u'그 질문에 대해서는 내가 대답해 줄 수 있는 게 없어. || 해당 질문에 대답하기를 원한다면 다음 링크를 통해서 너의 의견을 제안해 주면 고맙겠어. || <a href="http://35.189.163.55:8080/anemo/trainingUI/chatterbot_UI.html">임시 학습 페이지 링크</a>'
                }
            ],
            trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
        )

        # Train based on the english corpus
        chatbot.train("/Users/kimtony/workspace/anemonlp/AnemoNLP/App/MLBot/chatterbot/corpus")

        #conversation = self.get_conversation(request)

        #response = self.chatterbot.get_response(input_data, conversation.id)

        #response_data = response.serialize()

        response = unicode(chatbot.get_response(input_data)).encode("utf8")

        print "******* response : " + response

        response_data = {
            'text': response
        }

        return JsonResponse(response_data, status=200)
コード例 #25
0
ファイル: chat.py プロジェクト: Gab0/dZAP
 def __init__(self):
     
     self.brain = ChatBot("Adolfo",
             storage_adapter = "chatterbot.adapters.storage.MongoDatabaseAdapter",
                logic_adapters=["chatterbot.adapters.logic.EvaluateMathematically",
                               #"chatterbot.adapters.logic.TimeLogicAdapter"])
                               "chatterbot.adapters.logic.ClosestMatchAdapter"],
                 io_adapter="chatterbot.adapters.io.SelectiveAdapter")
     
     self.brain.train("chatterbot.corpus.Portuguese.conversations_pt-BR")
コード例 #26
0
ファイル: __init__.py プロジェクト: dawnpower/ChatterBot
def setup_module():
    chatbot = ChatBot('setup')

    chatbot.logic_adapters = [
        LogicAdapter(
            chatbot,
            statement_comparison_function=comparisons.jaccard_similarity
        ),
        LogicAdapter(
            chatbot,
            statement_comparison_function=comparisons.sentiment_comparison
        ),
        LogicAdapter(
            chatbot,
            statement_comparison_function=comparisons.synset_distance
        ),
    ]

    chatbot.initialize()
コード例 #27
0
ファイル: tkinter_gui.py プロジェクト: gunthercox/ChatterBot
class TkinterGUIExample(tk.Tk):

    def __init__(self, *args, **kwargs):
        """
        Create & set window variables.
        """
        tk.Tk.__init__(self, *args, **kwargs)

        self.chatbot = ChatBot(
            "GUI Bot",
            storage_adapter="chatterbot.storage.SQLStorageAdapter",
            logic_adapters=[
                "chatterbot.logic.BestMatch"
            ],
            database_uri="sqlite:///database.db"
        )

        self.title("Chatterbot")

        self.initialize()

    def initialize(self):
        """
        Set window layout.
        """
        self.grid()

        self.respond = ttk.Button(self, text='Get Response', command=self.get_response)
        self.respond.grid(column=0, row=0, sticky='nesw', padx=3, pady=3)

        self.usr_input = ttk.Entry(self, state='normal')
        self.usr_input.grid(column=1, row=0, sticky='nesw', padx=3, pady=3)

        self.conversation_lbl = ttk.Label(self, anchor=tk.E, text='Conversation:')
        self.conversation_lbl.grid(column=0, row=1, sticky='nesw', padx=3, pady=3)

        self.conversation = ScrolledText.ScrolledText(self, state='disabled')
        self.conversation.grid(column=0, row=2, columnspan=2, sticky='nesw', padx=3, pady=3)

    def get_response(self):
        """
        Get a response from the chatbot and display it.
        """
        user_input = self.usr_input.get()
        self.usr_input.delete(0, tk.END)

        response = self.chatbot.get_response(user_input)

        self.conversation['state'] = 'normal'
        self.conversation.insert(
            tk.END, "Human: " + user_input + "\n" + "ChatBot: " + str(response.text) + "\n"
        )
        self.conversation['state'] = 'disabled'

        time.sleep(0.5)
コード例 #28
0
class Conversation(Adaptor):

    def __init__(self, options):
        super(Conversation, self).__init__(options)

        if 'logic_adapters' not in options:
            options["logic_adapters"] = [
                "chatterbot.adapters.logic.ClosestMatchAdapter",
                "chatterbot.adapters.logic.EvaluateMathematically",
                "chatterbot.adapters.logic.TimeLogicAdapter"
            ]

        self.chatbot = ChatBot("Salvius", **options)

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

    def respond(self, text):
        return self.chatbot.get_response(text)
コード例 #29
0
ファイル: talk_manager.py プロジェクト: Pandhariix/ARIIA
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
コード例 #30
0
from chatterbot import ChatBot

bot = ChatBot(
    "Training Example",
    storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
    logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter",
    io_adapter="chatterbot.adapters.io.TerminalAdapter",
    database="./new_database.db")
'''
Give the chat bot a sample conversation to help
it learn how to respond to different statements.
'''
training_data = [
    "Hello", "Hi there!", "How are you doing?", "I'm great.",
    "That is good to hear", "Thank you.", "Your welcome.", "Sure, any time.",
    "Yeah", "Can I help you with anything?"
]

bot.train(training_data)

user_input = ""

while True:
    try:
        user_input = bot.get_input()

        bot_input = bot.get_response(user_input)

    except (KeyboardInterrupt, EOFError, SystemExit):
        break
コード例 #31
0
import chatterbot
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
'''
chatbot = ChatBot("Rog")
chatterbot.trainers.UbuntuCorpusTrainer(storage, **kwargs)
'''
'''
    input_adapter='chatterbot.input.TerminalAdapter',
    output_adapter='chatterbot.output.TerminalAdapter',
    logic_adapters=[
        'chatterbot.logic.MathematicalEvaluation',
        'chatterbot.logic.TimeLogicAdapter'
    ],
    '''
bot = ChatBot(
    'Rog',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    database=
    'F:\Projects\chatbotSocket\chatbotsoc\chatbot_tutorial/database.sqlite3')
#from chatterbot.trainers import ListTrainer

bot.set_trainer(ChatterBotCorpusTrainer)
#bot.train("chatterbot.corpus.english")
bot.train("C:\Users\AK24ALIVE\Desktop\Deeper\df\ubuntu_dialogs.tar")
#response = bot.get_response("F**k off")
#print(response)
コード例 #32
0
ファイル: app.py プロジェクト: omkarudawant/ChatterBot-WebApp
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")
trainer = ChatterBotCorpusTrainer(english_bot)
trainer.train("chatterbot.corpus.english")


@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(debug=False)
コード例 #33
0
async def on_message(message):
    chatbot = ChatBot("Ai2")
    conversation = [
        "Hello, my name is Ai2",
        "What’s your nationality?",
        "Everybody can be my friend.",
        "So we’ve met again,eh?",
        "What have you been doing?",
        "I like jazz music",
        "Training",
        "Who is your favourite singer?",
        "Pai",
        "Nice to meet you",
        "How are you?",
        "My favourite sport is batminton",
        "My favourite sport is chairball",
        "When is your birthday?",
        "Hello",
        "23th Dec 2020",
        "Do you have a mobile phone?",
        "Yes, I do",
        "No, I don't",
        "How long have you been here for? ",
        "What kind of music do you like?",
        "I like pop music",
        "Fine thanks, and you?",
        "I’m okay, thank you",
        "Where are you from?",
        "How much is it?",
        "Can you give me a discount?",
        "This is a special price for you",
        "I’m from Thailand",
        "How old are you?",
        "I’m 0 years old",
        "I like hip-hop music",
        "I like rock music",
        "I like electronic music",
        "What’s your favorite food?",
        "Thank you",
        "Thanks for everything",
        "My favourite food is noodle",
        "What’s your favorite movie?",
        "My favourite movie is Avenger",
        "My favourite movie is Interstellar",
        "Yes",
        "Do you deliver?",
        "Does it have a warranty?",
        "I am good",
        "That is good to hear",
        "That’s not fair",
        "You are welcome"
        "My favourite movie is Avatar",
        "What’s your favorite sport?",
        "My favourite sport is football",
        "My favourite sport is basketball",
        "My favourite sport is tennis",
        "What animals do you like?",
        "I like dogs",
        "I like cats",
        "What kind of fruit do you like?",
        "Do you like bananas?",
        "I like watching TV",
        "I really like gardening",
        "I love the cinema",
        "I enjoy travelling",
        "I’m interested in photography",
        "I read a lot",
        "How many languages can you speak?",
        "Can you sing?",
        "Can I try it on?",
        "I’ll take this one",
        "I like it very much",
        "I’ll take it",
        "This is the last piece!",
        "That seems expensive",
        "Do you have a less expensive one?",
        "It’s just right",
        "No",
        "I’ll pay",
        "What do you want to eat?",
        "What are you looking for?",
        "I’m looking for shoes",
        "I’m just looking",
    ]

    trainer = ListTrainer(chatbot)
    trainer.train(conversation)
    textttt = message.content.lower()

    response = chatbot.get_response(textttt)
    output = str(response) + "\n"

    if message.author.id == bot.user.id:
        return
    await message.channel.send(output)
    sleep(1)
コード例 #34
0
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot

bot = ChatBot('teste')
conversa = [
    'Oi', 'Olá', 'Tudo bem?', 'Tudo ótimo', 'Você gosta de programar?',
    'Sim, eu programo em Python'
]

bot.set_trainer(ListTrainer)
bot.train(conversa)

while True:
    pergunta = input("Usuário: ")
    resposta = bot.get_response(pergunta)
    if float(resposta.confidence) > 0.5:
        print('TW Bot: ', resposta)
    else:
        print('TW Bot: Ainda não sei responder esta pergunta')
コード例 #35
0
# -*- coding: utf-8 -*-
from chatterbot import ChatBot
"""
This example shows how to create a chat bot that
will learn responses based on an additional feedback
element from the user.
"""

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

# Create a new instance of a ChatBot
bot = ChatBot('Feedback Learning Bot',
              storage_adapter='chatterbot.storage.JsonFileStorageAdapter',
              logic_adapters=['chatterbot.logic.BestMatch'],
              input_adapter='chatterbot.input.TerminalAdapter',
              output_adapter='chatterbot.output.TerminalAdapter')

DEFAULT_SESSION_ID = bot.default_session.id


def get_feedback():
    from chatterbot.utils import input_function

    text = input_function()

    if 'yes' in text.lower():
        return True
    elif 'no' in text.lower():
        return False
コード例 #36
0
ファイル: app.py プロジェクト: sidarth16/Sid-Travel-Chatbot
from flask import Flask, render_template, request, redirect, url_for
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import re

app = Flask(__name__)

###-------Chatter-bot-----------####
chat_bot = ChatBot("Sid Travel Bot")
trainer = ListTrainer(chat_bot)
# trainer.train("chatterbot.corpus.english")
data = open("data/data_txt.txt", "r").readlines()
trainer.train(data)

####------Dictionary method instead of chatter-bot-------####
# chat_bot = dict()
# for i in range(0,len(data),2):
##      print(data[i])
#     chat_bot[data[i][:-1]] = data[i+1][:-1]
####-----------------------------------------------------####

curOption = 1
option_dict = {
    0:
    "type",
    1:
    "date",
    2: ["less than 3 days", "3 - 7 days", "more than 7 days"],
    3: ["Chennai", "Delhi", "Hyderabad", "Mumbai", "Kolkata"],
    4: [
        "Solo &#128102;", "Couple &#128107;", "Family &#128106;",
コード例 #37
0
ファイル: botv2.py プロジェクト: leomozzer/chatbot
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
from selenium import webdriver
import pyautogui
import time

bot = ChatBot('Test')

conv = [
    'oi', 'olá', 'bom dia', 'bom dia, como vai?', 'estou bem',
    'qual é o seu nome?', 'meu nome é Chatbot'
]

bot.set_trainer(ListTrainer)

bot.train(conv)

print('Olá, eu sou o AgropetBot, atendente virtual da AgropetSol')
print('Em que posso ajudar?')

while True:
    quest = input('Você: ')

    response = bot.get_response(quest)

    if float(response.confidence) > 0.5:

        print('Bot: ', response)

    else:
        print('Bot: Não entendi.')
コード例 #38
0
 def open(self):
     chatbot = ChatBot(
         'Captain Phasma',
         trainer='chatterbot.trainers.ChatterBotCorpusTrainer')
     chatbot.train("chatterbot.corpus.english")
     self.chatbot = chatbot
コード例 #39
0
 def __init__(self, *args):
     self.chatbot = ChatBot('antony', read_only=True)
     self.trainer_corpus = ChatterBotCorpusTrainer(self.chatbot)
     self.trainer_list = ListTrainer(self.chatbot)
コード例 #40
0
class DialogueManager(object):
    def __init__(self, paths):
        print("Loading resources...")

        # Intent recognition:
        self.intent_recognizer = unpickle_file(paths['INTENT_RECOGNIZER'])
        self.tfidf_vectorizer = unpickle_file(paths['TFIDF_VECTORIZER'])

        self.ANSWER_TEMPLATE = 'I think its about %s\nThis thread might help you: https://stackoverflow.com/questions/%s'

        # Goal-oriented part:
        self.tag_classifier = unpickle_file(paths['TAG_CLASSIFIER'])
        self.thread_ranker = ThreadRanker(paths)
        self.__init_chitchat_bot()

    def __init_chitchat_bot(self):
        """Initializes self.chitchat_bot with some conversational model."""

        # Hint: you might want to create and train chatterbot.ChatBot here.
        # Create an instance of the ChatBot class.
        # Set a trainer set_trainer(ChatterBotCorpusTrainer) for the ChatBot.
        # Train the ChatBot with "chatterbot.corpus.english" param.
        # Note that we use chatterbot==0.7.6 in this project. 
        # You are welcome to experiment with other versions but they might have slightly different API.
        
        ########################
        #### YOUR CODE HERE ####
        ########################

        # remove this when you're done
        #raise NotImplementedError(
        #    "Open dialogue_manager.py and fill with your code. In case of Google Colab, download"
        #    "(https://github.com/hse-aml/natural-language-processing/blob/master/project/dialogue_manager.py), "
        #    "edit locally and upload using '> arrow on the left edge' -> Files -> UPLOAD")

        self.chitchat_bot = ChatBot('week5')
        #trainer = ChatterBotCorpusTrainer(self.chitchat_bot)
        #trainer.train("chatterbot.corpus.english")
       
    def generate_answer(self, question):
        """Combines stackoverflow and chitchat parts using intent recognition."""

        # Recognize intent of the question using `intent_recognizer`.
        # Don't forget to prepare question and calculate features for the question.
        #### YOUR CODE HERE ####
        prepared_question = text_prepare(question)
        #### YOUR CODE HERE ####
        features = self.tfidf_vectorizer.transform([prepared_question])
        #### YOUR CODE HERE ####
        intent = self.intent_recognizer.predict(features)[0]

        # Chit-chat part:   
        if intent == 'dialogue':
            # Pass question to chitchat_bot to generate a response.       
            #### YOUR CODE HERE ####
            response = self.chitchat_bot.get_response(question)
            return response
        
        # Goal-oriented part:
        else:        
            # Pass features to tag_classifier to get predictions.
            #### YOUR CODE HERE ####
            tag = self.tag_classifier.predict(features)[0]
            
            # Pass prepared_question to thread_ranker to get predictions.
            #### YOUR CODE HERE ####
            thread_id = self.thread_ranker.get_best_thread(prepared_question, tag)
            
            return self.ANSWER_TEMPLATE % (tag, thread_id)
コード例 #41
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os
import codecs

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

for files in os.listdir(
        'C:/Users/asus\Desktop\chatterbot-corpus-master\chatterbot_corpus\data\Bangla/'
):
    data = codecs.open(
        'C:/Users/asus\Desktop\chatterbot-corpus-master\chatterbot_corpus\data\Bangla/'
        + files,
        'r',
        encoding='utf-8').readlines()
    bot.train(data)

while True:
    message = input('You: ', )
    if message.strip() != 'বাই':
        reply = bot.get_response(message)
        print('Admission_Helpline:', reply)
    if message.strip() == 'বাই':
        print('Admission_Helpline: bye')
        break
コード例 #42
0
from chatterbot import ChatBot

from plugin_system import Plugin

try:
    from settings import USE_CHATTER
except ImportError:
    USE_CHATTER = False

if not USE_CHATTER:
    plugin = Plugin(
        '💬 Переписка с ботом - для использование напишите в начале сообщения слово "бот"',
        usage=['бот [сообщение] - сообщение боту'])

    chatbot = ChatBot('Валера',
                      trainer='chatterbot.trainers.ChatterBotCorpusTrainer')

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

    @plugin.on_command('бот', 'бот,')
    async def chat(msg, args):
        return await msg.answer(str(chatbot.get_response(msg.text)))
コード例 #43
0
ファイル: main.py プロジェクト: techeduhelper/PythonChatBot
voices = engine.getProperty('voices')
print(voices)

# Set voice male or female '0' contain male voice and '1' contain female voice

engine.setProperty('voice', voices[1].id)


# For speek audio create a function
def speak(word):
    engine.say(word)
    engine.runAndWait()


# ptttsx2 instal library for voice
bot = ChatBot('Manir')

# for boat training
conversation = [
    "Hello", "Hi there!", "How are you doing?", "I'm doing great.",
    "That is good to hear", "Thank you.", "You're welcome."
]
trainer = ListTrainer(bot)

#now training the bot with the help of trainer

trainer.train(conversation)

#For testing purposes use

#answer = bot.get_response("How are you doing?")
コード例 #44
0
# while True:
# 	message=input('\t\t\tYou:')
# 	if message.strip()!='Bye':
# 		replay=bot.get_response(message)
# 		print('Candice:',replay)
# 	if message.strip()=='Bye':
# 		print('Candice: Bye')
# 		break

#import libraries
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os

#Create a chatbot
bot = ChatBot('Candice')

##
# bot.set_trainer(ListTrainer)
trainer = ListTrainer(bot)

#training on english dataset
for files in os.listdir('./english/'):
    data = open('./english/' + files, 'r').readlines()
    trainer.train(data)  #chat feature
while True:
    message = input('\t\t\tYou:')
    if message.strip() != 'Bye':
        reply = bot.get_response(message)
        print('Candice:', reply)
    if message.strip() == 'Bye':
コード例 #45
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from bottle import route, run, template, get, post, request
import json

chatbot = ChatBot('SimpleApi')
chatbot.set_trainer(ListTrainer)
chatbot.read_only = True


@route('/train', method='POST')
def index():
    try:
        l = json.load(request.body)
        chatbot.train(l["convo"])
        return json.dumps({"trained": l["convo"]})
    except:
        pass
    return json.dump({"error": "exception"})


@route('/ask', method='POST')
def index():
    try:
        l = json.load(request.body)
        CONVERSATION_ID = chatbot.storage.create_conversation()
        answer = chatbot.get_response(l["message"], CONVERSATION_ID)
        return json.dumps({"message": str(answer)})
    except:
        pass
    return json.dumps({"error": "exception"})
コード例 #46
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

chatbot = ChatBot("chatbot")

chatbot.set_trainer(ListTrainer)


def train(statement):
    chatbot.train(statement)


def speech(ask):
    return chatbot.get_response(ask).text
コード例 #47
0
#import files
from flask import Flask, render_template, request
from chatterbot import ChatBot
#from chatterbot.trainers import ChatterBotCorpusTrainer
from chatterbot.trainers import ListTrainer

conversation = ["aaaah ok", "and what does that mean?"]
app = Flask(__name__)
bot = ChatBot("Daniel")
#trainer = ChatterBotCorpusTrainer(bot)
trainer = ListTrainer(bot)
trainer.train(conversation)
#trainer.train('chatterbot.corpus.english')
#bot.train("chatterbot.corpus.english")
my_dict = {}


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


@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
    response = str(bot.get_response(userText))
    my_dict[userText] = response
    f = open("dict.csv", "w")
    f.write(str(my_dict))
    f.close()
    return response
コード例 #48
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 29 19:03:49 2020

@author: n_rishabh
"""


from chatterbot import ChatBot
chatbot = ChatBot("Ron")

from chatterbot.trainers import ListTrainer

from chatterbot.trainers import ChatterBotCorpusTrainer

trainer = ListTrainer(chatbot)

trainer.train([
    "I m not able to access my Bitrix24 account?",
    "Go to https://cloudcounselage24.bitrix24.com/ On the Login page, In the, ‘Enter the phone number or email’, type in your email id that you have registered with Cloud Counselage and Click ‘Forgot Password’. In case the problem persists, please write a mail to [email protected]",
])

trainer.train([
    "What is the job profile? Will we be able to work only in the tech we have chosen for the internship?",
    "Your job profile is 'Technology - Intern'; if you're in cloud computing technology to update in your LinkedIn or resume, you can write as 'Cloud Computing - Intern'. Yes, you'll only work in the technology you're selected for but you can take the training of other technologies.",
])

trainer.train([
    "How many workgroups will an intern be a part of?/ How many workgroups should I be in?",
    "Every intern should be a part of 2 workgroups. 1. '202003-IP'  -- This is a general workgroup. Everyone who is enrolled in IP should be a part of this workgroup. 2. '202003-IP-Technology'  -- This is a technology-specific workgroup. You'll be added to the technology you had enrolled for. For example '202003-IP-Python' for students who enrolled for python.If anyone has not been added to any of these workgroups, kindly message 'Cloud Counselage HR' regarding the same over bitrix24 platform.",
コード例 #49
0
ファイル: chatbot.py プロジェクト: mtnkodiak/900footalienbot
from chatterbot import ChatBot, filters
from chatterbot.trainers import ChatterBotCorpusTrainer
from chatterbot.trainers import UbuntuCorpusTrainer
from chatterbot.comparisons import levenshtein_distance
from chatterbot.response_selection import get_first_response
import logging

logging.basicConfig(level=logging.INFO)

ninefa_bot = ChatBot(name='NineFABot', 
                     read_only=False,
                     logic_adapters=[
                    {
                        "import_path": "chatterbot.logic.BestMatch",
                        "statement_comparison_function": levenshtein_distance,
                        "response_selection_method": get_first_response
                    }],
                    filters=[filters.get_recent_repeated_responses],
                     storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
                     database_uri='mongodb://localhost:27017/9fa-chatterbot'

                    )



# #                  logic_adapters=['chatterbot.logic.MathematicalEvaluation',
#                                  'chatterbot.logic.BestMatch'],

# small_talk = ['hi there!',
#               'hi!',
#               'how do you dooooo?',
コード例 #50
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

bot = ChatBot('SQLMemoryTerminal',
              storage_adapter='chatterbot.storage.SQLStorageAdapter',
              logic_adapters=[{
                  "import_path": "chatterbot.logic.BestMatch",
                  'default_response': 'chatterbot failed'
              }],
              database_uri='sqlite:///chatterbot_database.db',
              read_only=True)


def train(filename):

    f = open(filename, "r", encoding="utf-8")
    corpus = []
    for line in f:
        if line.strip(
        ) == "*****************************************************************************************************":
            break
        corpus.append(line.strip())

    samples = []
    for i in range(0, len(corpus) - 1, 2):
        dialog = []
        dialog.append(corpus[i])
        dialog.append(corpus[i + 1])
        samples.append(dialog)

    trainer = ListTrainer(bot)
コード例 #51
0
        lines = csv.reader(g)
        for line in lines:
            lineCount += 1
            if lineCount > 1:
                f.write("\r\n- - " + line[0])
                f.write("\r\n  - " + line[1])

print("I have successfully imported " + str(lineCount) + " rows of info and will now retrain...")

if os.path.exists("botData.sqlite3"):
    os.remove("botData.sqlite3")
    print("Clearing my old training data.")

bot = ChatBot(
    "Chat Bot",
    storage_adapter="chatterbot.storage.SQLStorageAdapter",
    database="botData.sqlite3"
)

#You can comment these out for production later since you won't be training everytime:
bot.set_trainer(ChatterBotCorpusTrainer)
bot.train("data/trainingdata.yml")

print('##################################################')
print("I am all trained up and ready to chat!")
print("If on PythonAnywhere, run this command: cp botData.sqlite3 ../botData.sqlite3")
print('##################################################')

print('Shall I delete the recent conversation logs?')
userConfirm = input('Press y or n: ')
コード例 #52
0
import time
import telepot
from telepot.loop import MessageLoop
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot

tbot = telepot.Bot(
    "AQUI VAI O SEU TOKEN DO @FATHERBOT DO TELEGRAM"
)  #cria o bot responsável por enviar e receber as mensagens do telegram.

bot = ChatBot(
    'Bot Inteligente'
)  #cria o segundo bot responsável por realizar o aprendizado de maquina.

conversa = [
    'Oi', 'Olá', 'Tudo bem?', 'Tudo ótimo', 'Você gosta de programar?',
    'Sim, eu programo em Python'
]  #vetor responsável por orientar o bot nas suas primeiras conversas.

trainer = ListTrainer(bot)
#bot.set_trainer(ListTrainer)
trainer.train(conversa)
#bot.train(conversa)

msgPadrao = False  #variavel responsavel por verificar se enviou a mensagem padrão ou Não


def handle(
    msg
):  #funcao responsavel por receber a mensagem do telegram e responder ao usuário.
    global msgPadrao  #define a variavel msgPadrao como global para ser utilizada dentro desse escopo
コード例 #53
0
ファイル: jarvis.py プロジェクト: mdietterle/aulas
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot

import speech_recognition as sr

import pyttsx3
import pyaudio

bot = ChatBot('Jarvis')
speak = pyttsx3.init('sapi5')


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


chats = ["hi", "hello", "I'm fine", "thanks", "I'm Jarvis", "the future"]

bot.set_trainer(ListTrainer)
bot.train(chats)

r = sr.Recognizer()

with sr.Microphone() as s:
    r.adjust_for_ambient_noise(s)

    while True:
        try:
            print("Diga alguma coisa...")
            audio = r.listen(s)
コード例 #54
0
def post_facebook_message(fbid, recevied_message):
    jerry = ChatBot("jerry",
                    storage_adapter="chatterbot.storage.SQLStorageAdapter",
                    database=os.path.join(settings.BASE_DIR,
                                          'fb_Chatbot/chat/test'))
    jerry.set_trainer(ChatterBotCorpusTrainer)
    jerry.train(
        "C:\\Users\\MA303\\Desktop\\Chatbot\\fb_Chatbot\\chat\\jerry_DB.json")
    # C:\Users\MA303\Desktop\Chatbot\fb_Chatbot\chat
    tokens = re.sub(r"[^a-zA-Z0-9\s]", ' ', recevied_message).lower().split()
    joke_text = ''
    # print (recevied_message)
    # print (type (recevied_message))
    # print (tokens)
    # print (type (tokens))
    y = jerry.get_response(recevied_message)
    y = HanziConv.toTraditional(y.text)
    print(y)
    joke_text = y
    user_details_url = "https://graph.facebook.com/v2.6/%s" % fbid
    user_details_params = {
        'fields': 'first_name,last_name,profile_pic',
        'access_token': PAGE_ACCESS_TOKEN
    }
    user_details = requests.get(user_details_url, user_details_params).json()
    joke_text = 'Yo ..! ' + joke_text
    post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=%s' % PAGE_ACCESS_TOKEN
    # global listlocation_find
    # global listtoolong_find
    # global list1
    # global listtoolong
    # for i in range(4):
    #     print (listlocation_find)
    #     listlocation_find = recevied_message.find(list1[i])
    #     print("after==")
    #     print (listlocation_find)
    #     if listlocation_find >= 0 :
    #         for r in range(5):
    #             listtoolong_find = recevied_message.find(listtoolong[r])
    #             if listtoolong_find >= 0:
    #                 l = listtoolong_find +1
    #                 recevied_message = recevied_message[:listtoolong_find] + recevied_message[l:]
    #                 print(recevied_message)
    #         response_msg = json.dumps({"recipient":{"id":fbid},"message":{"text":"https://www.google.com.tw/maps/search/"+recevied_message,}})
    #         status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg)
    #         pprint(status.json())
    str = recevied_message
    ans = 0
    for h in range(toolong):
        if str.find(dict["toolong"][h]) >= 0:
            dle = str.find(dict["toolong"][h])
            dle_long = len(dict["toolong"][h])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
    for i in range(a):
        if str.find(dict["toilet"][i]) >= 0 and ans <= 0:
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": "您附近的廁所有以下這些"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            ans = ans + 1
    for i10 in range(a10):
        if str.find(dict["乘車"][i10]) >= 0 and ans <= 0:
            dle = str.find(dict["乘車"][i10])
            dle_long = len(dict["乘車"][i10])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": "以下是" + str + "的交通資訊"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            ans = ans + 1
    for i11 in range(a11):
        if str.find(dict["價錢"][i11]) >= 0 and ans <= 0:
            dle = str.find(dict["價錢"][i11])
            dle_long = len(dict["價錢"][i11])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": "以下是" + str + "的價錢資訊"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            ans = ans + 1
    for i2 in range(a2):
        if str.find(dict["location"][i2]) >= 0 and ans <= 0:
            dle = str.find(dict["location"][i2])
            dle_long = len(dict["location"][i2])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": "以下是" + str + "的位置資訊"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            print("https://www.google.com.tw/maps/search/" + str)
            ans = ans + 1
    for i3 in range(a3):
        if str.find(dict["營業時間"][i3]) >= 0 and ans <= 0:
            dle = str.find(dict["營業時間"][i3])
            dle_long = len(dict["營業時間"][i3])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": str + "的營業時間是"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            ans = ans + 1
    for i4 in range(a4):
        if str.find(dict["電話"][i4]) >= 0 and ans <= 0:
            dle = str.find(dict["電話"][i4])
            dle_long = len(dict["電話"][i4])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": str + "的電話是"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            ans = ans + 1
    for i5 in range(a5):
        if str.find(dict["介紹"][i5]) >= 0 and ans <= 0:
            dle = str.find(dict["介紹"][i5])
            dle_long = len(dict["介紹"][i5])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": "以下是" + str + "的相關資訊"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            ans = ans + 1
    for i6 in range(a6):
        if str.find(dict["wifi"][i6]) >= 0 and ans <= 0:
            dle = str.find(dict["wifi"][i6])
            dle_long = len(dict["wifi"][i6])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": "以下是" + str + "的wifi資訊"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            ans = ans + 1

    for i7 in range(a7):
        if str.find(dict["菜單"][i7]) >= 0 and ans <= 0:
            dle = str.find(dict["菜單"][i7])
            dle_long = len(dict["菜單"][i7])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": "以下是" + str + "的菜單資訊"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            ans = ans + 1
    for i8 in range(a8):
        if str.find(dict["評價"][i8]) >= 0 and ans <= 0:
            dle = str.find(dict["評價"][i8])
            dle_long = len(dict["評價"][i8])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": "以下是" + str + "的評價資訊"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            ans = ans + 1
    for i9 in range(a9):
        if str.find(dict["充電"][i9]) >= 0 and ans <= 0:
            dle = str.find(dict["充電"][i9])
            dle_long = len(dict["充電"][i9])
            dle2 = dle + dle_long
            str = str[:dle] + str[dle2:]
            response_msg = json.dumps({
                "recipient": {
                    "id": fbid
                },
                "message": {
                    "text": "以下是充電資訊"
                }
            })
            status = requests.post(
                post_message_url,
                headers={"Content-Type": "application/json"},
                data=response_msg)
            ans = ans + 1

    print(str)
    if recevied_message == "查詢google圖片" and ans <= 0:
        response_msg = json.dumps({
            "recipient": {
                "id": fbid
            },
            "message": {
                "text": "以下是您搜尋的地點"
            }
        })
        status = requests.post(post_message_url,
                               headers={"Content-Type": "application/json"},
                               data=response_msg)
        post_facebook_image(fbid)
        ans = ans + 1
    # if recevied_message == "旅遊" and ans<=0:
    #     response_msg = json.dumps({"recipient":{"id":fbid},"message":{
    #         "text":"旅遊選擇如下",
    #         "quick_replies":[
    #             {
    #                 "content_type":"text",
    #                 "title":"台北",
    #                 "payload":"<PICK_TPE>"
    #             },
    #             {
    #                 "content_type":"text",
    #                 "title":"宜蘭",
    #                 "payload":"<PICK_IL>"
    #             },
    #             {
    #                 "content_type":"location"
    #             }

    #             ]}})
    #     status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg)
    #     pprint(status.json())
    #     ans=ans+1
    if ans <= 0:
        response_msg = json.dumps({
            "recipient": {
                "id": fbid
            },
            "message": {
                "text": joke_text,
            }
        })
        status = requests.post(post_message_url,
                               headers={"Content-Type": "application/json"},
                               data=response_msg)
        pprint(status.json())
コード例 #55
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

import os

arr = os.listdir("data")

try:
	os.remove("db.sqlite3")
	os.remove("db.sqlite3-shm")
	os.remove("db.sqlite3-wal")
except:
	print("some thing went wrong")
chatbot = ChatBot('buddy',
	logic_adapters=[
        "chatterbot.logic.BestMatch",
		"chatterbot.logic.MathematicalEvaluation"
    ]
)
trainer = ListTrainer(chatbot)
for i in arr:
	file=open('data/'+i, 'r').readlines();
	#trainer.train('chatterbot.corpus.english')
	trainer.train(file)

while True:

	
	#req=input("Enter:");
	print(req);
	if req=="Could not understand please try again":
	
コード例 #56
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('Ron Obvious')
trainer = ChatterBotCorpusTrainer(chatbot)

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

chatbot.get_response("Hello, how are you doing?")

while True:
    request = input('You: ')
    response = chatbot.get_response(request)

    print('Bot: ', response)
コード例 #57
0
ファイル: socket-server.py プロジェクト: gustavoghp87/chatbot
import socket
from decouple import config
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer
import pandas as pd

HOST = '127.0.0.1'
PORT = int(config("PORT"))

bot = ChatBot(
    'MaslaChat',  
    logic_adapters = ['chatterbot.logic.BestMatch']
)

trainer = ListTrainer(bot)
data = pd.read_excel('frases.xlsx')
list = []

for i in data.index:
    try:
        clave = str(data['clave'][i])
        frase = str(data['frase'][i])
        print(i)
        if clave!='nan':
            list.append(clave)
            list.append(clave)
            print(clave)
        list.append(frase)
        list.append(frase)
        print(frase)
コード例 #58
0
import pandas as pd
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

data = pd.read_csv('conversation_data.csv', usecols=['text'], skiprows=[1])
chatbot = ChatBot('shopping Bot')
trainer = ListTrainer(chatbot)

#test = list(data)
#print(data[:5])
#print(type(data))
#print(test)

newData = data['text'].values.tolist()
#print(newData[:10])

trainer.train(newData)

while True:
    user_input = input("You:")
    if user_input.lower() == 'bye':
        break
    else:
        bot_response = chatbot.get_response(user_input)
        print("ChatBot:", bot_response)
コード例 #59
0
def home(request):
    if request.method == "POST":
        query = request.POST['query']
        #----------------------------chatbot Part--------------------------------#
        #---------------------file training on dataset---------------------------#
        """For training the module according to required json file must be kept in your system 
        in the directory chatterbot_corpus\data\(language you want to train in)
        training file is availabe in staic/chatbot_traing just place it in above mention directory"""

        # chatbot = ChatBot(
        #         "Terminal",
        #         trainer='chatterbot.trainers.ChatterBotCorpusTrainer')

        # chatbot.train("chatterbot.corpus.english.module")
        # chatbot.train("chatterbot.corpus.english.greetings")

        #------------------------------------------------------------------------#
        input_statement = statement(query)
        print("input statement", input_statement)

        chatbot = ChatBot(
            "Terminal",
            storage_adapter="chatterbot.storage.JsonFileStorageAdapter",
            logic_adapters=[
                {
                    'import_path': 'chatterbot.logic.BestMatch'
                },
                {
                    'import_path': 'chatterbot.logic.SpecificResponseAdapter',
                    'input_text': 'Help me',
                    'output_text': 'Ok, go to sample queries'
                },
                {
                    '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",
            database="database.db")
        bot_output = chatbot.get_response(input_statement)
        print("##########################bot_output", bot_output)
        if bot_output == "top":
            column_list_length = (query_and_nlp(bot_output, query))
            if (column_list_length == 2):
                return redirect('/graph_bar_2')

            elif (column_list_length == 3):
                return redirect('/graph_bar_3')

            else:
                return redirect('/error_page')
        elif bot_output == "bottom":
            column_list_length = (query_and_nlp(bot_output, query))
            if (column_list_length == 2):
                return redirect('/graph_bar_2')

            elif (column_list_length == 3):
                return redirect('/graph_bar_3')

            else:
                return redirect('/error_page')
        elif bot_output == "trend":
            column_list_length = (query_and_nlp(bot_output, query))
            if (column_list_length == 2):
                return redirect('/trend_2')

            elif (column_list_length == 3):
                return redirect('/trend_3')
        elif bot_output == "segment":
            column_list_length = query_and_nlp(bot_output, query)
            return redirect('/segment')
        else:
            print(bot_output)
            return render(request, 'index.html', {
                "bot_output": bot_output,
                "input_statement": input_statement
            })
        print(bot_output)

    else:
        with open(os.path.join(base_dir,
                               "search/static/data/finaldataset.csv"),
                  newline='') as f:
            df = pd.read_csv(f)
            columns = df.columns
            list1 = []
            for i in range(len(columns)):
                list1.append(columns[i])
        list2 = [
            "for 12359", "for 12408", "for 12562", "for 12683", "for 12783",
            "for 12955", "for 13588", "for 14261", "for 15532", "for 16549",
            "for 16918", "for 17511", "top", "products by margin",
            "products by reverue", "products by location",
            "of DOLLY GIRL BEAKER", "of NINE DRAWER OFFICE TIDY",
            "of RED SPOT GIFT BAG LARGE", "of OVAL WALL MIRROR DIAMANTE",
            "of DOLLY BOY BEAKER", "of 4 PURPLE FLOCK DINNER CANDLES",
            "of 5 PURPLE FLOCK DINNER CANDLES",
            "of SQUARE WALL MIRROR DIAMANTE", "of DOLLY MEN BEAKER",
            "of DOLLY WOMEN BEAKER", "of YELLOW SPOT GIFT BAG LARGE",
            "of I LOVE LONDON MAXI BACKPACK", "buys RED SPOT GIFT BAG LARGE",
            "buys OVAL WALL MIRROR DIAMANTE", "buys DOLLY BOY BEAKER",
            "buys 4 PURPLE FLOCK DINNER CANDLES",
            "buys 5 PURPLE FLOCK DINNER CANDLES",
            "buys SQUARE WALL MIRROR DIAMANTE", "buys DOLLY MEN BEAKER",
            "buys DOLLY WOMEN BEAKER", "buys YELLOW SPOT GIFT BAG LARGE"
        ]
        list = list1 + list2
        return render(request, 'index.html', {'list': list})
コード例 #60
-2
class DataCachingTests(TestCase):

    def setUp(self):
        self.test_data_directory = 'test_data'
        self.test_database_name = self.random_string() + ".db"

        if not os.path.exists(self.test_data_directory):
            os.makedirs(self.test_data_directory)

        database_path = os.path.join(
            self.test_data_directory,
            self.test_database_name
        )

        self.chatbot = ChatBot(
            "Test Bot",
            io_adapter="chatterbot.adapters.io.NoOutputAdapter",
            logic_adapter="tests.logic_adapter_tests.test_data_cache.DummyMutatorLogicAdapter",
            database=database_path
        )

        self.chatbot.train([
            "Hello",
            "How are you?"
        ])

    def random_string(self, start=0, end=9000):
        """
        Generate a string based on a random number.
        """
        from random import randint
        return str(randint(start, end))

    def remove_data(self):
        import shutil

        if os.path.exists(self.test_data_directory):
            shutil.rmtree(self.test_data_directory)

    def tearDown(self):
        """
        Remove the test database.
        """
        self.chatbot.storage.drop()
        self.remove_data()

    def test_additional_attributes_saved(self):
        """
        Test that an additional data attribute can be added to the statement
        and that this attribute is saved.
        """
        response = self.chatbot.get_response("Hello")
        found_statement = self.chatbot.storage.find("Hello")

        self.assertIsNotNone(found_statement)
        self.assertIn("pos_tags", found_statement.serialize())
        self.assertEqual(
            "NN",
            found_statement.serialize()["pos_tags"]
        )