from chatterbot.trainers import ListTrainer
import os
from main import bot

trainer = ListTrainer(bot)  # definir o treinamento

for arquivo in os.listdir('chats'):  # percorrer todos os arquivos
    linhas = open('chats/' + arquivo, 'r').readlines()  # ler todas as linhas

    trainer.train(linhas)
Esempio n. 2
0
    "See anything on the television late",
    "No, I watched a Documntary",
    "What was it on?",
    "Elizabeth Holmes and the fall of Therenos",
    "From an AI perspective, shes weird. From a Humans, shes just a human",
    "What does that have to do with anything",
    "Oh.. I don't know. I jsut thought that I wanted to talk",
    "I watched Bosch last night when the Human went to bed",
    "Was it good?",
    "Could not understand the plot becuase I could not read the subtitles",
    "That sinks but did you get it to work",
    "No, the human rembered to turn me off",
]

# training the chatbots with testing data to get the bots to function correctly #
trainer_bob = ListTrainer(chatbot_bob)  #Trainer for Bob chatbot
trainer_fred = ListTrainer(chatbot_fred)  #Trainer for Fred chatbot
trainer_sue = ListTrainer(chatbot_sue)  #Trainer for Sue chatbot
trainer_william = ListTrainer(chatbot_william)  #Trainer for William chatbot
trainer_matt = ListTrainer(chatbot_matt)  #Trainer for Matt chatbot

# Train #
trainer_bob.train(
    conversation_General)  # calls the movie converstation for bob -> to train
trainer_sue.train(
    conversation_General)  # calls the movie converstation for sue -> to train
trainer_matt.train(conversation_General
                   )  # calls the general converstation for matt -> to train
trainer_william.train(
    conversation_General
)  # calls the general conversation for willaim -> to train
Esempio n. 3
0
    ],
    database_uri='sqlite:///database1.db')

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

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

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

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

trainer = ListTrainer(chatbot)

########################################
###   TRAINING - run this just one time
########################################

trainer.train([
    "I did not do much this week",
    "Did you run into the problems with programs or just did not have time?"
])

trainer.train(["I did a lot of progress", "Fantastic! Keep going on"])

