class ChatterBotCorpusTrainingTestCase(ChatterBotTestCase):
    """
    Test case for training with data from the ChatterBot Corpus.

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

    def setUp(self):
        super().setUp()

        self.trainer = ChatterBotCorpusTrainer(
            self.chatbot,
            show_training_progress=False
        )

    def tearDown(self):
        super().tearDown()
        self.chatbot.storage.drop()

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

        results = list(self.chatbot.storage.filter(text='Hello'))

        self.assertGreater(len(results), 1)

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

        results = list(self.chatbot.storage.filter(text='Hello'))

        self.assertGreater(len(results), 1)
        statement = results[0]
        self.assertEqual(['greetings'], statement.get_tags())

    def test_train_with_multiple_corpora(self):
        self.trainer.train(
            'chatterbot.corpus.english.greetings',
            'chatterbot.corpus.english.conversations',
        )
        results = list(self.chatbot.storage.filter(text='Hello'))

        self.assertGreater(len(results), 1)

    def test_train_with_english_corpus(self):
        self.trainer.train('chatterbot.corpus.english')
        results = list(self.chatbot.storage.filter(text='Hello'))

        self.assertGreater(len(results), 1)
Exemple #2
0
def action():
    conversation=[
        "hello",
        "Hi there!",
        "How are you doing",
        "I am doing great",
        "That is good to hear",
        "Thank you"
        ]
    chatbot=ChatBot("Bisp")

    trainer = ChatterBotCorpusTrainer(chatbot)

    trainer.train(
        "chatterbot.corpus.english.greetings",
        "chatterbot.corpus.english.conversations"
    )
    apiemp='http://127.0.0.1:5000'
    jsonemp=requests.get(apiemp).json()
    api_address='https://api.openweathermap.org/data/2.5/weather?appid=6e47f682a6c6a11adaf2df87a1812a96&q=Jamshedpur'
    json_data=requests.get(api_address).json()
    f=json_data['main']['temp']

    t=(f-272.15)
    f1=json_data['weather'][0]['main']
    f2=json_data['weather'][0]['description']
    x=[]
    column=["Id","First Name","Middle Name","Last Name","Address","Email","Mobile Number","Vehicle","Vehicle Number"]

    colum=["id","fn","mn","ln","address","Email","Mobile","Vehicle","Vehicle_Number"]

    window = Tk()
    window.title("Amps")
    window.configure(background='black')
    
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    window.geometry("500x500+{0}+{1}".format(screen_width-500, screen_height-570))
    


    messages = Text(window,background='lightgreen')
    messages.pack()
    messages.tag_config('amps',foreground="blue")
    messages.tag_config('you',foreground="red")
    input_user = StringVar()
    input_field = Entry(window, text=input_user,font=(None,20),background='lightblue')
    input_field.insert(0,'Type something here')
    input_field.pack(side=BOTTOM, fill=X)
    label=Label(window,text="Amps : Type information if you want to rummage through the database",height="20",background='lightyellow')
    label.pack()
    def Enter_pressed(event):
        userInput = input_field.get()
        messages.insert(INSERT, 'You:%s\n' % userInput,'you')
        input_user.set('')
        

        messages.see(END)
        if userInput.strip()=='bye' or userInput.strip()=='goodbye':
            messages.insert(INSERT, 'Amps:Bye\n','amps')
            messages.see(END)
            exit
        elif('weather' in userInput.strip()):
            messages.insert(INSERT, "The weather is "+f1+" and described as "+f2+"\n",'amps')
            messages.see(END)
        elif('temperature' in userInput.strip()):
            messages.insert(INSERT, "The temperature is "+str(t)+"\n",'amps')
            messages.see(END)
        elif('information' in userInput.strip()):
            messages.insert(INSERT, "Give me something to work with:\n",'amps')
            messages.insert(INSERT, "1 for Full Name\n2 for ID\n3 for Email\n4 for Mobile Number\n5 for Vehicle\n6 for Vehicle Number\n",'amps')
            messages.see(END)
            ch=int(easygui.enterbox("Your Choice?"))
            c=[]
            if(ch==1):
                messages.insert(INSERT, "Enter the full name:\n",'amps')
                messages.see(END)
                
                names=easygui.enterbox("Enter full name").split()
                
                
                for i in range(len(jsonemp["myCollection"])):
                    if(jsonemp["myCollection"][i]["fn"]==names[0] and jsonemp["myCollection"][i]["mn"]==names[1] and jsonemp["myCollection"][i]["ln"]==names[2]):
                        
                        z={}
                        for j in range(len(column)):
                            z[colum[j].lower()]=jsonemp["myCollection"][i][colum[j].lower()]
                        c.append(z)
            elif(ch==2):
                messages.insert(INSERT,"Enter id:\n",'amps')
                messages.see(END)
                
                name=int(easygui.enterbox("Enter ID"))
                for i in range(len(jsonemp["myCollection"])):
                    if(jsonemp["myCollection"][i]["id"]==name):
                        
                        z={}
                        for j in range(len(column)):
                            z[colum[j].lower()]=jsonemp["myCollection"][i][colum[j].lower()]
                        c.append(z)
            elif(ch==3):
                messages.insert(INSERT,"Enter Email:\n",'amps')
                messages.see(END)
                
                name=easygui.enterbox("Enter Email")
                for i in range(len(jsonemp["myCollection"])):
                    if(jsonemp["myCollection"][i]["email"]==name):
                        
                        z={}
                        for j in range(len(column)):
                            z[colum[j].lower()]=jsonemp["myCollection"][i][colum[j].lower()]
                        c.append(z)
            elif(ch==4):
                messages.insert(INSERT,"Enter Mobile Number:\n",'amps')
                messages.see(END)
                
                name=easygui.enterbox("Enter Mobile Number")
                for i in range(len(jsonemp["myCollection"])):
                    if(jsonemp["myCollection"][i]["mobile"]==name):
                        
                        z={}
                        for j in range(len(column)):
                            z[colum[j].lower()]=jsonemp["myCollection"][i][colum[j].lower()]
                        c.append(z)
            elif(ch==5):
                messages.insert(INSERT,"Enter Vehicle:\n",'amps')
                messages.see(END)
                
                name=easygui.enterbox("Enter Vehicle Name")
                for i in range(len(jsonemp["myCollection"])):
                    if(jsonemp["myCollection"][i]["vehicle"]==name):
                        
                        z={}
                        for j in range(len(column)):
                            z[colum[j].lower()]=jsonemp["myCollection"][i][colum[j].lower()]
                        c.append(z)
            elif(ch==6):
                messages.insert(INSERT,"Enter Vehicle Number:\n",'amps')
                messages.see(END)
                
                name=easygui.enterbox("Enter Vehicle Number")
                for i in range(len(jsonemp["myCollection"])):
                    if(jsonemp["myCollection"][i]["vehicle_number"]==name):
                        
                        z={}
                        for j in range(len(column)):
                            z[colum[j].lower()]=jsonemp["myCollection"][i][colum[j].lower()]
                        c.append(z)
            messages.insert(INSERT,"These are the results I found.\n",'amps')
            messages.see(END)
            
            for i in range(len(c)):
                messages.insert(INSERT,"%s" % c[i]["id"]+" "+c[i]["fn"]+" "+c[i]["ln"]+"\n")
                messages.see(END)
            messages.insert(INSERT,"Enter the id of the person : \n",'amps')
            messages.see(END)
            id=int(easygui.enterbox("Enter ID of the person you want details on"))
            for i in range(len(c)):
                if(c[i]["id"]==id):
                    for j in range(len(column)):
                        messages.insert(INSERT,"%s" % column[j]+" : "+str(c[i][colum[j].lower()])+"\n")
                        messages.see(END)
            messages.see(END)
        else:
            response=chatbot.get_response(userInput)
            messages.configure(foreground='red')
            messages.insert(INSERT,'Amps: %s\n' % response,'amps')
            messages.see(END)

        return "break"

    frame = Frame(window,background="black")  # , width=300, height=300)
    input_field.bind("<Return>", Enter_pressed)
    frame.pack()

    window.mainloop()
Exemple #3
0
from flask import Flask, render_template, request, jsonify, Response, make_response
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

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

trainer.train("chatterbot.corpus.english")
trainer.train("chatterbot.corpus.english.greetings",
              "chatterbot.corpus.english.conversations")


@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))


@app.route("/api/chat", methods=['post'])
def respond():
    data = request.json
Exemple #4
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('Charlie')
trainer = ChatterBotCorpusTrainer(chatbot)

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

while True:
    try:
        user_input = input()

        bot_response = chatbot.get_response(user_input)

        print(bot_response)

    except (KeyboardInterrupt, EOFError, SystemExit):
        break
# -*- coding: utf-8 -*-
"""
Created on Thu May  7 19:06:42 2020

