Exemple #1
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.conversation import Statement
from chatterbot.trainers import ChatterBotCorpusTrainer
import nltk
import ssl

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context

#initializes the trainer bot
trainer_bot = ChatBot(name="trainer")

#Make a new trainer to train the trainer bot
trainer = ChatterBotCorpusTrainer(trainer_bot)

#Trains the chatbot on the english corpus
trainer.train("chatterbot.corpus.english")
Exemple #2
0
 def _baseTrain(self):
     trainer = ChatterBotCorpusTrainer(self.chatbot)
     trainer.train('chatterbot.corpus.english')
Exemple #3
0
        'r') as file:
    data = file.readlines()
    while format_line < num_lines:
        if format_line == 0:
            data[format_line] = "- " + data[format_line]
            format_line = format_line + 1
        else:
            data[format_line] = "  " + data[format_line]
            format_line = format_line + 1

with open(
        r'C:\Users\wenka_000\Anaconda3\envs\chat\Lib\site-packages\chatterbot_corpus\data\training\trained.yml',
        'w') as file:
    file.write("categories:\n")
    file.write("- trained\n")
    file.write("conversations:\n")
    file.writelines(data)

english_bot = ChatBot(
    "Chatterbot",
    storage_adapter="chatterbot.storage.MongoDatabaseAdapter",
    logic_adapters=['chatterbot.logic.BestMatch'],
    database_uri="mongodb://localhost:27017/chatbot")
trainer = ChatterBotCorpusTrainer(english_bot)
trainer.train("chatterbot.corpus.training")

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["chatbot"]
mycol = mydb["training"]
mycol.drop()
Exemple #4
0
    def setUp(self):
        super().setUp()

        self.trainer = ChatterBotCorpusTrainer(self.chatbot,
                                               show_training_progress=False)
Exemple #5
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer
import json
import pyttsx3
import datetime
import random

ChatBot = ChatBot(name = 'BankBot',
                  read_only = False,
                  logic_adapters = ["chatterbot.logic.BestMatch"],
                  storage_adapter = "chatterbot.storage.SQLStorageAdapter")
corpus_trainer = ChatterBotCorpusTrainer(ChatBot)
corpus_trainer.train("chatterbot.corpus.english")
greet_conversation = [
    "yes",
    "ok",
    "good",
    "glad to hear it"
    "Hello",
    "Hi there!",
    "How are you doing?",
    "I'm doing great.",
    "That is good to hear",
    "Thank you.",
    "how are you?",
    "i am ok",
    "are you ok?",
    random.choice(["yes Why not?", 'It dependes']),
    "How old are you",
    "I burned In 2020 09/01/20",
Exemple #6
0
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer
import playsound
import speech_recognition as sr
from gtts import gTTS
import random

app = Flask(__name__)

credi_bot = ChatBot("CrediBot",
                    storage_adapter="chatterbot.storage.SQLStorageAdapter",
                    database_uri='sqlite:///database.sqlite3')

trainer = ChatterBotCorpusTrainer(credi_bot)
trainer.train("./data/creditos.yml")

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


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


@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
    return str(credi_bot.get_response(userText))
    # return speak(str(daliaBot.get_response(userText)))
Exemple #7
0
    '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):
        break
Exemple #8
0
def train_on_corpuses():
    trainer = ChatterBotCorpusTrainer(bot)
    trainer.train(*CORPUSES)
                      database_uri='mongodb+srv://Gabby:[email protected]/test?retryWrites=true&w=majority',# pylint: disable=line-too-long
                      statement_comparison_function=levenshtein_distance,
                      filters=[
                          'chatterbot.filters.RepetitiveResponseFilter'],
                      preprocessors=[
                          'chatterbot.preprocessors.clean_whitespace'],
                      logic_adapters=[
                          {
                              'import_path': 'chatterbot.logic.BestMatch',
                              'threshold': 0.85,
                              'default_response': 'I am sorry, but I do not understand.'
                              }
                          ]
                      )

TRAINER = ChatterBotCorpusTrainer(ENGLISH_BOT)

# For training Custom corpus data
#TRAINER.train("./data/mycorpus/")

# For training English corpus data
#TRAINER.train('chatterbot.corpus.english')

# For training list of conversations
#TRAINER_LIST = ListTrainer(ENGLISH_BOT)
#TRAINER_LIST.train([
#     "How are you?",
#     "I am good.",
#     "That is good to hear.",
#     "Thank you",
#     "You are welcome.",
Exemple #10
0
def get_chatterbot_corpus_trainer(chatbot):
    return ChatterBotCorpusTrainer(chatbot, show_training_progress=False)
Exemple #11
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
Exemple #12
0
from chatterbot.trainers import ListTrainer
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__":
Exemple #13
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,
Exemple #14
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.")
Exemple #15
0
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from tkinter import *
from flaskC.CB import CB
import yaml

app = Flask(__name__)

app.secret_key = b'\x0f~\xcfK\x08XML\x8f!\xb5\x05?\x1a9yE\x18"L\xf2\x08\x84o'

idioms = ""

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