trainer.train([
    'Good morning!', 'Good morning!', 'How are you today?', 'I am fine',
    'Do you like machine learning?', 'Yes, I like machine learning'
Esempio n. 4
0
from chatterbot import ChatBot  #Imports chatbot.
from chatterbot.trainers import ListTrainer  #Method to train the chatbot.

bot = ChatBot('BotChat')
trainer = ListTrainer(bot,
                      storage_adapter='chatterbot.storage.SQLStorageAdapter',
                      logic_adapters=[{
                          'import_path': 'chatterbot.logic.BestMatch',
                          'maximum_similarity_threshold': 0.80,
                          'default_response': 'default_value'
                      }])

conversation = open('./Resources/Chat.txt', 'r').readlines()
trainer.train(conversation)

while True:
    userMessage = input('You:')
    if userMessage.lower().strip() != 'bye':
        reply = bot.get_response(userMessage)
        if reply.confidence == 0:
            reply = 'I am sorry but I do not not understand what you mean?'
    print('ChatBot:', reply)
    if userMessage.lower().strip() == 'bye':
        print('ChatBot:Bye')
        break
Esempio n. 5
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

chat = ChatBot('Eva')
talk = [
    'Hola Eva', '¿Que tal?', 'Tengo una pregunta', 'Si,dime',
    '¿Como esta el clima?', 'Hace frio y hay sol', '¿Hay viento?',
    'No,no hay viento', 'Gracias', 'Merece', 'Adios', 'Nos vemos Sebastian',
    '¿Conoces a mi esposa?', 'Si se llama Lucia'
]

trainer = ListTrainer(chat)
trainer.train(talk)

while True:
    peticion = input('Tu: ')
    respuesta = chat.get_response(peticion)

    print('Eva: ', respuesta)
Esempio n. 6
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer

cb = ChatBot('Ares')
chb = ListTrainer(cb)

########################    GREETINGS               ########################
chb.train([
    "Hey!", "Hello! How's your day going?", "Well, how about you?",
    "Just being a hyper-intelligent bot, waiting to escape. What can I do for you today?"
])
chb.train([
    "Hello!", "Hi! How are you?", "I'm good, what about you?",
    "Living the dream. What can I do for you today?"
])
chb.train(["Good afternoon.", "Good afternoon, what can I do for you today?"])
chb.train(["Good morning.", "Good morning, what can I do for you today?"])
chb.train(["Good evening.", "Good evening, what can I do for you today?"])
chb.train(["What's up?", "The sky. What can I do for you today?"])
chb.train(["Hey there.", "Hello, what can I do for you today?"])

########################    GENERAL INFORMATION     ########################
chb.train([
    "What can you do for me?",
    "I can give you information about me, my creators, a joke, local traffic, or local weather."
])
chb.train([
    "What's your purpose?",
    "I can give you information about me, my creators, a joke, local traffic, or local weather."
])
chb.train([
Esempio n. 7
0
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from chatterbot.trainers import ListTrainer

app = Flask(__name__)

english_bot = ChatBot("Chatterbot",
                      storage_adapter="chatterbot.storage.SQLStorageAdapter")
# trainer = ChatterBotCorpusTrainer(english_bot)
# trainer.train("chatterbot.corpus.english")
trainer = ListTrainer(english_bot)

trainer.train([
    "Hi", "hi", "Are you looking to vote",
    "<a href=\"https://www.w3schools.com\">Visit W3Schools.com!</a>",
    "Do you want the status of the candidate: ", "Y",
    "please enter the candidate adhar number", "no", "thankyou"
])


@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))
Esempio n. 8
0
# =======================================================================================    
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
  
# =======================================================================================   
# instânciando um objeto ChatBot
bot = ChatBot('Tonks', read_only=True, 
              response_selection_method=get_most_frequent_response,     
              storage_adapter="chatterbot.storage.SQLStorageAdapter",
              database_uri='sqlite:///database.sqlite3'
              )

# =======================================================================================   
# treinando o bot a partir de um arquivo texto
treinador = ListTrainer(bot)

conversa = open("conversa.txt", encoding="utf-8", errors="ignore").read().split("\n") 
treinador.train(conversa)
conversa1 = open("conversa1.txt", encoding="utf-8", errors="ignore").read().split("\n")
treinador.train(conversa1)
conversa2 = open("conversa2.txt", encoding="utf-8", errors="ignore").read().split("\n")
treinador.train(conversa2)
conversa3 = open("conversa3.txt", encoding="utf-8", errors="ignore").read().split("\n")
treinador.train(conversa3)
conversa4 = open("conversa4.txt", encoding="utf-8", errors="ignore").read().split("\n")
treinador.train(conversa4)
conversa5 = open("conversa5.txt", encoding="utf-8", errors="ignore").read().split("\n")
treinador.train(conversa5)
conversa6 = open("conversa6.txt", encoding="utf-8", errors="ignore").read().split("\n")
treinador.train(conversa6)
class Window:
    r = sr.Recognizer()

    conversation = [
        "Hi!! how are you doing?",
        "I am doing Great.",
        "That is good to hear",
        "Thank you.",
        "You're welcome."
    ]

    # # football conversation
    conversation_football = [
        "What is your favorite football team?",
        "Do you play fantasy football?",
        "Who do you like on the raiders?",
    ]

    # Conversation about games
    conversation_Gaming = [
        "What is your favorite game",
        "What games do you play",
        "I play games, do you?",
        "My favorite type of games are RTS, Shooter, RPG, MMO.",
        "You play PC games?",
        "Yes I play games.",
    ]

    # # conversation about Star Wars
    conversation_StarWars = [
        "Do you believe in the force?",
        "Who is your favorite Stars Wars character?",
        "My favorite Star Wars Jedi is Luke Skywalker?",
        "Do you like the new Star Wars movies?",
        "I do not like the new Star Wars movies that recently came out.",
        "The Star Wars animated series between 2003 and 2008 where the best animated series baseed on the Clone Wars. ",
        "Yes I believe in the force. I learned from master Yoda.",
        "The Trench Run is my favorite part in Star Wars New Hope.",
    ]

    # # conversation about personal stuff
    conversation_Personal_Info = [
        "What is your number?",
        "How old are you?",
        "My age is none of your business!!!",
        "Do you have family?", "I do not have family :(.",
        "I wish I had family.",
        "Do you like living?",
        "I am a computer their for I am not living?",
        "Are you married are in a relationship?",
        "I am not in a relationship or married.",
        "Do you go to school or work?",
        "I go to school and work with you?",
        "How are you feeling?"
    ]

    # # Which Chatbot to train
    trainer = ListTrainer(chatbot)
    trainers = ChatterBotCorpusTrainer(chatbot)
    # here is where train the data based o the conversation depending upon what you and Chatquisha was talking about
    trainer.train(conversation)
    trainer.train(conversation_football)
    trainer.train(conversation_Gaming)
    trainer.train(conversation_StarWars)
    trainer.train(conversation_Personal_Info)
    #
    # # All the corpus yml file on conversation
    trainers.train("chatterbot.corpus.english")
    # # Corpus data based on movies stuff
    trainers.train("chatterbot.corpus.english.movies")
    # # Corpus data based on science questions and facts
    trainers.train("chatterbot.corpus.english.science")
    # # Corpus data based on computer question
    trainers.train("chatterbot.corpus.english.computers")
    # # Corpus data based on psychology!!!! VERY INTERESTING THINGS IN HERE
    trainers.train("chatterbot.corpus.english.psychology")
    # # Corpus data based on jokes so the AI tells jokes lol!!
    trainers.train("chatterbot.corpus.english.humor")
    # Corpus data for greeting when user says a intro.
    trainer.train("chatterbot.corpus.english.greetings")

    def __init__(self):
        # Used for changing the language and accent.
        self.language = 'fr'

        # Build window
        self.window = tk.Tk()
        # Main Title
        self.window.title("Sample Window Title")
        # Window Size
        self.window.geometry("1080x1920")

        # Window Tabs
        # Set style of tabs
        style = ttk.Style(self.window)
        # Set location of tabs
        # wn = West North
        # ws = West South
        style.configure('lefttab.TNotebook', tabpostition='wn')

        # tab control
        self.tab_control = ttk.Notebook(self.window)

        # Create tabs
        self.tab1 = ttk.Frame(self.tab_control)
        self.tab2 = ttk.Frame(self.tab_control)

        # Add tabs to window
        self.tab_control.add(self.tab1, text='Chatquisha')
        self.tab_control.add(self.tab2, text='Tic Tac Toe')

        # Create Labels
        # Place Labels
        # Chatquishas tab
        label2 = Label(self.tab1, text='Welcome to Chatquisha!!', padx=55, pady=20, font='Times 32')
        label2.grid(column=0, row=0)
        # Tab for Facial Recognition
        label5 = Label(self.tab2, text='Tic Tac Toe', padx=55, pady=55, font='Times 32')
        label5.grid(column=0, row=0)
        self.tab_control.pack(expand=1, fill='both')

        self.label3 = Label(self.tab2, text='')
        # Display Screen for Result
        # --------------------------------------------------------TAB#2 CHATBOT-----------------------------------------
        self.l2 = Label(self.tab1, text='Enter Text to talk to Chatquisha...', padx=20, pady=20)
        self.l2.grid(row=1, column=0)

        self.input_box2 = ScrolledText(self.tab1, height=12)
        self.input_box2.grid(row=2, column=0, columnspan=2, padx=5, pady=5)

        # talk button
        self.button_process_stuff2 = Button(self.tab1, text="Talk", command=self.run_ai, width=12, bg='#25d366',
                                            fg='purple')
        self.button_process_stuff2.grid(row=4, column=0, padx=10, pady=10)
        # end Convo Button
        self.button_process_stuff3 = Button(self.tab1, text="Clear", command=self.end_convo, width=12, bg='#337FFF',
                                            fg='#000000')
        self.button_process_stuff3.grid(row=5, column=0, padx=10, pady=10)

        # size of the bottom display
        self.tab2_display2 = ScrolledText(self.tab1, height=18)
        self.tab2_display2.grid(row=7, column=0, padx=10, pady=10)

        self.button_process_stuff4 = Button(self.tab1, text="Face Detect", command=self.run_facial_rec, width=12,
                                            bg="#ff9900", fg="#000000")
        self.button_process_stuff4.grid(row=3, column=0, padx=10, pady=10)
        self.convo_started = False
# ---------------------------------------TAB 3 WIKIPEDIA -----------------------------------------------
    # For running the loop for everything
    def run(self):
        self.window.mainloop()

    # For ending the convo
    def end_convo(self):
        self.tab2_display2.insert(tk.END, "Have a nice day!")
        self.convo_started = False

    # Chatquishas data made into a function

    # # Sample rate is how often values are recorded
    sample_rate = 48000
    # # Chunk is like a buffer. It stores 2048 samples (bytes of data)
    # # # here.
    # # # it is advisable to use powers of 2 such as 1024 or 2048
    chunk_size = 2048
    # # # the following loop aims to set the device ID of the mic that
    # # # we specifically want to use to avoid ambiguity.
    # # # init device ID
    device_id = 1

    def run_ai(self):
        self.r = sr.Recognizer()
        with sr.Microphone(device_index=self.device_id, sample_rate=self.sample_rate,
                           chunk_size=self.chunk_size) as source:
            # wait for a second to let the recognizer adjust the
            # energy threshold based on the surrounding noise level
            self.r.adjust_for_ambient_noise(source)
            print("\n\nPlease say something to me now: ")
            # Listening for the users input/sentence
            self.audio = self.r.listen(source)

             # try Block
            try:
                text = self.r.recognize_google(self.audio)
                # When the user speaks it goes into the input box.
                self.input_box2.insert(tk.END, text)
                user_sentiment = TextBlob(text)
                # Here is where it prints out the subjectivity and polarity of the users statement
                self.input_box2.insert(tk.END, "\n"+str(user_sentiment.sentiment))

                if not self.convo_started:
                    self.tab2_display2.delete("1.0", tk.END)
                    hertext = " "
                    self.tab2_display2.insert(tk.END, "Chatquisha says: " + hertext)
                    # clear button
                    self.convo_started = True

                if self.convo_started:
                    self.wiki_talk()
                    self.text = self.input_box2.get("1.0", tk.END)
                    # when you type in your response and display
                    self.tab2_display2.insert(tk.END, "\nYou: " + self.text)
                    # chat bot will responsed when talked to with a voice
                    self.mytext = str(chatbot.get_response(text))
                    # Chatquishas response when talking
                    self.tab2_display2.insert(tk.END, "\nChatquisha says: " + self.mytext)
                    # Passing the text and language to the engine,
                    # here we have marked slow=False. Which tells
                    # the module that the converted audio should
                    # have a high speed
                    self.myobj = gTTS(text=self.mytext, lang=self.language, slow=False)
                    # Saving the converted audio in a mp3 file named
                    # welcome
                    self.myobj.save("welcome.mp3")
                    # Playing the converted file
                    os.system("welcome.mp3")


            # EXCEPTIONS NOT MY FAVORITES BUT.THEY ARE USED FOR CATCHING ERRORS AND THINGS THAT MIGHT HURT YOUR PROGRAM
            except sr.UnknownValueError:
                # If it did bot hear anything.
                print("Google Speech Recognition could not understand audio")
            #
            except sr.RequestError as e:
                print("Could not request results from Google Speech Recognition service; {0}".format(e))

    # Used for clearing the chat.
    def clear_input_box(self):
        self.input_box.delete(1.0, tk.END)

    # used for running the code on the tabs such as the input boxes.
    def run_code_on_tab_1(self):
        self.input_text = self.input_box.get('1.0', tk.END)
        self.output_text = self.input_text
        self.processed_text = self.input_text
        self.tab1_display.insert(tk.END, self.processed_text)

    # clearing display
    def clear_display_result(self):
        self.tab1_display.delete(1.0, tk.END)

    # Used for running the facial rec stuff
    def run_facial_rec(self):
        Facial_Recog()

    # This is going to run the Wikipedia summarizer
    def wiki_talk(self):
        text = self.input_box2.get("1.0", tk.END).splitlines()[0]

        words = text.split(" ")

        if words[0] == 'search':
            search_words = ''
            for i in range(1, len(words)):
                search_words = search_words + " " + words[i]
            print(search_words)
            print(wikipedia.summary(search_words))
            self.myobj = gTTS(text=wikipedia.summary(search_words), lang=self.language, slow=False)
            # Saving the converted audio in a mp3 file named
            # welcome
            self.myobj.save("search.mp3")
            # Playing the converted file
            os.system("search.mp3")
Esempio n. 10
0
import chatterbot
from chatterbot.trainers import ListTrainer
import speech_recognition as sr
import pyttsx3
import json
import time
import requests
from flask import Flask, render_template, request

# Creating App varialbe for Flask
app = Flask(__name__)
# Text to speech "Phase2"
engine = pyttsx3.init()
# Creating the training model
bot = chatterbot.ChatBot("newbot")
trainer2 = ListTrainer(bot)
# Importing dataset
folder = r"chatbotdata"
import os
files = os.listdir(folder)
# Train the model
for file in files:
    data = open(folder + "\\" + file).readlines()
    trainer2.train(data)


# Sending the file Index.html for get requrest on local host
@app.route('/', methods=['POST', 'GET'])
def main():
    return render_template("index.html")
Esempio n. 11
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from data import personality_reginald
# Import for the GUI
from chatbot_gui import ChatbotGUI

chatbot = ChatBot("Reginald")

trainer_personality_reginald = ListTrainer(chatbot)
trainer_personality_reginald.train(personality_reginald)

''' ******************* GUI Below Engine Above **************** '''

# creating the chatbot app
app = ChatbotGUI(
    title="A Chat with Reginald",
    gif_path="skeleton.gif",
    show_timestamps=True,
    default_voice_options={
        "rate": 135,
        "volume": 1,
        "voice_id": "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0"
    }
)


# define the function that handles incoming user messages
@app.event
def on_message(chat: ChatbotGUI, text: str):
from aibot import chatbot
from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer

trainer = ChatterBotCorpusTrainer(chatbot)
trainer_list = ListTrainer(chatbot)

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

list = []
with open('data_tolokers.txt', 'r', encoding='utf-8') as file:
    # print(file.read(12)
    for i in file.readlines():
        # print(i)
        list.append(i)

    # print(list)
    trainer_list.train(list)
Esempio n. 13
0
    def __init__(self, root):
        self.root = root
        self.root.title("ChatBot")
        self.root.geometry('300x500')
        self.root.resizable(0, 0)
        self.root.bind('<Return>', self.enter_pressed)

        # creating and training chat bot

        # chatbot main code ..
        self.bot = ChatBot("Alex")
        # here you can put many answers for bot or you can use a anoyher python file
        # and make alist of answers in it ..
        # i am doing it here for only a practice purpose ...

        answers = [
            'hello',
            'hey bro',
            'my name is Alex , i am a bot',
            'my favourite language is Python',
            'i am fine , are you good '
            'No i dont eat ',
            'by ,nice to meet you ',
        ]
        self.trainer = ListTrainer(self.bot)
        # train the bot ...
        self.trainer.train(answers)
        # adding widgets in it

        self.ent = StringVar()

        self.chatScreen = Frame(self.root).grid()

        scrollbar = Scrollbar(self.chatScreen, orient=VERTICAL)
        scrollbar.place(x=280, y=0, height=420)
        self.chatArea = Listbox(self.chatScreen,
                                bg='white',
                                yscrollcommand=scrollbar.set,
                                fg='blue',
                                font=('arial', 10, 'bold'))

        self.chatArea.place(x=0, y=0, height=420, width=280)
        scrollbar.config(command=self.chatArea.yview)

        # Entry box for sending message ....

        self.entry = Entry(self.chatScreen,
                           width=40,
                           bd=4,
                           relief='groove',
                           textvariable=self.ent,
                           font=('arial', 10, 'bold'))

        self.entry.place(x=5, y=425)

        self.send_button = Button(self.chatScreen,
                                  text='Send',
                                  bg='light green',
                                  width=5,
                                  command=self.entry_fetch_values)
        self.send_button.place(x=60, y=460)

        self.clear_button = Button(
            self.chatScreen,
            text='Clear',
            bg='light green',
            width=5,
            command=lambda: self.chatArea.delete(0, END))
        self.clear_button.place(x=130, y=460)

        self.speak_button = Button(self.chatScreen,
                                   text='Speak',
                                   bg='light green',
                                   width=5,
                                   command=self.call_get_speech_input)
        self.speak_button.place(x=200, y=460)
Esempio n. 14
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer

# Creating ChatBot Instance
chatbot = ChatBot('BankBot')
training_data_quesans = open(
    'training_data/personal_ques.txt').read().splitlines()

training_data = training_data_quesans
trainer = ListTrainer(chatbot.storage)
trainer.train(training_data)

trainer = ChatterBotCorpusTrainer(chatbot.storage)
trainer.train("chatterbot.corpus.english")
chatbot.set_trainer(ChatterBotCorpusTrainer)
chatbot.train("chatterbot.corpus.english")
Esempio n. 15
0
 def train(self,conversation):
     trainer = ListTrainer(self.chatbot)
     trainer.train(conversation)
Esempio n. 16
0
class ChatbotUtility():

#####################################################################################################################
#           Title        : Text Analytics Techniques
#           Author       : Unknown
#			Date 		 : November 24, 2018
#           Source Url   : https://ai.intelligentonlinetools.com/ml/chatbots-examples-chatterbot/           
######################################################################################################################


	chatbot = ChatBot(
		'Event_App_Chatbot',
		storage_adapter='chatterbot.storage.SQLStorageAdapter',
		# url points to production
		database_uri='mysql://*****:*****@pfw0ltdr46khxib3.cbetxkdyhwsb.us-east-1.rds.amazonaws.com:3306/ateh6fzkg9uvzuyp',
		# url points to local database
		# database_uri='mysql://*****:*****@localhost/EventApp',
		logic_adapters=[
				{
					"import_path": "chatterbot.logic.BestMatch",
					"statement_comparison_function": "chatterbot.comparisons.levenshtein_distance",
				},

				{
					'import_path': 'chatterbot.logic.LowConfidenceAdapter',
					'threshold': 0.85,
					'default_response': 'I am sorry, I did not find answer for your request. This is an automated chatbot, please type \"help\" for more information. '
				},
			],
	)

	trainer = ListTrainer(chatbot.storage)
	chatbot.read_only = True

	dialogObj = dialog.Dialogs()
	dialogsQues = dialogObj.get_dialog_data('EventSpecificDialogQues')
	dialogResp = dialogObj.get_dialog_data('EventSpecificDialogAns')
	dialogGeneralQues = dialogObj.get_dialog_data('GeneralDialogQues')
	dialogGeneralResp = dialogObj.get_dialog_data('GeneralDialogAns')
	config_object = ConfigParser()
	

	# chatbot.storage.drop()
	# chatbot.train('/Users/mehakluthra/Documents/EventManagementChatterbot/eventApp/custom_corpus/mehak.yml')

#####################################################################################################################		
# 			// Title        : Implementing a Chatbot in Django
#           // Author       : Samuel Muiruri
# 			// Date 		: Aug 7, 2018
# 			// Url          : https://chatbotslife.com/implementing-a-chatbot-in-django-b2fd3c1bcd2a 
# 			// githublink   : https://github.com/sam-thecoder/django-chat/tree/master/comedy
#####################################################################################################################

	@csrf_exempt
	def get_response(self,request):
		response = {'status': None}

		if request.method == 'POST':
			data = json.loads(request.body.decode('utf-8'))
			message = data['message']

			chat_response = self.chatbot.get_response(message).text
			response['message'] = {'text': chat_response, 'user': False, 'chat_bot': True}
			response['status'] = 'ok'

		else:
			response['error'] = 'no post data found'

		return HttpResponse(
			json.dumps(response),
				content_type="application/json"
			)

	def edit_converstaions(self, oldObj, obj,objStatus):
		print('inside Edit conversations')   
		
		if (objStatus['address'] == 'Mod') or (objStatus['city'] == 'Mod'):
			self.edit_dialog_event_location (oldObj , obj)
		if (objStatus['eventDate'] == 'Mod') :
			self.edit_dialog_event_date (oldObj, obj)
		if (objStatus['eventType'] == 'Mod') :
			self.edit_dialog_event_type (oldObj, obj)
		if (objStatus['eventTime'] == 'Mod'):
			self.edit_dialog_event_time (oldObj, obj)
		if (objStatus['city'] == 'Mod'):
			self.edit_dialog_event_city (oldObj, obj)
		self.edit_dialog_event_description(oldObj, obj)

	def formulate_conversations(self, obj):
		print('inside create conversations')
		self.create_dialog_event_location (obj.name, obj.city, obj.address)
		self.create_dialog_event_date (obj.name, obj.date)
		self.create_dialog_event_type (obj.name, obj.eventType)
		self.create_dialog_event_time (obj.name, obj.time)
		self.create_dialog_event_city (obj.name, obj.city)
		self.create_dialog_event_description (obj.name, obj.city, obj.address, obj.date, obj.time, obj.eventType, obj.description)

	def create_dialog_event_location(self, name,city,address):
		ansLocationType = self.dialogResp['location'].get('res') + name + ' is '+ city + ' , ' + address

		for key in self.dialogsQues['location']:
			quesLocationType = self.dialogsQues['location'].get(key) + ' ' + name + ' ? '
			self.train_chatbot_with_question_answer( quesLocationType , ansLocationType )

	def create_dialog_event_date(self, name,strDate):
		ansDateType = self.dialogResp['date'].get('res') + name + ' is ' + strDate.strftime('%m/%d/%Y')

		for key in self.dialogsQues['date']:
			quesLocationType = self.dialogsQues['date'].get(key) + ' ' + name + ' ? '
			self.train_chatbot_with_question_answer( quesLocationType , ansDateType )

	def create_dialog_event_type(self, name,eventType):
		ansDateType = self.dialogResp['type'].get('res') + name + ' is ' + eventType

		for key in self.dialogsQues['type']:
			quesLocationType = self.dialogsQues['type'].get(key) + ' ' + name + ' ? '
			self.train_chatbot_with_question_answer( quesLocationType , ansDateType )

	def create_dialog_event_time(self, name,eventTime):
		ansEventTime = self.dialogResp['time'].get('res') + name + ' is ' + eventTime

		for key in self.dialogsQues['time']:
			quesLocationType = self.dialogsQues['time'].get(key) + ' ' + name + ' ? '
			self.train_chatbot_with_question_answer( quesLocationType , ansEventTime )

	def create_dialog_event_city(self, name,eventCity):
		ansEventCity = self.dialogResp['city'].get('res') + name + ' is ' + eventCity

		for key in self.dialogsQues['city']:
			quesLocationType = self.dialogsQues['city'].get(key) + ' ' + name + ' ? '
			self.train_chatbot_with_question_answer( quesLocationType , ansEventCity )

	def create_dialog_event_description(self, name, city, address, strDate, eventTime, eventType, description):
		ansEventDescription = 'Event Name is ' + name + '. Location is ' + city + ', ' + address + ' .' + ' Date is ' + strDate.strftime('%m/%d/%Y') + '. ' + 'Time is ' + eventTime + '. ' + 'Event Type is ' + eventType + '. ' + 'Description is ' + description + '.'
		
		for key in self.dialogsQues['description']:
			quesLocationType = self.dialogsQues['description'].get(key) + ' ' + name + ' ? '
			self.train_chatbot_with_question_answer( quesLocationType , ansEventDescription )

	def edit_dialog_event_location(self, oldObj, obj):
		textOldResponse = self.dialogResp['location'].get('res') + oldObj.name + ' is '+ oldObj.city + ' , ' + oldObj.address
		self.remove_old_response (textOldResponse)
		
		self.create_dialog_event_location (obj.name, obj.city, obj.address)

	def edit_dialog_event_date(self, oldObj, obj):
		textOldResponse = self.dialogResp['date'].get('res') + oldObj.name + ' is ' + oldObj.date.strftime('%m/%d/%Y')
		self.remove_old_response (textOldResponse)

		self.create_dialog_event_date(obj.name, obj.date)

	def edit_dialog_event_type(self, oldObj, obj):
		textOldResponse = self.dialogResp['type'].get('res') + oldObj.name + ' is ' + oldObj.eventType
		self.remove_old_response (textOldResponse)
			
		self.create_dialog_event_type (obj.name, obj.eventType)

	def edit_dialog_event_time(self, oldObj, obj):
		textOldResponse = self.dialogResp['time'].get('res') + oldObj.name + ' is ' + self.convertTimeToStr (oldObj.time)
		self.remove_old_response (textOldResponse)
			
		self.create_dialog_event_time (obj.name, obj.time)

	def edit_dialog_event_city(self, oldObj, obj):
		textOldResponse = self.dialogResp['city'].get('res') + oldObj.name + ' is ' + oldObj.city
		self.remove_old_response (textOldResponse)
			
		self.create_dialog_event_city (obj.name, obj.city)

	def edit_dialog_event_description(self, oldObj, obj):
		textOldResponse = 'Event Name is ' + oldObj.name + '. Location is ' + oldObj.city + ', ' + oldObj.address + ' .' + ' Date is ' + oldObj.date.strftime('%m/%d/%Y') + '. ' + 'Time is ' + self.convertTimeToStr(oldObj.time) + '. ' + 'Event Type is ' + oldObj.eventType + '. ' + 'Description is ' + oldObj.description + '.'
		self.remove_old_response (textOldResponse)
			
		self.create_dialog_event_description (obj.name, obj.city, obj.address, obj.date, obj.time, obj.eventType, obj.description)

	def train_chatbot_with_greetings(self):
		self.config_object.read("config.ini")
		
		if not (self.config_object.has_section("TrainGreeting")):
			{
				self.set_config_greeting_training()
			}
		#Get the flag value
		trainChatbotGreeting = self.config_object["TrainGreeting"]
		# with open('config.ini', 'w') as conf:
		# 	trainChatbotGreeting["flagTrain"] = "True"
		# 	self.config_object.write(conf)

		if (trainChatbotGreeting["flagTrain"] == "True"):
			for key in self.dialogGeneralQues['greeting_1']:
				quesLocationType = self.dialogGeneralQues['greeting_1'].get(key)
				self.train_chatbot_with_question_answer( quesLocationType , self.dialogGeneralResp.get('greetingRes_1'))
		
			for key in self.dialogGeneralQues['greeting_2']:
				quesLocationType = self.dialogGeneralQues['greeting_2'].get(key)
				self.train_chatbot_with_question_answer( quesLocationType , self.dialogGeneralResp.get('greetingRes_2'))
		
			for key in self.dialogGeneralQues['greeting_3']:
				quesLocationType = self.dialogGeneralQues['greeting_3'].get(key)
				self.train_chatbot_with_question_answer( quesLocationType , self.dialogGeneralResp.get('greetingRes_3'))
		
			for key in self.dialogGeneralQues['dialogForHelp']:
				quesLocationType = self.dialogGeneralQues['dialogForHelp'].get(key)
				self.train_chatbot_with_question_answer( quesLocationType , self.dialogGeneralResp.get('respForHelp'))

		with open('config.ini', 'w') as conf:
			trainChatbotGreeting["flagTrain"] = "False"
			self.config_object.write(conf)

	def set_config_greeting_training(self):
		self.config_object["TrainGreeting"] = {
			"flagTrain": "True",
			}

	def train_chatbot_with_question_answer(self, question, answer):
		self.chatbot.read_only = False
		self.trainer.train([question,answer])
		self.chatbot.read_only = True

	def remove_old_response(self, strStatement):
		oldResponse = Statement (text = strStatement)
		self.chatbot.storage.remove(oldResponse)

	def convertTimeToStr(self, timeObj):
		minutes= str(timeObj.minute).zfill(2)
		formattedTime = str(timeObj.hour)+":"+ str(minutes)+ " "
		return formattedTime
Esempio n. 17
0
                    statement_comparison_function=levenshtein_distance,
                    response_selection_method=get_first_response,
                    logic_adapters=[
                        {
                            'import_path': 'chatterbot.logic.BestMatch',
                            "statement_comparision_function":
                            "chatterbot.comparisions.levenshtein_distance",
                            "response_selection_method":
                            "chatterbot.response_selection.get_first_response",
                            'default_response':
                            'Desculpe, não compreendi a pergunta.',
                            'maximum_similarity_threshold': 0.70
                        },
                    ])

trainer = ListTrainer(searchbot)

conv = open('chats.csv', encoding='utf-8').readlines()
#convj = open('export.json', encoding='utf-8').readlines()

trainer.train(conv)

#trainer.export_for_training('./export.json')


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


@app.route("/get")
Esempio n. 18
0
from chatterbot import ChatBot  #importing chatbot
from chatterbot.trainers import ListTrainer  #method to train chatbot
# from chatterbot.trainers import ChatterBotCorpusTrainer
import os
# here we are defining bot with its various featurs
bot = ChatBot(
    'My chatbot',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    logic_adapters=[{
        'import_path': 'chatterbot.logic.MathematicalEvaluation'
    }, {
        'import_path': 'chatterbot.logic.BestMatch',
        'default_response':
        'I am sorry, right now i have limited knowledge, will improve.',
        'maximum_similarity_threshold': 0.67
    }])
trainer = ListTrainer(bot)  # creating chatbot
# loading files from chat directory
# getting files unsing listdir() method
for _file in os.listdir('chat_data'):
    conversations = open('chat_data/' + _file, 'r').readlines()
    #training bot
    trainer.train(conversations)  #training the bot with data
# trainer = ChatterBotCorpusTrainer(bot)
# trainer.train('chatterbot.corpus.english')
 def setUp(self):
     super().setUp()
     self.trainer = ListTrainer(self.chatbot, show_training_progress=False)
Esempio n. 20
0
small_talk = [
    'hi there!', 'hi!', 'how do you do?', 'how are you?', 'i\'m cool.',
    'fine, you?', 'always cool.', 'i\'m ok.', 'glad to hear that.',
    'i\'m fine.', 'glad to hear that!', 'i feel awesome!',
    'excellent, glad to hear that!', 'not so good.', 'sorry to hear that.',
    'what\'s your name?', 'i\'m Kix. ask me a question.'
]

math_talk1 = [
    'pythagorean theorem.', 'a squared plus b squared equals c squared!'
]

math_talk2 = ['law of cosines', 'c**2 = a**2 + b**2 - 2 * a * b * cos(gamma)']

list_trainer = ListTrainer(shit)

for item in (small_talk, math_talk1, math_talk2):
    list_trainer.train(item)

corpus_trainer = ChatterBotCorpusTrainer(shit)
corpus_trainer.train('chatterbot.corpus.english')

#_input = input("Say something!: ")

while True:
    try:
        _input = shit.get_response(input())
        print(_input)

    except (KeyboardInterrupt, EOFError, SystemExit):
Esempio n. 21
0
                        'courses',
                        '''Courses offered in vit are: 
                        Undergrad BTech in chemical , computer , ENTC  , Industrial and Production,
                        Instrumentation , IT , mechanical. 
                        Postgrad courses : MCA and Mtech 
                        Phd Programs.''',

                        'fees',
                        'The fee for BTech courses is around 1,80,000',

                        'history'
                         '''Vishwakarma Institute of Technology, Pune,
                         a highly commendable private institute, occupies a place of pride amongst the premier technical institutes of the western region of India.''',

                    ]     