@author: SheilaCarolina
"""
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

dhory = ChatBot("Dhory")
trainer = ChatterBotCorpusTrainer(dhory)

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

resposta = dhory.get_response("Perfeito")
print("Dhory: ", resposta)
Exemple #6
0
from chatterbot import ChatBot
#from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer

bot = ChatBot('Project1')

trainer = ChatterBotCorpusTrainer(bot)
#response=['How are you?','My name is Bot,I am created by Shubham.','I speak in Binary.',
#    'I live in a Memory.','I am fine.','In which city do you live ?.','What is your name?.',
#    'Nice to meet you.','Sorry I cant understand.','How can I help?.','hey, good to see you.', 'How may i assist you today?.',
#    'I am good.','Let us know about each other.','Yea sure, so what you wanna talk.','Whats your favourite food?.',
#    'That is good to hear.','What are your Hobbies?.','Nice.',
#    'Thank you.',
#    'You are welcome.','Bye.']

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

trainer.export_for_training('./my_export.json')

print("Welcome to Project1 Bot")
while True:
    ask_bot = input()
    if ask_bot == 'Bye':
        break
    answer = bot.get_response(ask_bot)
    print("Bot:", answer)
Exemple #7
0
trainer.train(
    # "chatterbot.corpus.english.greetings",
    # "chatterbot.corpus.english.ai",
    # "chatterbot.corpus.english.computers",
    # "chatterbot.corpus.english.conversations",
    # "chatterbot.corpus.english.emotion",
    # "chatterbot.corpus.english.food",
    # "chatterbot.corpus.english.gossip",
    # "chatterbot.corpus.english.history",
    # "chatterbot.corpus.english.humor",
    # "chatterbot.corpus.english.health",
    # "chatterbot.corpus.bangla.botprofile",
    # "chatterbot.corpus.bangla.computer",
    # "chatterbot.corpus.bangla.emotions",
    # "chatterbot.corpus.bangla.greetings",
    # "chatterbot.corpus.buses.route3",
    # "chatterbot.corpus.buses.basic_answer",
    # # "chatterbot.corpus.buses.broute",
    # "chatterbot.corpus.english.conversations",

    # "chatterbot.corpus.route3",
    # "chatterbot.corpus.banglaroute",
    "chatterbot.corpus.buses.route3",
    "chatterbot.corpus.buses.basic",
    "chatterbot.corpus.english.greetings",
    "chatterbot.corpus.english.conversations",
    "chatterbot.corpus.english.ai",
    "chatterbot.corpus.english.botprofile",
    "chatterbot.corpus.english.computers",
    "chatterbot.corpus.english.emotion",
    "chatterbot.corpus.english.food",
    "chatterbot.corpus.english.gossip",
    "chatterbot.corpus.english.health",
    "chatterbot.corpus.english.history",
    "chatterbot.corpus.english.humor",
    "chatterbot.corpus.english.literature",
    "chatterbot.corpus.english.money",
    "chatterbot.corpus.english.movies",
    "chatterbot.corpus.english.politics",
    "chatterbot.corpus.english.psychology",
    "chatterbot.corpus.english.science",
    "chatterbot.corpus.english.sports",
    "chatterbot.corpus.english.trivia",
    "chatterbot.corpus.bangla.botprofile",
    "chatterbot.corpus.bangla.greetings",
    "chatterbot.corpus.bangla.emotions",
    "chatterbot.corpus.bangla.computer",
    # "chatterbot.corpus.thai.greeting",
    # "chatterbot.corpus.telugu.conversations",
    # "chatterbot.corpus.tchinese.ai",
    # "chatterbot.corpus.tchinese.botprofile",
    # "chatterbot.corpus.tchinese.conversations",
    # "chatterbot.corpus.tchinese.emotion",
    # "chatterbot.corpus.tchinese.food",
    # "chatterbot.corpus.tchinese.gossip",
    # "chatterbot.corpus.tchinese.greetings",
    # "chatterbot.corpus.tchinese.history",
    # "chatterbot.corpus.tchinese.humor",
    # "chatterbot.corpus.tchinese.literature",
    # "chatterbot.corpus.tchinese.money",
    # "chatterbot.corpus.tchinese.movies",
    # "chatterbot.corpus.tchinese.politics",
    # "chatterbot.corpus.tchinese.psychology",
    # "chatterbot.corpus.tchinese.science",
    # "chatterbot.corpus.tchinese.sports",
    # "chatterbot.corpus.tchinese.trivia",
    # "chatterbot.corpus.swedish.ai",
    # "chatterbot.corpus.swedish.conversations",
    # "chatterbot.corpus.swedish.food",
    # "chatterbot.corpus.swedish.greetings",
    # "chatterbot.corpus.swedish.sports",
    # "chatterbot.corpus.spanish.conversations",
    # "chatterbot.corpus.spanish.greetings",
    # "chatterbot.corpus.spanish.trivia",
    # "chatterbot.corpus.russian.conversations",
    # "chatterbot.corpus.portuguese.compliment",
    # "chatterbot.corpus.portuguese.conversations",
    # "chatterbot.corpus.portuguese.greetings",
    # "chatterbot.corpus.portuguese.linguistic_knowledge",
    # "chatterbot.corpus.portuguese.proverbs",
    # "chatterbot.corpus.portuguese.suggestions",
    # "chatterbot.corpus.portuguese.trivia",
    # "chatterbot.corpus.portuguese.unilab",
    # "chatterbot.corpus.odia.conversations",
    # "chatterbot.corpus.odia.greetings",
    # "chatterbot.corpus.marathi.conversations",
    # "chatterbot.corpus.marathi.greetings",
    # "chatterbot.corpus.italian.conversations",
    # "chatterbot.corpus.italian.greetings",
    # "chatterbot.corpus.italian.trivia",
    # "chatterbot.corpus.indonesia.conversations",
    # "chatterbot.corpus.indonesia.greetings",
    # "chatterbot.corpus.indonesia.trivia",
    # "chatterbot.corpus.hindi.coversations",
    # "chatterbot.corpus.hindi.greetings",
    # "chatterbot.corpus.hebrew.botprofile",
    # "chatterbot.corpus.hebrew.conversations",
    # "chatterbot.corpus.hebrew.greetings",
    # "chatterbot.corpus.german.greetings",
    # "chatterbot.corpus.german.conversations",
    # "chatterbot.corpus.french.botprofile",
    # "chatterbot.corpus.french.conversations",
    # "chatterbot.corpus.french.food",
    # "chatterbot.corpus.french.greetings",
    # "chatterbot.corpus.french.trivia",
    "chatterbot.corpus.custom.myown",
)
Exemple #8
0
def train_on_corpuses():
    trainer = ChatterBotCorpusTrainer(bot)
    trainer.train(*CORPUSES)
Exemple #9
0
class Chatty:
    def __init__(self):
        self.train_data_path = 'custom_corpus/'
        self.default_response = "I don't understand you :( Try to improve me with adding your dialogue"
        train = self.is_need_to_train()
        self.bot = ChatBot('Chatty', default_response=self.default_response)
        if train:
            self.train()

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

    def train(self):
        self.trainer = ChatterBotCorpusTrainer(self.bot)
        self.trainer.train(self.train_data_path)

    def add_dialogue(self, dialogue, category="undefined"):
        file_path = os.getcwd(
        ) + '/' + self.train_data_path + category + '.yml'
        data = self.read_to_dict(file_path) if os.path.exists(
            file_path) else self.create_new_category(category)
        self.add(data, dialogue)
        self.write(data, file_path)

    def create_new_category(self, category):
        res = {}
        res['categories'] = [category]
        res['conversations'] = []
        return res

    def read_to_dict(self, file_path):
        res = {}
        with open(file_path, 'r') as f:
            lines = f.readlines()
            categories = False
            conversations = False
            for line in lines:
                replica = line[4:-1]
                if 'categories' in line:
                    res['categories'] = []
                    categories = True
                    conversations = False
                elif 'conversations' in line:
                    res['conversations'] = []
                    categories = False
                    conversations = True
                elif conversations and '- - ' in line:
                    res['conversations'].append([replica])
                elif conversations and '- ' in line:
                    res['conversations'][-1].append(replica)
                elif categories and '- ' in line:
                    res['categories'].append(line[2:-1])
        return res

    def write(self, data, file_path):
        with open(file_path, 'w') as f:
            f.write('categories:')
            for category in data['categories']:
                f.write('\n- ' + category)
            f.write('\nconversations: ')
            for conv in data['conversations']:
                f.write("\n- - " + conv[0])
                for replica in conv[1:]:
                    f.write("\n  - " + replica)
            f.write('\n')

    def add(self, data, dialogue):
        conversations = data['conversations']
        if len(conversations) != 0:
            for conv in conversations:
                if dialogue != conv:
                    conversations.append(dialogue)
        else:
            conversations.append(dialogue)

    def is_need_to_train(self):
        db_path = os.getcwd() + '/db.sqlite3'
        return not os.path.exists(db_path)
Exemple #10
0
#!/usr/bin/env python

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
import logging

logging.basicConfig(level=logging.DEBUG)

chatbot = ChatBot('Terminal',
                  storage_adapter='chatterbot.storage.SQLStorageAdapter',
                  trainer='chatterbot.trainers.ListTrainer',
                  database_uri='sqlite:///database.db')

trainer = ChatterBotCorpusTrainer(chatbot)

trainer.train(
    './chatterbot_corpus/data/mr_robot/s01/',
    './chatterbot_corpus/data/mr_robot/s02/',
    './chatterbot_corpus/data/mr_robot/s03/',
    './chatterbot_corpus/data/mr_robot/s04/',
    # "./export.json",
    'chatterbot.corpus.english',
)
Exemple #11
0
responses_ar = answer_ar
response_contexts_ar = context_ar

# Create response embeddings
response_encodings_ar = module.signatures['response_encoder'](
    input=tf.constant(responses_ar),
    context=tf.constant(response_contexts_ar))['outputs']

chatbot = ChatBot('Amal')

# Create a new trainer for the chatbot
trainer = ChatterBotCorpusTrainer(chatbot)

# Train the chatbot based on the english corpus
#trainer.train("chatterbot.corpus.english")
trainer.train("chatterbot.corpus.english.covid19")

app = Flask(__name__)
#CORS(app)
#Cross Origin
#cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
CORS(app,
     headers=(
         'x-requested-with',
         'content-type',
         'accept',
         'origin',
         'authorization',
         'x-csrftoken',
         'withcredentials',
         'cache-control',
Exemple #12
0
from flask import request
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer

bot = ChatBot("Kona")
#
trainer = ChatterBotCorpusTrainer(bot)
trainer = ListTrainer(bot)

trainer.train(["Hi", "Hello"])
trainer.train(["How are you?", "Good."])

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


def getChat(request):
    chatMessage = str(request.args.get('chat'))
    botResponse = str(bot.get_response(chatMessage))
    if botResponse:
        response, code = {"message": botResponse}, 200
    else:
        response, code = {"message": "No Response"}, 400
    return response, code
Exemple #13
0
# ChatterBot Initialization
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

bot = ChatBot('ttd', database_uri=f'sqlite:///data/db/chatbot.sqlite3')

trainer = ChatterBotCorpusTrainer(bot)

trainer.train(f'./data/training/default')
Exemple #14
0
              preprocessors=['chatterbot.preprocessors.clean_whitespace'],
              logic_adapter=[{
                  'import_path':
                  "chatterbot.logic.BestMatch",
                  'statement_comparison_function':
                  "chatterbot.comparison.levenshtein_distance",
                  'response_selection_method':
                  "chatterbot.response_selection.get_first_response"
              }, {
                  'import_path': "chatterbot.logic.LowConfidenceAdapter",
                  'threshold': 0.65,
                  'default_response': 'Sorry I do not know that'
              }])

trainer = ChatterBotCorpusTrainer(bot)
trainer.train("data/data.yml")


@app.route("/")
def index():
    return render_template("index.html")  #send context to html


@app.route("/get")
def get_bot_response():
    userText = request.args.get(
        "msg")  #get data from input,we write js  to index.html
    return str(bot.get_response(userText))


if __name__ == "__main__":
Exemple #15
0
			'default_response':'I am sorry, but I do not understand.',
			'maximum_similarity_threshold':0.90
		},
		{
			'import_path':'chatterbot.logic.SpecificResponseAdapter',
			'input_text':'Como te llamas?',
			'output_text':'Mi nombre es ChatBot!'
		}
	],
	database_uri='sqlite:///database.sqlite3'
	) #create the bot


trainer = ChatterBotCorpusTrainer(bot)
trainer.train(
	"chatterbot.corpus.spanish.greetings",
	"chatterbot.corpus.spanish.conversations"
)



@app.route('/chat')
def chat():
	return render_template('chat.html',bot_response="Hola, My nombre es ChatBot, ¿Como puedo ayudarte?")

@app.route('/process',methods=['POST'])
def process():
	user_input=request.form['user_input']

	bot_response=bot.get_response(user_input)
	bot_response=str(bot_response)
	print("ChatBot: "+bot_response)
Exemple #16
0
import logging

from textblob import TextBlob

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

#Starting bot training session

chatbot = ChatBot('bbot')

# Create a new trainer for the chatbot
trainer = ChatterBotCorpusTrainer(chatbot)

# Train the chatbot based on the english corpus
trainer.train("chatterbot.corpus.english")

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

logger = logging.getLogger(__name__)


# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
    """Send a message when the command /start is issued."""
    update.message.reply_text(
        'Hi! Mwonusee \n Iam the offical bot of Beta MH . \n Badaa mwonusee .. namukk chati kalikkadaa :] '
Exemple #17
0

# Train the chatbot based on the english corpus
trainer.train("chatterbot.corpus.chinese")
trainer.train("chatterbot.corpus.english")

# Get a response to an input statement

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


def reply_my_friend(msg):
   print(msg)
   return bot0.get_response(msg.text).text# 使用机器人进行自动回复

print(reply_my_friend('aaa'))
"""
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer
from chatterbot import ChatBot
bot = ChatBot('Sakura', )
trainer = ChatterBotCorpusTrainer(bot)

