def __init__(self, lex_happiness, lex_sadness, lex_anger, lex_fear, list_happiness, list_sadness, list_anger, list_fear, list_happiness_adj, list_sadness_adj, list_anger_adj, list_fear_adj, nlp): # this is so i dont get a minor error message every turn logger = logging.getLogger() logger.setLevel(logging.CRITICAL) # init constants self.DEBUG_COMMANDS = ["h", "s", "a", "f", "d"] self.NLP = nlp # assign emotion lexica and lists self.lex_happiness = lex_happiness self.lex_sadness = lex_sadness self.lex_anger = lex_anger self.lex_fear = lex_fear self.lex_happiness_adj = list_happiness_adj self.lex_sadness_adj = list_sadness_adj self.lex_anger_adj = list_anger_adj self.lex_fear_adj = list_fear_adj self.list_happiness = list_happiness self.list_sadness = list_sadness self.list_anger = list_anger self.list_fear = list_fear # init variables self.is_debug_input = False # intitialize the chatbot self.bot = cb.ChatBot( "chatterbot", preprocessors=['chatterbot.preprocessors.clean_whitespace'])
def _build_cb_chatbot(self): self.cb_chatbot = chatterbot.ChatBot( "ChatterBot", storage_adapter='chatterbot.storage.SQLStorageAdapter', database_uri='sqlite:///{}/ChatterBot_db.sqlite3'.format( self.db_dir), statement_comparison_function=my_cf, logic_adapters=[ { "import_path": "chatterbot.logic.BestMatch", "response_selection_method": chatterbot.response_selection.get_random_response, "maximum_similarity_threshold": self.cb_similarity_threshold, "default_response": self.cb_default_response, }, ], preprocessors=[ 'chatterbot.preprocessors.clean_whitespace', 'chatterbot.preprocessors.convert_to_ascii' ], read_only=True, ) self.cb_chatbot.storage.tagger.language = chatterbot.languages.SPA # Building Trainer self.trainer = ListTrainer(self.cb_chatbot, show_training_progress=False) return None
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json("data/chatterbot/settings.json") self.log = dataIO.load_json("data/chatterbot/log.json") self.chatbot = chatterbot.ChatBot("redbot", storage_adapter="chatterbot.storage.MongoDatabaseAdapter", # database="data/chatterbot/db", logic_adapters=[ "chatterbot.logic.BestMatch", "chatterbot.logic.TimeLogicAdapter", "chatterbot.logic.MathematicalEvaluation"] ) self.chatbot.set_trainer(ListTrainer)
def chatting(self): bot = chatterbot.ChatBot('Bot') bot.set_trainer(ListTrainer) for files in os.listdir('data/'): data = open('data/' + files, 'r').readlines() bot.train(data) v = True while v: text = input("Your message: ") if text != "bye": replay = bot.get_response(text) self.speak(replay) else: print("kora Chatbot closed!") self.speak("goodbye") v = False
def __init__(self): self.corpus = 'chatterbot.corpus.openstack.conversation' self.chatbot = chatterbot.ChatBot( 'OpenStack Bot', logic_adapters=[{ 'import_path': 'chatterbot.logic.BestMatch', }, { 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 'threshold': 0.65, 'default_response': 'I am sorry, but I do not understand.' }], response_selection_method=get_random_response) self.chatbot.set_trainer(ChatterBotCorpusTrainer) self.chatbot.train("chatterbot.corpus.english.greetings", self.corpus)
def __init__(self): # this is so i dont get a minor error message every turn logger = logging.getLogger() logger.setLevel(logging.CRITICAL) self.response = None self.response_package = {} self.bot_state_package = {} self.bot = cb.ChatBot( "chatterbot", preprocessors=[ 'chatterbot.preprocessors.clean_whitespace' ] ) self.train()
def appbot_answer(ask): bot = chatterbot.ChatBot( 'Bot', tagger_language=chatterbot.languages.VIE, storage_adapter="chatterbot.storage.SQLStorageAdapter", logic_adapters=[ 'chatterbot.logic.MathematicalEvaluation', #'chatterbot.logic.TimeLogicAdapter', 'chatterbot.logic.BestMatch' ], database_uri='sqlite:///database.db', filters=[chatterbot.filters.get_recent_repeated_responses]) trainer = chatterbot.trainers.ListTrainer(bot, show_training_progress=False) importlib.reload(conversionlib) conversion = conversionlib.conversion trainer.train(conversion) answer = bot.get_response(ask).text return answer
def load(self, config=None, state=None): super().load(config=config, state=state) importlib.reload(logic) # set our bot default config.setdefault('min_response_confidence', 0.9) config.setdefault('min_response_confidence_mentioned', 0.3) config.setdefault('max_responders', 5) config.setdefault('persona', 'Stoner') config.setdefault('read_only', True) config.setdefault('storage_adapter', 'chatterbot.storage.SQLStorageAdapter') config.setdefault('database_uri', 'sqlite:///chatter.sqlite3') config.setdefault('preprocessors', []) config.setdefault('logic_adapters', [ { "import_path" : "programs.chatter.logic.QueryLogicAdapter" }, { "import_path" : "chatterbot.logic.BestMatch", "statement_comparison_function" : "chatterbot.comparisons.SpacySimilarity", "response_selection_method" : "get_random_response" } ]) for adapter in config['logic_adapters']: response_selection_method = adapter.get('response_selection_method') if type(response_selection_method) != str: continue if hasattr(chatterbot.response_selection, response_selection_method): # this needs some work. it limits the methods to the chatterbot.response_selection module adapter['response_selection_method'] = getattr(chatterbot.response_selection, response_selection_method) else: logger.error('Invalid response_selection_method %s, using default', response_selection_method) del config['response_selection_method'] self.bot = chatterbot.ChatBot( config['persona'], read_only=config['read_only'], storage_adapter=config['storage_adapter'], database_uri=config['database_uri'], preprocessors=config['preprocessors'], logic_adapters=config['logic_adapters'] )
def __init__(self, bot): self.bot = bot self.audio_players = {} self.sound_base = "data/sfx" self.temp_filepath = self.sound_base + "/temp/" self.settings_path = "data/sfx/settings.json" self.settings = dataIO.load_json(self.settings_path) self.language = "en" self.default_volume = 75 self.tts_volume = 100 self.vc_buffers = {} self.master_queue = asyncio.Queue() # Combine slave_queues and slave_tasks into a single dict, maybe self.slave_queues = {} self.slave_tasks = {} self.queue_task = bot.loop.create_task(self._queue_manager()) #chatbot setup self.sborraBot = chatterbot.ChatBot( "Sborra bot", storage_adapter='chatterbot.storage.MongoDatabaseAdapter')
def __init__(self, name, config, personality="normal"): self.config = config #logging.basicConfig(level=logging.DEBUG) #self.logger = logging.getLogger(__name__) self.chatbot = chatterbot.ChatBot( name, filters=["chatterbot.filters.RepetitiveResponseFilter"], logic_adapters=[{ "import_path": "chatterbot.logic.BestMatch", "statemlanguageent_comparison_function": "chatterbot.comparisons.levenshtein_distance", "response_selection_method": "chatterbot.response_selection.get_first_response" }, { 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 'threshold': 0.65, 'default_response': '...' }], #storage_adapter="chatterbot.storage.MongoDatabaseAdapter", database='database_' + name) self.chatbot.set_trainer(trainer.SingleShotTrainer)
if limit and iteration > limit: return retList else: iteration += 1 currentPhrase = im.group(1) + " " elif cm: currentPhrase += cm.group(1) return retList print("making training set...") if os.path.isfile(sys.argv[1]): trainingList = makeCorpusList(sys.argv[1], 0) else: raise IOError("no such file or directory") print("setting up bot...") chatbot = chatterbot.ChatBot( 'bot', storage_adapter='chatterbot.storage.MongoDatabaseAdapter', trainer="chatterbot.trainers.ListTrainer") # Train based on provided list print("training...") chatbot.train(trainingList) print("done!") # Get a response to an input statement #print("bot, can you answer this question?") #print(chatbot.get_response("bot, can you answer this question?"))
# -*- coding: utf-8 -*- """ Created on Tue Apr 2 06:27:49 2019 @author: Mohammad Hamid & Mohammad Marwan """ # importing Packeges from flask import Flask, render_template, request import chatterbot from chatterbot.trainers import ChatterBotCorpusTrainer # Creating App varialbe for Flask app = Flask(__name__) bot = chatterbot.ChatBot('smartbot') # train the model trainer = ChatterBotCorpusTrainer(bot) trainer.train("chatterbot.corpus.english.ai") # Sending the file Index.html for get requrest on local host @app.route('/', methods=['POST', 'GET']) def main(): return render_template("index2.html") # replying to the get request by the user with the response @app.route('/get') def get_response():
def __init__(self): self.chatbot = chatterbot.ChatBot("TalkingKai", read_only=True)
UploadURL = "https://upload.facebook.com/ajax/mercury/upload.php" UserInfoURL = "https://www.facebook.com/chat/user_info/" br = mechanize.Browser() br.set_handle_equiv(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Ignore robots.txt br.set_handle_refresh(False) #Google demands a user-agent that isn't a robot br.addheaders = [('User-agent', 'Firefox')] AI_Bot = chatterbot.ChatBot( "Scofield", storage_adapter="chatterbot.adapters.storage.MongoDatabaseAdapter", io_adapters=["chatterbot.adapters.io.TerminalAdapter"], database="scofield") class Client(object): fbid = 0 ques = 'a' def __init__(self, email, password, debug=True, user_agent=None, max_retries=5):
from tkinter import Tk, PhotoImage, Label, END, Frame, Scrollbar, Listbox, Button, Entry, X, LEFT, RIGHT, Y, BOTH import chatterbot from chatterbot.trainers import ListTrainer from _tkinter import * bot = chatterbot.ChatBot("my bot") convo = [ 'what is coronavirus', 'Coronaviruses are a large family of viruses which may cause illness in animals or humans', 'what is COVID-19', 'COVID-19 is the infectious disease caused by the most recently discovered coronavirus.', 'what are the symptoms of COVID-19', 'fever,dry cough,tiredness', 'who is risk for coronavirus?', 'these are older people and who are underlying medical condition' 'what should i do if i have COVID-19 symptoms?', 'stay home,isolate from other,take who guideness', 'How can we protect others', 'if possible,maintain minimum 1 meter distance', 'what should i do if i have close contact with someone who are COVID-19 affected?' 'if you are not live in dengue infected area you can follow minimum 14 days self quarintine yourself ', 'what does mean self-quarantine?', 'Quarantine means restricting activities or separating people who are not ill themselves', 'what does mean physical distancing?', 'minimum 1 meter distance from other' 'what does it mean to self isolate? ', 'keep at least one meter from other and 14 days isolate from other', 'is there any vaccine drug or treatment?', 'clean your hand frequently and througly, Avoid touching your nose and mouth, keep minimum 1 meters distance ', 'Does who recommand medical mask for prevenet COVID-19?', 'WHO recomend N95 and sergical mask for covid-19',
import os from chatterbot.trainers import ChatterBotCorpusTrainer from chatterbot.trainers import ListTrainer from datetime import datetime #Initializing everything client = pm.MongoClient('localhost', 27017) db = client.escabot userchat = db.userchat userdata = db.userdata #bot = cb.ChatBot('ESCABOT') bot = cb.ChatBot( 'ESCABOT', storage_adapter='chatterbot.storage.MongoDatabaseAdapter', logic_adapters=[ 'chatterbot.logic.BestMatch' ], database_uri='mongodb://localhost:27017/escabot' ) #storage_adapter="chatterbot.storage.MongoDatabaseAdapter" #trainer = ChatterBotCorpusTrainer(bot) #trainer.train('chatterbot.corpus.english') if __name__ == "__main__": flag = True print("NOW RUNNNING") while True: cursor = userchat.find({"type":"sent", "replied":False}) for document in cursor:
# -*- coding: utf-8 -*- import chatterbot from chatterbot.trainers import * bot = chatterbot.ChatBot( 'Mirtheyl', storage_adapter='chatterbot.storage.SQLStorageAdapter', logic_adapters=[ 'chatterbot.logic.MathematicalEvaluation', 'chatterbot.logic.BestMatch' ], preprocessors=['chatterbot.preprocessors.clean_whitespace'], database_uri='sqlite:///database.sqlite3') ctrainer = ChatterBotCorpusTrainer(bot) ctrainer.train( "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.portuguese", ) while True: try: quest = input('Você: ') response = bot.get_response(quest) if float(response.confidence) > 0.5:
def a_chatbot_pls(read_only=False): return chatterbot.ChatBot("Kalpak", read_only=read_only)
# Create a new chat bot named Charlie chatbot = chatterbot.ChatBot("Zanuuudina", storage_adapter="chatterbot.storage.MongoDatabaseAdapter", # MongDB #storage_adapter='chatterbot.storage.SQLStorageAdapter', # SQLite3 # logic_adapters=[ # "chatterbot.logic.TimeLogicAdapter", # "chatterbot.logic.MathematicalEvaluation", # "chatterbot.logic.BestMatch", # { # 'import_path': 'chatterbot.logic.LowConfidenceAdapter', # 'threshold': 0.65, # 'default_response': 'Я не понимаю. :\'(' # } # "chatterbot.adapters.logic.ClosestMatchAdapter" # "chatterbot.adapters.logic.ClosestMeaningAdapter" # "chatterbot.adapters.logic.ApproximateSentenceMatchAdapter" # ], # filters=["chatterbot.filters.RepetitiveResponseFilter"], logic_adapters=[ 'chatterbot.logic.BestMatch' # , # { # 'import_path': 'chatterbot.logic.LowConfidenceAdapter', # 'threshold': 0.65, # 'default_response': 'Я не понимаю. :\'(' # } ], filters=[ 'chatterbot.filters.RepetitiveResponseFilter' ], database="Zanuda-01") # mongoDB #database='./Zanuda-01.sqlite3') # SQLite3
import sys import chatterbot sborraBot = chatterbot.ChatBot( "Sborra bot", storage_adapter='chatterbot.storage.MongoDatabaseAdapter') print(sborraBot.get_response(sys.argv[1]))
def chatbot_init(): chatbot = chatterbot.ChatBot( 'Pepper Chatbot', trainer='chatterbot.trainers.ChatterBotCorpusTrainer')
from flask import Flask, request, render_template, abort import chatterbot from chatterbot.conversation import Statement from timechat import IdfTimeAdapter, EntityTimeAdapter, SyntaxTimeAdapter, FallbackAdapter, Api chatbots = {} api = Api() for method, adapter_class in [('idf', IdfTimeAdapter), ('entity', EntityTimeAdapter), ('syntax', SyntaxTimeAdapter)]: chatbot = chatterbot.ChatBot('TimezoneChatBot', logic_adapters=[]) adapter = adapter_class(api) if method == 'idf': adapter.load_models('models.pickle') chatbot.logic.add_adapter(adapter) chatbot.logic.add_adapter(FallbackAdapter()) chatbots[method] = chatbot app = Flask(__name__) @app.route("/", defaults={'method': 'idf'}, methods=['GET']) @app.route("/<method>", methods=['GET']) def index(method): if method not in chatbots: abort(404) return render_template('index.html', method=method) @app.route("/handle/<method>", methods=['POST']) def handle(method):
from termcolor import colored, cprint from multiprocessing import Process, Lock name = "Loewi_proto" db_fname = "db222" my_adapters = [{ 'import_path': 'MovieAdapter.MovieInfoLogicAdapter' }, { 'import_path': 'MovieAdapter.CityMovieLogicAdapter' }, "chatterbot.logic.BestMatch"] if not os.path.exists(db_fname): # 如果不存在 DB 文件,则新建一个 bot 并重新训练 chatbot = chatterbot.ChatBot( name, storage_adapter='chatterbot.storage.SQLStorageAdapter', database=db_fname, logic_adapters=my_adapters, read_only=False) chatbot.set_trainer(chatterbot.trainers.ChatterBotCorpusTrainer) # chatbot.train( "chatterbot.corpus.english" ) # chatbot.train( "chatterbot.corpus.chinese" ) chatbot.train("myCorpus") chatbot.set_trainer(chatterbot.trainers.ListTrainer) chatbot.train([ "你好", "Hello", "哈喽", "Do you need help?" "我可以根据您所在城市推荐电影", ])
rst_statement.confidence = 1.0 return rst_statement if __name__ == "__main__": print("I am running") r = chatterbot.ChatBot( "Kala", storage_adapter='chatterbot.storage.SQLStorageAdapter', database="db_test", logic_adapters = [ { 'import_path' : 'MovieAdapter.CityMovieLogicAdapter' }, { 'import_path' : 'MovieAdapter.MovieInfoLogicAdapter' } ], read_only = True ) print( r.get_response('我在南京') ) print( r.get_response('邪不压正好不好看') ) print( r.get_response('我去,南京有啥电影') ) print( r.get_response('给我讲讲神奇马戏团之动物饼干') )
LANGUAGE = 'en-uk' OUTPUT_PATH = './audioData/speechOutput.mp3' def play_response(message): responseText = chatbot.get_response(message).text speechObject = gTTS(text=responseText, lang=LANGUAGE, slow=False) speechObject.save(OUTPUT_PATH) print('Echoing speech --> ') playsound(OUTPUT_PATH) if __name__ == '__main__': #train the chatterbot chatbot = chatterbot.ChatBot('HAL 9001') trainer = chatterbot.trainers.ChatterBotCorpusTrainer(chatbot) trainer.train('chatterbot.corpus.english') trainer.train('chatterbot.corpus.english.greetings') trainer.train('chatterbot.corpus.english.conversations') #create a recognizer object r = sr.Recognizer() #list available input devices micList = sr.Microphone.list_microphone_names() print('Available input devices: ', micList) #select an input device for the Microphone object to use DEVICE_INDEX = 5 mic = sr.Microphone(device_index = DEVICE_INDEX)
import chatterbot import os from commands import * def absolute(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) chatbot = chatterbot.ChatBot( "BergerBot", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", database=absolute("database.db")) set_train_bot(chatbot) commands = { c.name: c for c in [ helpme, train, stop, invite, echo, silentecho, WolframAlpha, Time, dateTime, date, restart, xkcd ] } cmdnames = commands.keys() def processMsg(message, userRoles): print 'processing for channel bergerbot' if message.startswith('!'): inp = message[1:] for cn in cmdnames: if inp.startswith(cn):
import chatterbot import speech_recognition as sr import pyttsx3 import sys bot=chatterbot.ChatBot('bot',trainer='chatterbot.trainers.ChatterBotCorpusTrainer') engine=pyttsx3.init() def speak(text): engine.say(text) engine.runAndWait() try: r=sr.Recognizer() while True: speak('You : ') print("you : ") with sr.Microphone() as source: audio=r.listen(source) user=r.recognize_google(audio) print("you : ",user) ans=bot.get_response(user) speak(ans) print('bot : ',ans) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") speak('google speech recognition could not understand audio') sys.exit() except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e)) sys.exit()
#Used to generate the database. If you have cloned entire repo, this file is not necessary, as a database is included. import chatterbot import parse_shakespeare def train_bot(bot, plays=["j_caesar"]): dialogue = parse_shakespeare.getDialogueList(*plays) print "Training bot based on the text of " + " and ".join( ["./shakespeare/" + p + ".xml" for p in plays]) + "...", for play in dialogue: for scene in play: bot.train(scene) print "Done!" if __name__ == "__main__": bot = chatterbot.ChatBot( "Julius Caesar", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", database="julius_caesar.db") train_bot(bot) bot.storage.read_only = True import time while 1: query = raw_input(">") a = time.time() bot.get_response(query) print time.time() - a
# importing Packeges 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")
from django.shortcuts import render from django import views from django.http import JsonResponse, HttpResponse import requests from chatterbot.trainers import ListTrainer import chatterbot import json chatbot = chatterbot.ChatBot("UICHAT") chatbot.set_trainer(ListTrainer) class ChatView(views.View): def get(self, request, *args, **kwargs): print(request.GET) text = request.GET['text'] resp = chatbot.get_response(text) if resp.confidence > 0.85: return JsonResponse({"response": str(resp)}) url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=%s&features=concepts" %(text) r = requests.get(url=url, auth=requests.auth.HTTPBasicAuth('55ea49b2-c353-463a-8d25-b3c358fa1df3', 'z5AU0l7jtd3c')).json() concept = 'general' try: concept = r['concepts'][0]['text'] except: pass dialogflow_data = { "contexts": [ concept ], "lang": "en", "query": text, "sessionId": "12345",