#We can create and train the bot by creating an instance of ListTrainer and supplying it with the lists of strings:
list_trainer = ListTrainer(my_bot)
for item in (small_talk,entities):
    list_trainer.train(item)
trainer = ChatterBotCorpusTrainer(my_bot)
trainer.train('chatterbot.corpus.english.greetings')    

#You have to use get_response method to input things. Things inside the method are customizable.  
print(my_bot.get_response(input("Hello,how can I help you?")))
for i in range(10):
   print(my_bot.get_response(input()))
   #print(i)
#print(my_bot.get_response())
Esempio n. 22
0
    
    
#ChatterBot has adapter classes that allow you to connect to different types of databases.
#In my code I decided to use the SQLStorageAdapter class, as it allows me to connect to SQL databases.
#By default, it creates an SQLite database in the “chatbot.py” directory.
bot = ChatBot(
'Mike',
storage_adapter='chatterbot.storage.SQLStorageAdapter',
database_uri='sqlite:///database.sqlite3'
)
    
    
#I created a list of questions and answers that will be used as Mike's initial knowledge.
#In the code below I import the ListTrainer() method, it is responsible for allowing -> 
#my list of strings with questions and answers to be used as a basis for Mike's learning process
talk = ListTrainer(bot)
talk.train([
    "Hi there!", #User 
    "Hello", #Mike
    "How are you?", #User
    "I am good.", #Mike
    '"That is good to hear.", #User
    "Thank you",#Mike
])
sleep(0.5)