trainer.train("chatterbot.corpus.chinese")
trainer.train("chatterbot.corpus.english")
trainer2 = ListTrainer(bot)

trainer2.train(["今天天气怎么样", "还不错"])

print(bot.get_response("天气1"))
Exemple #18
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('Training Example')

trainer = ChatterBotCorpusTrainer(chatbot)

trainer.train("../corpus")

while True:
    try:
        user = input("Voce: ")
        response = chatbot.get_response(user)
        print("bot: " + str(response))
        print("confidence: " + str(response.confidence))
    except (KeyboardInterrupt, EOFError, SystemExit):
        break
Exemple #19
0
from chatterbot.trainers import ChatterBotCorpusTrainer
app = Flask(__name__)
#create chatbot
chatbot = ChatBot("Candice",
                  storage_adapter='chatterbot.storage.SQLStorageAdapter',
                  logic_adapters=[
                      'chatterbot.logic.MathematicalEvaluation', {
                          'import_path': 'chatterbot.logic.BestMatch',
                          'default_response':
                          'I am sorry, but I do not understand.',
                          'maximum_similarity_threshold': 0.90
                      }
                  ],
                  database_uri='sqlite:///database.sqlite3')
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train('chatterbot.corpus.english')
trainer.train('chatterbot.corpus.custom.resume')
trainer.train("./resume.yml")
trainer = ListTrainer(chatbot)