trainer = ChatterBotCorpusTrainer(chat_bot_storage)
trainer.train("chatterbot.corpus.italian")

def startIdiomCombo():
    with open("comboIdiom.yaml", 'r') as stream:
        idioms = yaml.load(stream)
    return idioms

@app.route("/")
def home():
    idioms = startIdiomCombo()
    return render_template("index.html", idioms=idioms)

@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
Exemple #16
0
 def bot(self):
     chatbot = ChatBot("Tob")
     trainer = ChatterBotCorpusTrainer(chatbot)
Exemple #17
0
    # database_uri = "mysql://*****:*****@localhost:3306/chatbot?charset=utf8",
    database='tchatter.sqlite3',
    logic_adapters=[{
        'import_path': 'chatterbot.logic.BestMatch',
        'statement_comparison_function': LevenshteinDistance,
        # "statement_comparison_function": SentimentComparison
        # "statement_comparison_function": SynsetDistance
        # "statement_comparison_function": JaccardSimilarity,
        'response_selection_method': get_random_response,
        'default_response': default_response,
        'maximum_similarity_threshold': 0.90
    }],
    preprocessors=['chatterbot.preprocessors.clean_whitespace'],
)

trainer = ChatterBotCorpusTrainer(taklip_bot)


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


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

    return str(taklip_bot.get_response(userText))


@app.route("/chat")
Exemple #18
0
trainer.train([
    "who made you?",
    "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")
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")
# -*- 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)
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

if __name__ == '__main__':
    chatbot = ChatBot(name='house')
    ChatterBotCorpusTrainer(chatbot).train('chatterbot.corpus.english')

    done = False
    while not done:
        user_input = input('?: ')
        if user_input not in {'quit', 'bye', 'cya'}:
            print(chatbot.get_response(user_input))
        else:
            done = True
Exemple #22
0
        '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(yemenchatbot)

training_data_quesans = open('training_data/YemenBot_QA.txt').read().splitlines()
training_data_personal = open('training_data/YemenBot_PQ.txt').read().splitlines()

training_data = training_data_quesans + training_data_personal

trainer.train(training_data)

from chatterbot.trainers import ChatterBotCorpusTrainer

trainer_corpus = ChatterBotCorpusTrainer(yemenchatbot)

trainer_corpus.train(
    'chatterbot.corpus.english'
)
bot_ = ChatBot(
    'Anokha',
    storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
    logic_adapters=[
        "chatterbot.logic.BestMatch",
        "chatterbot.logic.MathematicalEvaluation",
    ],
    filters=[
        # 'chatterbot.filters.RepetitiveResponseFilter'
    ],
    database_uri='mongodb://mongo:27017/chatterbot-database')

# bot_.set_trainer(ChatterBotCorpusTrainer)
# bot_.train("chatterbot.corpus.english")

trainer = ChatterBotCorpusTrainer(bot_)

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

# 'chatterbot.corpus.english'

# In[2]:

import telepot
import time

# In[3]:

bot = telepot.Bot('258599010:AAEi9pqVhiP3h-wVw1tzCiq_elG5RuBefVc')
prevText = {}
prevReply = {}
Exemple #24
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 #25
0
def trainEnglishGreetings(chatbot):
    trainer = ChatterBotCorpusTrainer(chatbot)
    trainer.train("chatterbot.corpus.english.greetings")
    def setUp(self):
        super(ChatterBotCorpusTrainingTestCase, self).setUp()
        self.chatbot = ChatBot(**settings.CHATTERBOT)

        self.trainer = ChatterBotCorpusTrainer(self.chatbot,
                                               show_training_progress=False)
Exemple #27
0
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer

# Creating ChatBot Instance
chatbot = ChatBot('CoronaBot')

# Training with Personal Ques & Ans
conversation = [
    "Hello", "Hi there!", "How are you doing?", "I'm doing great.",
    "That is good to hear", "Thank you.", "You're welcome."
]

trainer = ListTrainer(chatbot)
trainer.train(conversation)

# Training with English Corpus Data
trainer_corpus = ChatterBotCorpusTrainer(chatbot)
trainer_corpus.train('chatterbot.corpus.english')
Exemple #28
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")
Exemple #29
0
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
#initializing chatbot
chatbot = ChatBot('Chatterbot',
                  trainer='chatterbot.trainers.CorpusTrainer',
                  storage_adapter='chatterbot.storage.SQLStorageAdapter',
                  database_uri='sqlite:///django_chatterbot_statement.sqlite3')
import logging
#initializing trainer
trainer = ChatterBotCorpusTrainer(chatbot)

#training the chatbot with yml files present in the location specified
trainer.train('./training_data/')

#logging to the console when the data is entered
logging.basicConfig(filename="./log.txt",
                    format='%(asctime)s - %(message)s',
                    datefmt="%d-%b-%y  %H:%M:%S",
                    level=logging.INFO)
logging.info('Training data added to database')
Exemple #30
0
 def train(self):
     self.trainer = ChatterBotCorpusTrainer(self.bot)
     self.trainer.train(self.train_data_path)