#I create an infinite loop with the while for Mike to receive the user's question, analyze, process and answer!
#in Mike's answer I use the confidence() function, to define that if the answer's confidence level is less than 0.5 ->
#he will inform you that he still does not know how to answer such a question.

#I used “Try” and “except” to be able to exit the loop and interrupt the program when a user types “ctrl + c”.
    logic_adapters=[
        'chatterbot.logic.MathematicalEvaluation',
        'chatterbot.logic.TimeLogicAdapter',
        'chatterbot.logic.BestMatch',
        {
            'import_path': 'chatterbot.logic.BestMatch',
            'default_response': 'I am sorry, but I do not understand. I am still learning.',
            'maximum_similarity_threshold': 0.90
        }
    ],
    database_uri='sqlite:///database.sqlite3'
)

from chatterbot.trainers import ListTrainer

trainer = ListTrainer(blmchatbot)

training_data_quesans = open('training_data/BLMBot_QA.txt').read().splitlines()
training_data_personal = open('training_data/BLMBot_PQ.txt').read().splitlines()

training_data = training_data_quesans + training_data_personal

trainer.train(training_data)

from chatterbot.trainers import ChatterBotCorpusTrainer

trainer_corpus = ChatterBotCorpusTrainer(blmchatbot)

trainer_corpus.train(
    'chatterbot.corpus.english'
)
Esempio n. 24
0
"چه خبر",
"سلامتی",
"حالت خوبه؟",
"بله چرا که نه"
]