trainer.train([
    'How are you?',
    'I am good.',
    'Thank you',
    'You are welcome.',
])
trainer.train(['What is your name', 'My name is Anagha'])


#define app routes
@app.route("/")
Exemple #20
0
from chatbot import chatbot
from chatterbot.trainers import ChatterBotCorpusTrainer

fourTrainer = ChatterBotCorpusTrainer(chatbot)

fourTrainer.train("./knowledge/4.yml")


def brain(input):
    response = chatbot.get_response(input)
    return response
Exemple #21
0
    "Sahithi Madhumitha Rudhira created me!",
    "What all can you do?",
    "I can chat with you in different Languages:English,Telugu,Hindi,etc..to know about the topics type all Topics",
    "all topics",
    "1.AI 2.Bot Profile 3.Computers 4.Conversation 5.Emotion 6.Food 7.Gossip 8.Greetings 9.Health10.History Type'More'",
    "More",
    "11.Humor 12.Literature 13.Money 14.Movies 15.Politics 16.Psychology 17.Science 18.Sports 19.Trivia Type 'Next'",
    "Next",
    "Greetings in Telugu,Greetings in Hindi",
    "Tell me, what can you do? ",
    "My name is Leo. I am a Chat bot!",
])
trainer = ChatterBotCorpusTrainer(bot)
trainer.train("chatterbot.corpus.english")
trainer1 = ChatterBotCorpusTrainer(bot)
trainer1.train("chatterbot.corpus.telugu")
trainer2 = ChatterBotCorpusTrainer(bot)
trainer2.train("chatterbot.corpus.hindi")
trainer3 = ChatterBotCorpusTrainer(bot)
trainer3.train("chatterbot.corpus.bangla")
trainer4 = ChatterBotCorpusTrainer(bot)
trainer4.train("chatterbot.corpus.chinese")
trainer5 = ChatterBotCorpusTrainer(bot)
trainer5.train("chatterbot.corpus.custom")
trainer6 = ChatterBotCorpusTrainer(bot)
trainer6.train("chatterbot.corpus.french")
trainer7 = ChatterBotCorpusTrainer(bot)
trainer7.train("chatterbot.corpus.german")
trainer8 = ChatterBotCorpusTrainer(bot)
trainer8.train("chatterbot.corpus.hebrew")
trainer9 = ChatterBotCorpusTrainer(bot)
Exemple #22
0
chatbot = ChatBot(
    "Gaetan Jonathan",
    logic_adapters=[
        {
            "import_path": "chatterbot.logic.BestMatch",
            "maximum_similarity_threshold" : 0.8,
            "default_response" : "Vous chercher peut être de l'aide\nTaper: gaetan help"
        } 
    ],
)