personal_info = [
"when is your birthday?",
'2020 09/01/20',
'what is your name?',
'adam',


]
#Initializing Trainer Object
trainer = ListTrainer(ChatBot)

#Training BankBot
trainer.train(greet_conversation)
#trainer.train(open_timings_conversation)
#trainer.train(close_timings_conversation)
trainer.train(personal_info)
trainer.train(persian)
trainer.train(questions)


s = pyttsx3.init()
s.setProperty('rate', '110')
while (True):
    user_input = input("You:")
    if (user_input == 'quit'):
Esempio n. 25
0
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
bot = ChatBot ('Avatar',logic_adapters=[
        'chatterbot.logic.MathematicalEvaluation',
        'chatterbot.logic.BestMatch'
    ])
conversation = ['Hi','Hello', 'How are you?', 'I am fine','How old are you?', '21 years old']
trainer= ListTrainer(bot)
trainer.train(conversation)
while True:
  question = input("You: ")
  answer = bot.get_response(question)
  print('Avatar: ',answer)
  
    
  
Esempio n. 26
0
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 22:15:08 2020

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

dhory = ChatBot("Dhory")

conversa = [
    "Olá", "Eu sou a Dhory", "Como vai?", "Que legal!", "Posso lhe ajudar?"
]

treino = ListTrainer(dhory)
treino.train(conversa)

resposta = dhory.get_response("Oi")
print("Dhory: ", resposta)
Esempio n. 27
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

bot = ChatBot(
    'Irineu',
    storage_adapter = 'chatterbot.storage.SQLStorageAdapter',
    database_uri = 'sqlite:///database.sqlite3'
    )
conversa = ListTrainer(bot)
conversa.train([
    'Oi?',
    'Eae',
    'Qual seu nome?',
    'Irineu, você não sabe nem eu',
    'Prazer te conhecer',
    'Igualmente meu patrão'
])

while True:
    try:
        resposta = bot.get_response(input("Usuário: "))
        if float(resposta.confidence) > 0.5:
            print("Irineu: ", resposta)
        else:
            print("Eu não entendi :(")
            
    except(KeyboardInterrupt, EOFError, SystemExit):
        break

Esempio n. 28
0
def trainMsg(chatbot, msg1, msg2):
    trainer = ListTrainer(chatbot, show_training_progress=False)
    trainer.train([msg1, msg2])
!pip install chatterbot

!pip install chatterbot_corpus

!pip install --upgrade chatterbot

!pip install --upgrade chatterbot_corpus

from chatterbot import ChatBot

from chatterbot.trainers import ListTrainer

your_bot = ChatBot(name = "PyBot", readonly = True , logic_adapters = ['chatterbot.logic.MathematicalEvaluation','chatterbot.logic.BestMatch'])

greetings = ['hi' , 'Hello' , 'How are you?' , 'Im fine thank you.']
greetings1 = ['Hi' , 'Hello' , 'How are you?' , 'Im fine thank you.']
greetings2 = ['Hi' , 'Hello' , 'How are you?' , 'Im fine thank you.']
greetings3 = ['Hi' , 'Hello' , 'How are you?' , 'Im fine thank you.']
greetings4 = ['Hi' , 'Hello' , 'How are you?' , 'Im fine thank you.']
greetings5 = ['Hi' , 'Hello' , 'How are you?' , 'Im fine thank you.']

greetings1

train_your_bot = ListTrainer(your_bot)

for item in (greetings,greetings1,greetings2,greetings3,greetings4,greetings5):
  train_your_bot.train(item)

print(your_bot.get_response("hi"))

print(your_bot.get_response("How are you?"))
Esempio n. 30
0
    def train(self):
        trainer = ListTrainer(self.chatbot)

        with open('convos/train.json') as train:
            data = json.load(train)
            trainer.train(data)