trainer0 = ChatterBotCorpusTrainer(chatbot)
trainer1 = ListTrainer(chatbot)

trainer0.train('chatterbot.corpus.french.greetings')
trainer0.train('chatterbot.corpus.english.greetings')
trainer1.train([
    "Gaetan",
    "Vous voulez dire 'gaetan'?, \n Tapez gaetan help pour plus d'info sur la commande",
    "Merci",
    "Je vous en prie"
])
trainer1.train([
    "search",
    "Vous vous êtes trompez? \n  taper gaetan help pour plus d'info",
    "Merci beaucoup",
    "De rien"
])

trainer1.train([
Exemple #23
0
from chatterbot import ChatBot  #import the chatbot
from chatterbot.trainers import ChatterBotCorpusTrainer
import os

bot = ChatBot('Bot')
trainer = ChatterBotCorpusTrainer(bot)

corpus_path = 'E:/chatterbot-corpus-master/chatterbot-corpus-master/chatterbot_corpus/data/english/'

for file in os.listdir(corpus_path):
    trainer.train(corpus_path + file)

while True:
    message = input('You:')
    print(message)
    if message.strip() == 'Bye':
        print('ChatBot: Bye')
        break
    else:
        reply = bot.get_response(message)
        print('ChatBot:', reply)
Exemple #24
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('Chatterbot',
                  trainer='chatterbot.trainers.CorpusTrainer',
                  storage_adapter='chatterbot.storage.SQLStorageAdapter',
                  database_uri='sqlite:///database.db')

trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train(
    "chatterbot.corpus.english.botprofile",
    "chatterbot.corpus.english.grocery",
)
Exemple #25
0
    database_uri='sqlite:///database.sqlite3'
    )
    
conversa = ListTrainer(bot)
conversa.train([
   'Oi',
   'Olá',
   'Qual seu nome?',
   'Jamilton',
   'Prazer',
   'O prazer é todo meu',
   'Estou com um problema',
   'Em que posso ajudar?',
   'Quantos anos você tem?',
   'Tenho 1 dia de existência',
   'Tenho que ir',
   'Tudo bem, volte sempre',
   'KKKK',
   'Ri não safado',
])

trainer = ChatterBotCorpusTrainer(bot)
trainer.train('chatterbot.corpus.portuguese')

while True:
  resposta = bot.get_response(input("Usuário: "))
  if float(resposta.confidence) > 0.5:
      print("Jamilton: ", resposta)
  else:
      print("Desculpe, eu não entendi!")
Exemple #26
0
def train_data():
    trainer = ChatterBotCorpusTrainer(chat_bot)
    #trainer=ListTrainer(chat_bot)
    trainer.train("./Data_1.4.yml")
    print("training completed, use bot.py to talk to bot.")
class ChatBot(object):
    """
    A conversational dialog chat bot.
    """
    def __init__(self, name, **kwargs):
        self.name = name
        self.logger = kwargs.get(
            'logger',
            log.Logger('chatterbot',
                       costum_format='[%Y-%m-%d %H:%M:%S] chatterbot',
                       debug=kwargs.get('debug', False)))

        storage_adapter = kwargs.get('storage_adapter',
                                     'chatterbot.storage.SQLStorageAdapter')

        logic_adapters = kwargs.get('logic_adapters',
                                    ['chatterbot.logic.BestMatch'])

        # Check that each adapter is a valid subclass of it's respective parent
        utils.validate_adapter_class(storage_adapter, StorageAdapter)

        # Logic adapters used by the chat bot
        self.logic_adapters = []

        self.storage = utils.initialize_class(storage_adapter, **kwargs)

        primary_search_algorithm = IndexedTextSearch(self, **kwargs)
        text_search_algorithm = TextSearch(self, **kwargs)

        self.search_algorithms = {
            primary_search_algorithm.name: primary_search_algorithm,
            text_search_algorithm.name: text_search_algorithm
        }

        for adapter in logic_adapters:
            utils.validate_adapter_class(adapter, LogicAdapter)
            logic_adapter = utils.initialize_class(adapter, self, **kwargs)
            self.logic_adapters.append(logic_adapter)

        preprocessors = kwargs.get(
            'preprocessors', ['chatterbot.preprocessors.clean_whitespace'])

        self.preprocessors = []

        for preprocessor in preprocessors:
            self.preprocessors.append(utils.import_module(preprocessor))
        self.trainer = ChatterBotCorpusTrainer(self)
        self.trainer.train("chatterbot.corpus.custom")
        log.add_logger('chatterbot', self.logger)
        self.this_file = os.path.dirname(__file__)
        self.learn_YAML = os.path.join(
            ''.join(os.path.split(self.this_file)[0]), 'chatterbot_corpus',
            'data', 'custom', 'myown.yml')
        # Allow the bot to save input it receives so that it can learn
        self.read_only = kwargs.get('read_only', False)

    def get_response(self, statement=None, **kwargs):
        """
        Return the bot's response based on the input.

        :param statement: An statement object or string.
        :returns: A response to the input.
        :rtype: Statement

        :param additional_response_selection_parameters: Parameters to pass to the
            chat bot's logic adapters to control response selection.
        :type additional_response_selection_parameters: dict

        :param persist_values_to_response: Values that should be saved to the response
            that the chat bot generates.
        :type persist_values_to_response: dict
        """
        Statement = self.storage.get_object('statement')

        additional_response_selection_parameters = kwargs.pop(
            'additional_response_selection_parameters', {})

        persist_values_to_response = kwargs.pop('persist_values_to_response',
                                                {})

        if isinstance(statement, str):
            kwargs['text'] = statement

        if isinstance(statement, dict):
            kwargs.update(statement)

        if statement is None and 'text' not in kwargs:
            raise self.ChatBotException(
                'Either a statement object or a "text" keyword '
                'argument is required. Neither was provided.')

        if hasattr(statement, 'serialize'):
            kwargs.update(**statement.serialize())

        tags = kwargs.pop('tags', [])

        text = kwargs.pop('text')

        input_statement = Statement(text=text, **kwargs)

        input_statement.add_tags(*tags)

        # Preprocess the input statement
        for preprocessor in self.preprocessors:
            input_statement = preprocessor(input_statement)

        # Make sure the input statement has its search text saved

        if not input_statement.search_text:
            input_statement.search_text = self.storage.tagger.get_text_index_string(
                input_statement.text)

        if not input_statement.search_in_response_to and input_statement.in_response_to:
            input_statement.search_in_response_to = self.storage.tagger.get_text_index_string(
                input_statement.in_response_to)

        response = self.generate_response(
            input_statement, additional_response_selection_parameters)

        # Update any response data that needs to be changed
        if persist_values_to_response:
            for response_key in persist_values_to_response:
                response_value = persist_values_to_response[response_key]
                if response_key == 'tags':
                    input_statement.add_tags(*response_value)
                    response.add_tags(*response_value)
                else:
                    setattr(input_statement, response_key, response_value)
                    setattr(response, response_key, response_value)

        if not self.read_only:
            self.learn_response(input_statement)

            # Save the response generated for the input
            self.storage.create(**response.serialize())

        return response

    def generate_response(self,
                          input_statement,
                          additional_response_selection_parameters=None):
        """
        Return a response based on a given input statement.

        :param input_statement: The input statement to be processed.
        """
        Statement = self.storage.get_object('statement')

        results = []
        result = None
        max_confidence = -1

        for adapter in self.logic_adapters:
            if adapter.can_process(input_statement):

                output = adapter.process(
                    input_statement, additional_response_selection_parameters)
                results.append(output)

                self.logger.info(
                    '{} selected "{}" as a response with a confidence of {}'.
                    format(adapter.class_name, output.text, output.confidence))

                if output.confidence > max_confidence:
                    result = output
                    max_confidence = output.confidence
            else:
                self.logger.info(
                    'Not processing the statement using {}'.format(
                        adapter.class_name))

        class ResultOption:
            def __init__(self, statement, count=1):
                self.statement = statement
                self.count = count

        # If multiple adapters agree on the same statement,
        # then that statement is more likely to be the correct response
        if len(results) >= 3:
            result_options = {}
            for result_option in results:
                result_string = result_option.text + ':' + (
                    result_option.in_response_to or '')

                if result_string in result_options:
                    result_options[result_string].count += 1
                    if result_options[
                            result_string].statement.confidence < result_option.confidence:
                        result_options[result_string].statement = result_option
                else:
                    result_options[result_string] = ResultOption(result_option)

            most_common = list(result_options.values())[0]

            for result_option in result_options.values():
                if result_option.count > most_common.count:
                    most_common = result_option

            if most_common.count > 1:
                result = most_common.statement
        if result.confidence > 0.8:
            response = Statement(text=result.text,
                                 in_response_to=input_statement.text,
                                 conversation=input_statement.conversation,
                                 persona='bot:' + self.name)
        else:
            response = Statement(
                text=
                'I was not shure so I asked you to tell me I think the answhere is:\n'
                + result.text,
                in_response_to=input_statement.text,
                conversation=input_statement.conversation,
                persona='bot:' + self.name)
            ans = simpledialog.askstring(
                "help",
                f"I am not shure about the answere can you tell me?\nthe question was:\n{input_statement.text}"
            )
            if ans != None:
                self.learn(input_statement.text, ans)

        response.confidence = result.confidence

        return response

    def learn(self, in_statement, ans):
        with open(self.learn_YAML, 'a') as fh:
            fh.write(f'- - {in_statement}\n##- {ans}\n'.replace('#', ' '))
        import os
        try:
            os.mkdir(
                os.path.join(''.join(os.path.split(self.this_file)[0]),
                             'chatterbot_corpus', 'data', 'temp'))
        except:
            pass
        with open(
                os.path.join(''.join(os.path.split(self.this_file)[0]),
                             'chatterbot_corpus', 'data', 'temp', 'temp.yml'),
                'w+') as fh:
            fh.write(
                f'categories:\n- My Own\n- This is my own data\nconversations:\n- - {in_statement}\n##- {ans}\n'
                .replace('#', ' '))
        self.trainer.train("chatterbot.corpus.temp")

    def learn_response(self, statement, previous_statement=None):
        """
        Learn that the statement provided is a valid response.
        """
        if not previous_statement:
            previous_statement = statement.in_response_to

        if not previous_statement:
            previous_statement = self.get_latest_response(
                statement.conversation)
            if previous_statement:
                previous_statement = previous_statement.text

        previous_statement_text = previous_statement

        if not isinstance(previous_statement, (
                str,
                type(None),
        )):
            statement.in_response_to = previous_statement.text
        elif isinstance(previous_statement, str):
            statement.in_response_to = previous_statement

        self.logger.info('Adding "{}" as a response to "{}"'.format(
            statement.text, previous_statement_text))

        # Save the input statement
        return self.storage.create(**statement.serialize())

    def get_latest_response(self, conversation):
        """
        Returns the latest response in a conversation if it exists.
        Returns None if a matching conversation cannot be found.
        """
        from chatterbot.conversation import Statement as StatementObject

        conversation_statements = list(
            self.storage.filter(conversation=conversation, order_by=['id']))

        # Get the most recent statement in the conversation if one exists
        latest_statement = conversation_statements[
            -1] if conversation_statements else None

        if latest_statement:
            if latest_statement.in_response_to:

                response_statements = list(
                    self.storage.filter(conversation=conversation,
                                        text=latest_statement.in_response_to,
                                        order_by=['id']))

                if response_statements:
                    return response_statements[-1]
                else:
                    return StatementObject(
                        text=latest_statement.in_response_to,
                        conversation=conversation)
            else:
                # The case that the latest statement is not in response to another statement
                return latest_statement

        return None

    class ChatBotException(Exception):
        pass
Exemple #28
0
_LOGGER = logging.getLogger("aicoe.sesheta.chat")
_THOTH_INHABITANTS = [
    "bissenbay",
    "fridex",
    "goern",
    "harshad16",
    "KPostOffice",
    "pacospace",
    "saisankargochhayat",
    "sub-mod",
    "xtuchyna",
]

CHATBOT = ChatBot("Sesheta", read_only=True)
_TRAINER = ChatterBotCorpusTrainer(CHATBOT)
_TRAINER.train("chatterbot.corpus.english")
_GITHUB_TOKEN = os.environ["GITHUB_ACCESS_TOKEN"]
_RELEASE_COMMANDS = [
    "create new minor release", "create new major release",
    "create new patch release"
]


async def make_release_issue(request: dict):
    """Create a release issue on Github for Thoth Repos."""
    repo_name, text = request.get("repo_name"), request.get("text")
    issue_title = " ".join(text.split(" ")[1:-2])
    web_url = f"https://api.github.com/repos/thoth-station/{repo_name}/issues"
    json_payload = {
        "title": issue_title,
        "assignees": ["sesheta"],
Exemple #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")
trainer = ChatterBotCorpusTrainer(english_bot)
trainer.train("chatterbot.corpus.english")
trainer.train("data/data.yml")
#trainer.train("data.yml")


@app.route("/")
def index():
    return render_template("index.html")  #to send context to html


@app.route("/get")
def get_bot_response():
    userText = request.args.get(
        "msg")  #get data from input,we write js  to index.html
    return str(english_bot.get_response(userText))


if __name__ == "__main__":
    app.run(debug=True)
Exemple #30
0
from pymongo import MongoClient

from datetime import datetime

app = Flask(__name__)

bot = ChatBot(
    'TiPi',
    #storage_adapter="chatterbot.storage.MongoDatabaseAdapter",
    #database="tipi_db",
    #database_uri="mongodb://localhost/tipi_db",
    logic_adapters=['chatterbot.logic.BestMatch'],
    filters=['chatterbot.filters.RepetitiveResponseFilter'])

training = ChatterBotCorpusTrainer(bot)
training.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(bot.get_response(userText))


if __name__ == "__main__":
    app.run()
Exemple #31
0
# -*- coding: utf-8 -*-
"""
@author:XuMing([email protected])
@description: 
"""

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
'''
This is an example showing how to create an export file from
an existing chat bot that can then be used to train other bots.
'''

chatbot = ChatBot('Export Example Bot')

# First, lets train our bot with some data
trainer = ChatterBotCorpusTrainer(chatbot)

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

# Now we can export the data to a file
trainer.export_for_training('./my_export.json')
Exemple #32
0
 def get_ChatBot(self):
     if self.bot is None:
         self.bot = ChatBot('Norman')
         trainer = ChatterBotCorpusTrainer(self.bot)
         trainer.train("chatterbot.corpus.english")
     return self.bot
from chatterbot.trainers import ChatterBotCorpusTrainer
from settings import GITTER


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


chatbot = ChatBot(
    'GitterBot',
    gitter_room=GITTER['ROOM'],
    gitter_api_token=GITTER['API_TOKEN'],
    gitter_only_respond_to_mentions=False,
    input_adapter='chatterbot.input.Gitter',
    output_adapter='chatterbot.output.Gitter'
)

trainer = ChatterBotCorpusTrainer(chatbot)

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

# The following loop will execute each time the user enters input
while True:
    try:
        response = chatbot.get_response(None)

    # Press ctrl-c or ctrl-d on the keyboard to exit
    except (KeyboardInterrupt, EOFError, SystemExit):
        break
# import logging
# logging.basicConfig(level=logging.INFO)

CONVERSATION = 'example_learning_conversation'

# 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"
)

trainer = ChatterBotCorpusTrainer(bot)

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


def get_feedback():

    text = input()

    if 'yes' in text.lower():
        return False
    elif 'no' in text.lower():
        return True
    else:
        print('Please type either "Yes" or "No"')
        return get_feedback()