def open(self): chatbot = ChatBot( 'Captain Phasma', trainer='chatterbot.trainers.ChatterBotCorpusTrainer' ) chatbot.train("chatterbot.corpus.english") self.chatbot = chatbot
def test_training_with_unicode_characters(self): """ Ensure that the training method adds unicode statements to the database. """ import os bot = ChatBot("Test Bot2", database="unicode-database.db") conversation = [ u"¶ ∑ ∞ ∫ π ∈ ℝ² ∖ ⩆ ⩇ ⩈ ⩉ ⩊ ⩋ ⪽ ⪾ ⪿ ⫀ ⫁ ⫂ ⋒ ⋓", u"⊂ ⊃ ⊆ ⊇ ⊈ ⊉ ⊊ ⊋ ⊄ ⊅ ⫅ ⫆ ⫋ ⫌ ⫃ ⫄ ⫇ ⫈ ⫉ ⫊ ⟃ ⟄", u"∠ ∡ ⦛ ⦞ ⦟ ⦢ ⦣ ⦤ ⦥ ⦦ ⦧ ⦨ ⦩ ⦪ ⦫ ⦬ ⦭ ⦮ ⦯ ⦓ ⦔ ⦕ ⦖ ⟀", u"∫ ∬ ∭ ∮ ∯ ∰ ∱ ∲ ∳ ⨋ ⨌ ⨍ ⨎ ⨏ ⨐ ⨑ ⨒ ⨓ ⨔ ⨕ ⨖ ⨗ ⨘ ⨙ ⨚ ⨛ ⨜", u"≁ ≂ ≃ ≄ ⋍ ≅ ≆ ≇ ≈ ≉ ≊ ≋ ≌ ⩯ ⩰ ⫏ ⫐ ⫑ ⫒ ⫓ ⫔ ⫕ ⫖", u"¬ ⫬ ⫭ ⊨ ⊭ ∀ ∁ ∃ ∄ ∴ ∵ ⊦ ⊬ ⊧ ⊩ ⊮ ⊫ ⊯ ⊪ ⊰ ⊱ ⫗ ⫘", u"∧ ∨ ⊻ ⊼ ⊽ ⋎ ⋏ ⟑ ⟇ ⩑ ⩒ ⩓ ⩔ ⩕ ⩖ ⩗ ⩘ ⩙ ⩚ ⩛ ⩜ ⩝ ⩞ ⩟ ⩠ ⩢", ] bot.train(conversation) response = bot.get_response(conversation[1]) os.remove("unicode-database.db") self.assertEqual(response, conversation[2])
class Bot: def __init__(self, session): self.session = session self.chatbot = ChatBot(session) self.training() print session, " Initialized!" def training(self): # Train based on the english corpus print "Training . . ." self.chatbot.train("chatterbot.corpus.english") self.chatbot.train("chatterbot.corpus.italian") def getSession(self): print self.session return self.session # def getCreateDate(): # return self.createDate def getResponse(self, msg): response = self.chatbot.get_response(msg) return response
async def talk(self, ctx): """Command that implements the talk to the bot function. It uses ChatterBot, is a machine-learning based conversational dialog engine build in Python which makes it possible to generate responses based on collections of known conversations **Dependencies**: pip install chatterbot **Keyword arguments**: chatbot -- stores chatbot object ctx -- Context reference to get message tts -- Set to true for text to speed implementation """ chatbot = ChatBot("Ron Obvious") chatbot.train("chatterbot.corpus.english") msg = ctx.message.content print(msg) if msg.startswith('$talk'): msg = msg[6:] print(msg) reply = chatbot.get_response(msg) await self.bot.send_message(ctx.message.channel, reply, tts=True)
def test_training_adds_statements(self): """ Test that the training method adds statements to the database. """ import os bot = ChatBot("Test Bot2", database="test-database-2") conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm great.", "That is good to hear", "Thank you.", "You are welcome.", "Sure, any time.", "Yeah", "Can I help you with anything?" ] bot.train(conversation) response = bot.get_response("Thank you.") os.remove("test-database-2") self.assertEqual(response, "You are welcome.")
def baseTest(): deepThought = ChatBot("deepThought") deepThought.set_trainer(ChatterBotCorpusTrainer) # 使用中文语料库训练它 deepThought.train("chatterbot.corpus.chinese") # 语料库 print(deepThought.get_response(u"很高兴认识你")) print(deepThought.get_response(u"嗨,最近如何?")) print(deepThought.get_response(u"复杂优于晦涩")) #语出 The Zen of Python print(deepThought.get_response(u"面对模棱两可,拒绝猜测的诱惑.")) print(deepThought.get_response(u"你叫什么名字?"))
class Train(object): def __init__(self, chatbot_name='Thought'): self.model_name = chatbot_name self.model = ChatBot(chatbot_name, trainer='chatterbot.trainers.ChatterBotCorpusTrainer') self.model.train('chatterbot.corpus.chinese') self.model.train('chatterbot.corpus.english') self.model.set_trainer(ListTrainer) def train(self, train_data_list): assert isinstance(train_data_list, list) self.model.train(train_data_list)
def makeBot(playName,name): pame = name.replace(".","") pame = pame.replace("/","") pame = filter(lambda x: x in string.printable,pame) bot = ChatBot(pame) bot.gg() bot = ChatBot(pame) print playName+'.'+pame print os.getcwd() bot.train(playName+'.'+pame) return bot
def response(a): chatbot = ChatBot("Ron Obvious") chatbot.set_trainer(ChatterBotCorpusTrainer) chatbot.train("chatterbot.corpus.english") b = str(chatbot.get_response(a)) return b
def testAddTraining(): from chatterbot.trainers import ListTrainer deepThought = ChatBot("Training demo") deepThought.set_trainer(ListTrainer) deepThought.train([ u"嗳,渡边君,真喜欢我?", u"那还用说?", u"那么,可依得我两件事?", u"三件也依得", ]) print(deepThought.get_response(u"真喜欢我?")) #不必完全匹配 print(deepThought.get_response(u"那用说?"))
def run(password, name='Black Jesus', username='******', learn_mentions=True): chatbot = ChatBot(name, storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter", io_adapter="chatterbot.adapters.io.NoOutputAdapter", database="database.db") chatbot.train('chatterbot.corpus.english') print('\nInitializing Discord Chatbot') print('Logging in as {}.'.format(name)) print('Username: {}'.format(username)) print('Password: {}\n'.format(password)) logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) client = discord.Client() client.login(username, password) def process_message(message): message = message.replace('<@{}>'.format(client.user.id), '') # remove the bot's id. if not learn_mentions: for match in re.finditer('(<@\d+>)', message, re.IGNORECASE): # remove mentions message = message.replace(match.groups(1), '') return message.strip() def should_skip_message(message): return False @client.event def on_message(message): if message.author == client.user: # learning from yourself is an exercise in futility return processed_message = process_message(message.content) if should_skip_message(message.content): return bot_response = chatbot.get_response(processed_message) # learn everything! if client.user in message.mentions: client.send_message(message.channel, bot_response) print('Running...') client.run()
class reply_engine: bot = None def init(self): self.bot = ChatBot( "Lisa", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter", io_adapter="chatterbot.adapters.io.NoOutputAdapter", database="../database.db", ) self.bot.train("chatterbot.corpus.english") def get_reply(self, data): return self.bot.get_response(data)
class Chatbrain (): def __init__(self): self.brain = ChatBot("Adolfo", storage_adapter = "chatterbot.adapters.storage.MongoDatabaseAdapter", logic_adapters=["chatterbot.adapters.logic.EvaluateMathematically", #"chatterbot.adapters.logic.TimeLogicAdapter"]) "chatterbot.adapters.logic.ClosestMatchAdapter"], io_adapter="chatterbot.adapters.io.SelectiveAdapter") self.brain.train("chatterbot.corpus.Portuguese.conversations_pt-BR") def respond(self, textin): return self.brain.get_response(textin) def read(self, inputc): self.brain.io.process_input(statement=inputc)
def create_chatter_bot(self): logging.info('Creating ChatBot...') chatterbot = ChatBot( self.config['botname'], # TODO move to config database="/var/lib/yobot/chatterbot.db", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", logic_adapters=[ # "chatterbot.adapters.logic.EvaluateMathematically", "chatterbot.adapters.logic.ClosestMatchAdapter" ], io_adapter="chatterbot.adapters.io.NoOutputAdapter", ) chatterbot.train("chatterbot.corpus.english") logging.info('ChatBot initialized') return chatterbot
def handle(self, *args, **options): from chatterbot import ChatBot from chatterbot.ext.django_chatterbot import settings chatterbot = ChatBot(**settings.CHATTERBOT) chatterbot.train(chatterbot.training_data) # Django 1.8 does not define SUCCESS if hasattr(self.style, "SUCCESS"): style = self.style.SUCCESS else: style = self.style.NOTICE training_class = chatterbot.trainer.__class__.__name__ self.stdout.write(style('ChatterBot trained using "%s"' % training_class))
class GoodFoodBot: def __init__(self): self.bot = ChatBot('Good Food Bot') print 'start training' # Train based on the english conversations corpus print 'finished training' def train_bot(self): chunks = self.get_chunks(self.clean_dataset, 100) print 'start chunk training' for chunk, i in chunks: self.bot.train(chunk) print 'finished chunk %s' % i print 'finished training with movie_lines' def clean_dataset(self): n = path.join(path.dirname(__file__), 'data/movie_lines.txt') file = open(n, 'r') array = file.read().split('\n') mapped_arr = map(lambda txt: txt.split(' +++$+++ ')[-1:][0], array[0:1000]) return mapped_arr def format_data(self, arr): return map(lambda txt: txt.split(' +++$+++ ')[-1:][0], arr) def get_response(self, text): return self.bot.get_response(text) def get_chunks(self, arr, n): # Declare some empty lists chunk = [] chunks = [] # Step through the data n elements # at a time for x in range(0, len(arr), n): # Extract n elements chunk = arr[x:x+n] # Add them to list chunks.append(chunk) # Return the new list return chunks
def load_chatbot(): try: chatbot = pickle.load(open(CHATBOT_PKL_PATH, 'rb')) except FileNotFoundError: print('Chatbot not found at {}, regenerating'.format(CHATBOT_PKL_PATH)) chatbot = ChatBot("Machine Salesman") chatbot.set_trainer(ChatterBotCorpusTrainer) chatbot.train('chatterbot.corpus.english') # This is taking too long... skip for now # chatbot.set_trainer(ListTrainer) # for chat in load_chat_histories(): # chatbot.train([message.text for message in chat.messages]) pickle.dump(chatbot, open(CHATBOT_PKL_PATH, 'wb')) return chatbot
def post(self, request, *args, **kwargs): """ Return a response to the statement in the posted data. """ input_data = json.loads(request.read().decode('utf-8')) #self.validate(input_data) #print "******* input_data : " + json.dumps(input_data) print "******* input_data : " + input_data.get("text") chatbot = ChatBot( 'tony bot 01', logic_adapters=[ { 'import_path': 'chatterbot.logic.BestMatch' }, { 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 'threshold': 0.33, 'default_response': u'그 질문에 대해서는 내가 대답해 줄 수 있는 게 없어. || 해당 질문에 대답하기를 원한다면 다음 링크를 통해서 너의 의견을 제안해 주면 고맙겠어. || <a href="http://35.189.163.55:8080/anemo/trainingUI/chatterbot_UI.html">임시 학습 페이지 링크</a>' } ], trainer='chatterbot.trainers.ChatterBotCorpusTrainer' ) # Train based on the english corpus chatbot.train("/Users/kimtony/workspace/anemonlp/AnemoNLP/App/MLBot/chatterbot/corpus") #conversation = self.get_conversation(request) #response = self.chatterbot.get_response(input_data, conversation.id) #response_data = response.serialize() response = unicode(chatbot.get_response(input_data)).encode("utf8") print "******* response : " + response response_data = { 'text': response } return JsonResponse(response_data, status=200)
class Conversation(Adaptor): def __init__(self, options): super(Conversation, self).__init__(options) if 'logic_adapters' not in options: options["logic_adapters"] = [ "chatterbot.adapters.logic.ClosestMatchAdapter", "chatterbot.adapters.logic.EvaluateMathematically", "chatterbot.adapters.logic.TimeLogicAdapter" ] self.chatbot = ChatBot("Salvius", **options) self.chatbot.train( "chatterbot.corpus.english" ) def respond(self, text): return self.chatbot.get_response(text)
class ChatBotTestCase(TestCase): def setUp(self): """ Set up a database for testing. """ import os data1 = [ "african or european?", "Huh? I... I don't know that.", "How do you know so much about swallows?" ] data2 = [ "Siri is adorable", "Who is Seri?", "Siri is my cat" ] data3 = [ "What... is your quest?", "To seek the Holy Grail.", "What... is your favourite colour?", "Blue." ] self.chatbot = ChatBot("Test Bot") self.chatbot.database.set_path("test-database.db") self.chatbot.train(data1) self.chatbot.train(data2) self.chatbot.train(data3) def tearDown(self): """ Remove the log files that were created for testing. """ import os os.remove(self.chatbot.database.path)
class Chatter: """ Chatter is the core class involved with the integration with ChatterBot. It handles abstracting all interactions with ChatterBot. """ def __init__(self): self.chat_bot = ChatBot( 'JenkiesBot', storage_adapter='chatterbot.adapters.storage.JsonDatabaseAdapter', logic_adapters=[ 'chatterbot.adapters.logic.ClosestMeaningAdapter', 'chatterbot.adapters.logic.ClosestMatchAdapter' ], database='./chat-storage.json') # Training self.chat_bot.set_trainer(ChatterBotCorpusTrainer) self.train_from_corpa() def train_from_corpa(self): """ Trains the ChatterBot instance.""" self.chat_bot.train('chatterbot.corpus.english') self.chat_bot.train('.corpa') def add_axiom(self, statement: str, responses: str): """ Adds the user's supplied axiom to the axiom file.""" def update_axiom_json(json_file_contents: dict) -> dict: """ Used as the call back for add_axiom()'s call to update_json_file. Describes how we should add a new axiom to our training corpa json file. """ json_file_contents['axioms'].append([ statement ] + responses) return json_file_contents update_json_file('../corpa/training-corpa.json', update_axiom_json) # Retraining is required now! self.train_from_corpa() def get_reply(self, message): """ Abstracts away the to our bots method for retrieving a repsonse.""" return self.chat_bot.get_response(message)
def assert_response_duration(self, maximum_duration, test_kwargs): """ Assert that the response time did not exceed the maximum allowed amount. """ from sys import stdout chatbot = ChatBot('Benchmark', **test_kwargs) chatbot.train(STATEMENT_LIST) duration = utils.get_response_time(chatbot) stdout.write('\nBENCHMARK: Duration was %f seconds\n' % duration) if duration > maximum_duration: raise AssertionError( '{duration} was greater than the maximum allowed ' 'response time of {maximum_duration}'.format( duration=duration, maximum_duration=maximum_duration ) )
class reply_engine: bot = None def init(self): self.bot = ChatBot( "Lisa", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter", io_adapter="chatterbot.adapters.io.NoOutputAdapter", database="database/database.db", ) def get_reply(self, data): return self.bot.get_response(data) def train(self): trainingData = [] print "Input Converstion" while True: data = raw_input() if data == "#": break trainingData.append(data) self.bot.train(trainingData)
class ChatBotTestCase(TestCase): def setUp(self): """ Set up a database for testing. """ data1 = [ "african or european?", "Huh? I... I don't know that.", "How do you know so much about swallows?" ] data2 = [ "Siri is adorable", "Who is Seri?", "Siri is my cat" ] data3 = [ "What... is your quest?", "To seek the Holy Grail.", "What... is your favourite colour?", "Blue." ] self.chatbot = ChatBot("Test Bot", database="test-database.db") self.chatbot.train(data1) self.chatbot.train(data2) self.chatbot.train(data3) def tearDown(self): """ Remove the test database. """ self.chatbot.storage.storage_adapter.drop()
class ChatterBotCorpusTrainingTestCase(TestCase): """ Test case for training with data from the ChatterBot Corpus. Note: This class has a mirror tests/training_tests/ """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot = ChatBot(**settings.CHATTERBOT) self.chatbot.set_trainer(ChatterBotCorpusTrainer) def tearDown(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.storage.drop() def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertEqual(['greetings'], statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement)
class Bot(object): def __init__(self, config_file): config = json.load(open(config_file)) self.chatbot = ChatBot( 'Robot Overload', io_adapter='chatterbot.adapters.io.NoOutputAdapter', database=config['database']) self.chatbot.train('chatterbot.corpus.english') self.chatbot.train('chatterbot.corpus.english.greetings') self.chatbot.train('chatterbot.corpus.english.conversations') self.token = config['token'] self.bot_id = config['bot_id'] self.slack_client = None def connect(self): self.slack_client = SlackClient(self.token) self.slack_client.rtm_connect() self.last_ping = 0 def start(self): self.connect() while True: for reply in self.slack_client.rtm_read(): self.input(reply) self.autoping() time.sleep(.1) def input(self, data): text = data.get('text', '') if data.get('type') == 'message' and self.bot_id in text: channel = data['channel'] text = text.replace(self.bot_id, '') response = self.chatbot.get_response(text) self.output([channel, response]) def output(self, output): limiter = False channel = self.slack_client.server.channels.find(output[0]) if channel != None and output[1] != None: if limiter == True: time.sleep(.1) limiter = False message = output[1].encode('ascii','ignore') channel.send_message("{}".format(message)) limiter = True def autoping(self): now = int(time.time()) if now > self.last_ping + 3: self.slack_client.server.ping() self.last_ping = now
class TalkManager: """ Class Managing the discussions held by Ariia and her training. """ def __init__(self): """ Constructor """ self.ariiaTalker = ChatBot("Ariia") self.talk = None self.ariiaTalker.set_trainer(ListTrainer) self.ariiaTalker.train([ "comment vas-tu", "ça va bien merci, et toi ?", "très bien !", "moi ça va.", "je suis en pleine forme !", ]) self.ariiaTalker.train([ "comment tu t'appelles", "Ariia", ]) self.ariiaTalker.train([ "qui est ton Créateur", "un programmeur du dimanche.", ]) def getTalk(self, dialog): """ Specify the speech answering the user's dialog Parameters : dialog - The dialog held by the user """ self.talk = unicode(self.ariiaTalker.get_response(dialog)) self.talk = self.talk.encode('utf-8') print type(self.talk) return self.talk
“不要” "其次,爷每周还更新一次所有股票的背景资料,你想听谁的背景资料吗?本宝可以很有耐心的读给你听哦。" “不要” "最后就是上帝给我创造了算法,让我从众多的热点新闻中挑选最匹配的股票然后推荐给您" ] conversation=[ "给我推荐股票?", answer, "为什么?", why, "美国近期的gdp是多少?", answer1, "华夏银行2018年一季度的营业额是多少?", answer2, ] my_bot.train(conversation) myself = bot.friends().search('forex')[0] # 向文件传输助手发送消息 myself.send('Hello!') @bot.register(myself) def reply_my_friend(msg): print(msg) print(answer) ans = my_bot.get_response(msg) myself.send(ans) return myself.get_response(msg.text).tex# 使用机器人进行自动回复 # 堵塞线程,并进入 Python 命令行 embed()
from chatterbot.trainers import ListTrainer from chatterbot import ChatBot import os bot = ChatBot('Test') bot.set_trainer(ListTrainer) for _file in os.listdir('files'): chats = open('files/' + _file, 'r').readlines() bot.train(chats) while True: request = input('You: ') response = bot.get_response(request) print('Bot: ', response)
from chatterbot import ChatBot import logging ''' This is an example showing how to train a chat bot using the Ubuntu Corpus of conversation dialog. ''' # Enable info level logging logging.basicConfig(level=logging.INFO) chatbot = ChatBot( 'Example Bot', trainer='chatterbot.trainers.UbuntuCorpusTrainer' ) # Start by training our bot with the Ubuntu corpus data chatbot.train() # Now let's get a response to a greeting response = chatbot.get_response('How are you doing today?') print(response)
bot = ChatBot('Default Response Example Bot', storage_adapter='chatterbot.storage.JsonFileStorageAdapter', logic_adapters=[{ 'import_path': 'chatterbot.logic.BestMatch' }, { 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 'threshold': 0.65, 'default_response': 'Say what?' }], trainer='chatterbot.trainers.ListTrainer') # Train the chat bot with a few responses bot.train([ 'Im off hours', 'What are we going to do', 'Youre drunk', 'lets get drunk', 'lets go to alvarado street brewery', 'Im hungry', 'whats wrong', 'whats wroooong', 'speaking of drinking, whens everyone free next week', 'this is so janky', 'hello beautiful', 'watup cuz', 'Im so beautiful', 'Im so smart', 'Im so humble' ]) #these lists will contain all the messages and people that are connected all_users = [] all_messages = [] def getBotResponse(someString): if '!! about' in someString: msg = "This web app is an open chatroom" #chat with the bot elif '!! bot' in someString:
def process(self, statement): import random # Randomly select a confidence between 0 and 1 confidence = random.uniform(0, 1) # For this example, we will just return the input as output selected_statement = statement selected_statement.confidence = confidence return selected_statement bot = ChatBot("Chippy", logic_adapters=["chatterbot.logic.BestMatch"]) conversa0= ['oi', 'olá', 'tudo bem', 'sim', 'tchau'] bot.set_trainer(ListTrainer) bot.train(conversa0) chamar = input('Inicializar: ') while chamar == 'Elliot': #while True: #quest != 'tchau.': print("############################################################################################") quest = input('Você: ') resposta = bot.get_response(quest) if float(resposta.confidence) > 0.6: print('Elliot: ', resposta) elif quest == 'tchau':
class autoBot(): # metodo _init_ é chamdo ao criar um novo objecto desta class def __init__(self, nome): try: memoria = open(nome + '.json', 'r') except FileNotFoundError: memoria = open(nome + '.json', 'w') memoria.write('["Luís"]') memoria.close() memoria = open(nome + '.json', 'r') self.nome = nome self.conhecidos = json.load(memoria) memoria.close() self.FB_API_URL = 'https://graph.facebook.com/v2.6/me/messages' self.VERIFY_TOKEN = 'TESTINGTOKEN' self.PAGE_ACCESS_TOKEN = 'EAAEZBu5BhT0IBAGPTXyW34wLD7dxZCxxekenKkbu59FIDoMKZBMLIpBFTNadMapOAgq1tnIk5cAiJvGvnDlFg55FrXpP6HRuQpulMOUZAKdn6QHa86a26TqsmLYOValiIcZCo9EnF4P1vGpp1lfx1M84klEx2rzqGADue8c6ZBIUtcYLPfG0h6' self.historico = [] self.bot = ChatBot('LUNA') self.regex = "" def addRegex(self, regex): self.regex = regex # metodos principais def start(self): print('Olá, qual é o seu nome?') frase = input('>: ') nome = self.catchName(frase) frase = self.speakName(nome) print(frase) def training(self): print("Vou aquirir conhecimento") self.bot.set_trainer(ListTrainer) for _file in os.listdir('chats'): print(_file) lines = open('chats/' + _file, 'r').readlines() self.bot.train(lines) def listen(self): frase = input('>: ') frase = frase.lower() self.historico.append(frase) return frase def think(self, frase): resultado = self.regex.resp(frase) if resultado != "Não entendi": return resultado if 'aprende' in str(frase): return self.learn() if 'executa' in str(frase): return self.run(frase) try: return self.calculate(frase) except: pass return self.bot.get_response(frase) def thinkfb(self, frase): resultado = self.regex.resp(frase) if resultado != "Não entendi": return "{}".format(resultado) try: return "{}".format(self.calculate(frase)) except: pass return "{}".format(self.bot.get_response(frase)) def speak(self, frase): print(frase) self.historico.append(frase) # metodos secundarios ou auxiliares # metodos auxiliar em start def catchName(self, nome): if 'o meu nome é ' in nome: nome = nome[13:] if 'eu sou o ' in nome: nome = nome[9:] if 'eu sou a ' in nome: nome = nome[9:] nome = nome.title() return nome def speakName(self, nome): if nome in self.conhecidos: frase = 'Olá ' else: frase = 'Muito Prazer ' self.conhecidos.append(nome) memoria = open(self.nome + '.json', 'w') json.dump(self.conhecidos, memoria) memoria.close() return frase + nome def learn(self): chave = input('Digite a palvra chave: ') resp = input('Digite a resposta: ') self.regex.respostas[chave] = resp return 'Aprendido' def run(self, frase): try: plataforma = sys.platform comando = str(frase).replace('executa ', '') if 'win' in plataforma: os.startfile(comando) if 'linux' in plataforma: try: s.Popen(comando) except FileNotFoundError: s.Popen(["xdg-open", comando]) if 'linux2' in platforma: subprocess.call(["xdg-open", comando]) except: pass return 'A tentar Executar!!' def calculate(self, frase): resp = str(eval(frase)) return resp # metodos auxiliares em resp def getData(self): now = datetime.now() resp = "" resp += str(now.day) resp += "/" resp += str(now.month) resp += "/" resp += str(now.year) return resp def getHora(self): now = datetime.now() resp = "" resp += str(now.hour) resp += ":" resp += str(now.minute) return resp def weather(self): data = urllib2.urlopen( "http://api.openweathermap.org/data/2.5/weather?q=Braga,PT&lang=pt&units=metric&type=acurrate&APPID=da5dbcbe2ab4a84aee5e7da42cf7666b" ) html = data.read() html = html.decode("utf-8") weather = json.loads(html) main = str(weather['weather'][0]["main"]) descricao = str(weather['weather'][0]['description']) temperatura = str(weather['main']['temp']) + 'º Graus' temperatura_min = str(weather['main']['temp_min']) temperatura_max = str(weather['main']['temp_max']) humidade = str(weather['main']['humidity']) + '%' resp = '##########################\n\n' resp += main + ' => ' + descricao + '\n' resp += 'Temperatura: ' + temperatura + ' => [' + temperatura_min + 'º,' + temperatura_max + 'º]\n' resp += 'Humidade => ' + humidade resp += '\n\n##########################' return resp def dictionaryQuery(self, palavra): data = urllib2.urlopen("http://dicionario-aberto.net/search-json/" + palavra) html = data.read() html = html.decode("utf-8") dic = json.loads(html) i = 0 j = 0 resp = "" if 'superEntry' in dic: for a in dic['superEntry']: i = 0 for b in dic['superEntry'][j]['entry']['sense']: resp += "\n=> " resp += dic['superEntry'][j]['entry']['sense'][i]['def'] i += 1 resp += "\n" j += 1 else: for b in dic['entry']['sense']: resp += "\n=> " resp += dic['entry']['sense'][i]['def'] i += 1 resp += "\n" resp = resp.replace('<br/>', '') return resp def news(self): data = urllib2.urlopen( "https://newsapi.org/v2/top-headlines?country=pt&apiKey=626c562e3c144e6da1303da6f84ebf1f" ) html = data.read() html = html.decode("utf-8") news = json.loads(html) resp = "" i = 0 for a in news['articles']: if i < 3: resp += "\n################\n" resp += news['articles'][i]['title'] + '\n' resp += news['articles'][i]['url'] + '\n' i += 1 print(resp) return resp def canteenMenu(self): resp = "" SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('calendar', 'v3', http=creds.authorize(Http())) # Call the Calendar API now = datetime.utcnow().isoformat() + 'Z' resp += 'Os Proximos 10 Dias:\n' events_result = service.events().list( calendarId='*****@*****.**', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) meses = [ 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro' ] if not events: resp += 'Não existem Eventos!' for event in events: start = event['start'].get('dateTime', event['start'].get('date')) a, b = start.split('T') ano, mes, dia = a.split('-') data = "Dia " + str(dia) + " de " + meses[int(mes) - 1] resp += data + '=>' + event['summary'] + '\n' return resp def music(self, musica, artista): data = urllib2.urlopen("https://api.vagalume.com.br/search.php?art=" + artista + "&mus=" + musica + "&apikey=0c7c3e61ae19d03c25c287686b61892c") html = data.read() html = html.decode("utf-8") musc = json.loads(html) resp = '##########################\n\n' resp += musc['mus'][0]['text'] resp += '\n\n##########################' return resp def trmusic(self, musica, artista): data = urllib2.urlopen("https://api.vagalume.com.br/search.php?art=" + artista + "&mus=" + musica + "&apikey=0c7c3e61ae19d03c25c287686b61892c") html = data.read() html = html.decode("utf-8") musc = json.loads(html) resp = '##########################\n\n' resp += musc['mus'][0]['translate'][0]['text'] resp += '\n\n##########################' return resp def pesquisa(self, palavra): resp = "" resp += '\n\n### ' resp += "Veja o que encontrei na internet" resp += ' ###\n\n' resp += palavra.upper() resp += '\n\n' api_key = "AIzaSyCG5rnXXaaTfbrMzfwmB-1khzNeIgtYo2g" cse_id = "000833984522281484892:irqcmaus5_e" service = build("customsearch", "v1", developerKey=api_key) res = service.cse().list(q=palavra, cx=cse_id, num=3).execute() searchData = res['items'] resp += "#######################\n" for er in searchData: title = er['title'] resp += "\n=>Titulo: " resp += title resp += "\n" link = er['link'] if 'pagemap' in er: if 'metatags' in er['pagemap']: if 'og:description' in er['pagemap']['metatags'][0]: description = er['pagemap']['metatags'][0][ 'og:description'] resp += "=>Descrição: " resp += description resp += "\n" resp += "=>Link: " resp += link resp += "\n\n#######################\n" return resp def verify_webhook(self, req): if req.args.get("hub.verify_token") == self.VERIFY_TOKEN: return req.args.get("hub.challenge") else: return "incorrect" def is_user_message(self, message): return (message.get('message') and message['message'].get('text') and not message['message'].get("is_echo")) def speakfb(self, recipient_id, text): payload = { 'message': { 'text': text }, 'recipient': { 'id': recipient_id }, 'notification_type': 'regular' } auth = {'access_token': self.PAGE_ACCESS_TOKEN} response = requests.post(self.FB_API_URL, params=auth, json=payload) return response.json() def listenfb(self): text = "" sender_id = "" if request.method == 'GET': return self.verify_webhook(request) if request.method == 'POST': payload = request.json event = payload['entry'][0]['messaging'] for x in event: if self.is_user_message(x): text = x['message']['text'] sender_id = x['sender']['id'] return (sender_id, text)
# -*- coding:utf-8 -*- from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer deepThought = ChatBot("deepThought") deepThought.set_trainer(ChatterBotCorpusTrainer) # 使用中文语料库训练它 deepThought.train("chatterbot.corpus.chinese") # 语料库 print(deepThought.get_response("很高兴认识你".encode("utf8"))) print(deepThought.get_response("嗨,最近如何?".encode("utf8"))) print(deepThought.get_response("复杂优于晦涩".encode("utf8"))) #语出 The Zen of Python print(deepThought.get_response("面对模棱两可,拒绝猜测的诱惑.".encode("utf8"))) print(deepThought.get_response("生命、宇宙以及世间万物的终极答案是什么?".encode("utf8")))
#!/usr/bin/python # -*- coding: utf-8 -*- from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from chatterbot.trainers import ChatterBotCorpusTrainer my_bot = ChatBot("Training demo", database="./db.sqlite3") # 直接写语句训练 my_bot.set_trainer(ListTrainer) my_bot.train([ "你叫什么名字?", "我叫小白兔!", ]) my_bot.train([ "Test1", "Test2", "Test3", "Test4", ]) # 使用自定义语句训练它 my_bot.set_trainer(ChatterBotCorpusTrainer) my_bot.train("chatterbot.corpus.mytrain") # while True: # print(my_bot.get_response(input("user:")))
def entrena(): bot = ChatBot("Yocasta") bot.set_trainer(ChatterBotCorpusTrainer) bot.train("./plantilla/saludo.yml", "./plantilla/yocasta.yml", "./plantilla/drp.yml", "./plantilla/general.yml", "./plantilla/nube.yml")
class wppbot: dir_path = os.getcwd() def __init__(self, nome_bot): print(self.dir_path) self.nome_bot = nome_bot self.bot = ChatBot(nome_bot) self.bot.set_trainer(ListTrainer) self.chrome = self.dir_path+'/chromedriver' self.options = webdriver.ChromeOptions() self.options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4086.0 Safari/537.36") self.options.add_argument(r"user-data-dir="+self.dir_path+"/profile/wpp") self.driver = webdriver.Chrome(self.chrome, chrome_options=self.options) def inicia(self,nome_contato): self.driver.get('https://web.whatsapp.com/') self.driver.implicitly_wait(30) self.caixa_de_pesquisa = self.driver.find_element_by_xpath("//div[@class='_3u328 copyable-text selectable-text']") self.caixa_de_pesquisa.send_keys(nome_contato) time.sleep(2) print(nome_contato) self.contato = self.driver.find_element_by_xpath(f"//span[@title='{nome_contato}']") self.contato.click() time.sleep(2) def saudacao(self,frase_inicial): self.caixa_de_mensagem = self.driver.find_element_by_class_name('_13mgZ') if type(frase_inicial) == list: for frase in frase_inicial: self.caixa_de_mensagem.send_keys(frase) time.sleep(1) self.botao_enviar = self.driver.find_element_by_xpath("//span[@data-icon='send']") self.botao_enviar.click() time.sleep(1) else: return False def escuta(self): post = self.driver.find_elements_by_class_name('_1zGQT') ultimo = len(post) - 1 texto = post[ultimo].find_element_by_css_selector('span.selectable-text').text return texto def aprender(self,ultimo_texto,frase_inicial,frase_final,frase_erro): self.caixa_de_mensagem = self.driver.find_element_by_class_name('_13mgZ') self.caixa_de_mensagem.send_keys(frase_inicial) time.sleep(1) self.botao_enviar = self.driver.find_element_by_xpath("//span[@data-icon='send']") self.botao_enviar.click() self.x = True while self.x == True: texto = self.escuta() if texto != ultimo_texto and re.match(r'^\.\.\.', texto): if texto.find('?') != -1: ultimo_texto = texto texto = texto.replace('...', '') texto = texto.lower() texto = texto.replace('?', '?*') texto = texto.split('*') novo = [] for elemento in texto: elemento = elemento.strip() novo.append(elemento) self.bot.train(novo) self.caixa_de_mensagem.send_keys(frase_final) time.sleep(1) self.botao_enviar = self.driver.find_element_by_xpath("//span[@data-icon='send']") self.botao_enviar.click() self.x = False return ultimo_texto else: self.caixa_de_mensagem.send_keys(frase_erro) time.sleep(1) self.botao_enviar = self.driver.find_element_by_xpath("//span[@data-icon='send']") self.botao_enviar.click() self.x = False return ultimo_texto else: ultimo_texto = texto def noticias(self): req = requests.get('https://newsapi.org/v2/top-headlines?sources=globo&pageSize=5&apiKey=f6fdb7cb0f2a497d92dbe719a29b197f') noticias = json.loads(req.text) for news in noticias['articles']: titulo = news['title'] link = news['url'] new = f'{self.nome_bot}: ' + titulo + ' ' + link + '\n' self.caixa_de_mensagem.send_keys(new) time.sleep(1) def responde(self,texto): try: itens = self.filtra_produto(texto) self.envia_cardapio(itens) except: response = self.bot.get_response(texto) # if float(response.confidence) > 0.5: response = str(response) response = f'{self.nome_bot}: ' + response self.caixa_de_mensagem = self.driver.find_element_by_class_name('_13mgZ') self.caixa_de_mensagem.send_keys(response) time.sleep(1) self.botao_enviar = self.driver.find_element_by_xpath("//span[@data-icon='send']") self.botao_enviar.click() def treina(self,nome_pasta): for treino in os.listdir(nome_pasta): conversas = open(nome_pasta+'/'+treino, 'r').readlines() self.bot.train(conversas) def bebidas(self): itens = self.filtra_categoria('1') self.envia_cardapio(itens) def salgados(self): itens = self.filtra_categoria('2') self.envia_cardapio(itens) def cervejas(self): itens = self.filtra_categoria('3') self.envia_cardapio(itens) def tiragostos(self): itens = self.filtra_categoria('4') self.envia_cardapio(itens) def sincronizar(self): API_URL = config('API_URL') # Variáveis definidas no arquivo .env API_USER = config('API_USER') API_PASS = config('API_PASS') r = requests.get(f'{API_URL}produtos/', auth=HTTPBasicAuth(API_USER, API_PASS)) file = open('cardapio.json', 'w+') file.write(r.text) file.close() def filtra_categoria(self, cat): file = open('cardapio.json', 'r') if file.mode == 'r': cardapio = file.read() produtos = json.loads(cardapio) itens = [] for produto in produtos['results']: nome = produto['nome_produto'] preco = produto['preco'] categoria = produto['categoria'][-2] if categoria == cat: itens.append(f'{nome} - R$ {preco}') return itens def filtra_produto(self, texto): file = open('cardapio.json', 'r') if file.mode == 'r': cardapio = file.read() produtos = json.loads(cardapio) itens = [] for produto in produtos['results']: nome = produto['nome_produto'] preco = produto['preco'] if nome.lower().find(texto.lower()) > -1: itens.append(f'{nome} - R$ {preco}') return itens def envia_cardapio(self, itens): for item in itens: self.caixa_de_mensagem.send_keys(f'\n{self.nome_bot}: {item}') time.sleep(1) self.botao_enviar = self.driver.find_element_by_xpath("//span[@data-icon='send']") self.botao_enviar.click() def publica_mensagem(self, mensagem): self.caixa_de_mensagem.send_keys(f'{self.nome_bot}: {mensagem}') time.sleep(1) self.botao_enviar = self.driver.find_element_by_xpath("//span[@data-icon='send']") self.botao_enviar.click()
# -*- coding: utf-8 -*- from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from thai import thai import codecs,json with codecs.open("data.json", 'r',encoding='utf8') as f: data=json.load(f) cor=data["conversations"] chatbot = ChatBot( 'Fah', # ชื่อแชตบ็อต storage_adapter='chatterbot.storage.SQLStorageAdapter', # กำหนดการจัดเก็บ ในที่นี้เลือก chatterbot.storage.SQLStorageAdapter เก็บเป็น Sqllite database='fah2.sqlite3', # ที่ตั้งฐานข้อมูล statement_comparison_function=thai ) chatbot.set_trainer(ListTrainer) for data_list in cor: chatbot.train(data_list) print("train : OK")
convSaudacao = [ 'Oi', 'Olá', 'Qual é o seu nome?', 'Bom dia, como vai?', 'Estou bem, obrigada por pergutar' ] #criando list de conversação 2, abrangendo o foco convMusic = [ 'Você gosta de músicas?', 'Sim, e você?', 'Adoro!', 'Qual seu estilo de música favorito?', 'Rock!', 'Que Legal!' ] #metodo de treinamento bot.set_trainer(ListTrainer) #treino bot.train(convSaudacao) bot.train(convMusic) #laço de perguntas while True: quest = input('You: ') response = bot.get_response(quest) #função confidence, acima de 0.5 entra no if if float(response.confidence > 0.5): print('Bot: ', response) # igual ou menor que 0.5 entra no else else: print('Bot: Não compreendi')
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer app = Flask(__name__) realli_bot = ChatBot("Realli Bot", ) with open("./data/conversations.json", "rb") as json_data: conversations = json.load(json_data)['conversations'] with open("./data/property.json", "rb") as json_data: property_data = json.load(json_data)['property'] realli_bot.set_trainer(ListTrainer) realli_bot.train(conversations[0]) realli_bot.train(property_data[0]) @app.route('/', methods=['GET']) def verify(): if request.args.get("hub.mode") == "subscribe" and request.args.get( "hub.challenge"): if not request.args.get( "hub.verify_token") == os.environ["VERIFY_TOKEN"]: return "Verification token mismatch", 403 return request.args["hub.challenge"], 200 return "Hello world", 200
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.' }], trainer='chatterbot.trainers.ListTrainer') # 手动给定一点语料用于训练 bot.train([ 'How can I help you?', 'I want to create a chat bot', 'Have you read the documentation?', 'No, I have not', 'This should help get you started: http://chatterbot.rtfd.org/en/latest/quickstart.html' ]) # 给定问题并取回结果 question = 'How do I make an omelette?' print(question) response = bot.get_response(question) print(response) print("\n") question = 'how to make a chat bot?' print(question) response = bot.get_response(question) print(response)
class DialogueManager(object): def __init__(self, paths): print("Loading resources...") # Intent recognition: self.intent_recognizer = unpickle_file(paths['INTENT_RECOGNIZER']) self.tfidf_vectorizer = unpickle_file(paths['TFIDF_VECTORIZER']) self.ANSWER_TEMPLATE = 'I think its about %s\nThis thread might help you: https://stackoverflow.com/questions/%s' # Goal-oriented part: self.tag_classifier = unpickle_file(paths['TAG_CLASSIFIER']) self.thread_ranker = ThreadRanker(paths) def create_chitchat_bot(self): """Initializes self.chitchat_bot with some conversational model.""" # Hint: you might want to create and train chatterbot.ChatBot here. # It could be done by creating ChatBot with the *trainer* parameter equals # "chatterbot.trainers.ChatterBotCorpusTrainer" # and then calling *train* function with "chatterbot.corpus.english" param ######################## #### YOUR CODE HERE #### ######################## if not os.path.exists(chitchat_bot_path): self.chitchat_bot = ChatBot( "myBot", storage_adapter="chatterbot.storage.SQLStorageAdapter", database=chitchat_bot_path) self.chitchat_bot.set_trainer(ChatterBotCorpusTrainer) self.chitchat_bot.train("chatterbot.corpus.english") else: self.chitchat_bot = ChatBot( "myBot", storage_adapter="chatterbot.storage.SQLStorageAdapter", database=chitchat_bot_path) def generate_answer(self, question): """Combines stackoverflow and chitchat parts using intent recognition.""" # Recognize intent of the question using `intent_recognizer`. # Don't forget to prepare question and calculate features for the question. prepared_question = text_prepare(question) #### YOUR CODE HERE #### features = self.tfidf_vectorizer.transform( [prepared_question]) #### YOUR CODE HERE #### intent = self.intent_recognizer.predict(features)[ 0] #### YOUR CODE HERE #### # Chit-chat part: if intent == 'dialogue': # Pass question to chitchat_bot to generate a response. response = self.chitchat_bot.get_response( question) #### YOUR CODE HERE #### return response # Goal-oriented part: else: # Pass features to tag_classifier to get predictions. tag = self.tag_classifier.predict(features)[ 0] #### YOUR CODE HERE #### # Pass prepared_question to thread_ranker to get predictions. thread_id = self.thread_ranker.get_best_thread( question, tag) #### YOUR CODE HERE #### return self.ANSWER_TEMPLATE % (tag, thread_id)
from flask import Flask, render_template, request from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer app = Flask(__name__) english_bot = ChatBot("budgy", storage_adapter="chatterbot.storage.SQLStorageAdapter") english_bot.set_trainer(ChatterBotCorpusTrainer) english_bot.train('chatterbot.corpus.english.greetings') english_bot.train("./Final_2017.yml") english_bot.train("./Final_2016.yml") english_bot.train("./Final_GST.yml") english_bot.train("./trainerdata.yml") @app.route("/") def home(): return render_template("index.html") @app.route("/get") def get_bot_response(): userText = request.args.get('msg') return str(english_bot.get_response(userText)) if __name__ == "__main__": app.run(host="0.0.0.0")
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import os bot = ChatBot('RDX BOT') bot.set_trainer(ListTrainer) for files in os.listdir( 'G:/chandigarh university ppts/PP2\chatterbot-corpus-master\chatterbot_corpus\data\english/' ): data = open( 'G:/chandigarh university ppts/PP2\chatterbot-corpus-master\chatterbot_corpus\data\english/' + files, 'r').readlines() bot.train(data) while True: message = input('You:') if message.strip() != 'Bye': reply = bot.get_response(message) print('ChatBot :', reply) if message.strip() == 'Bye': print('ChatBot : Bye') break
from chatterbot.trainers import ListTrainer # method to train the chatbot from chatterbot import ChatBot # import the chatbot bot = ChatBot('Test') #create a chatbot conv = open('chateng.txt', 'r').readlines() bot.set_trainer(ListTrainer) #set the trainers bot.train(conv) # train the bot while True: request = input('You: ') response = bot.get_response(request) print('Bot: ', response)
return if bars[current_bar].UpdateBar(iteration_counter, max=total_items) is False: return # show the training dataset name texts[current_bar].update(description) if iteration_counter == total_items: current_bar += 1 # redefine the chatbot text based progress bar with a graphical one chatterbot.utils.print_progress_bar = print_progress_bar chatbot = ChatBot('Ron Obvious', trainer='chatterbot.trainers.ChatterBotCorpusTrainer') # Train based on the english corpus chatbot.train("chatterbot.corpus.english") ################# GUI ################# layout = [[sg.Output(size=(80, 20))], [sg.MLine(size=(70, 5), enter_submits=True), sg.Button('SEND', bind_return_key=True), sg.Button('EXIT')]] window = sg.Window('Chat Window', layout, default_element_size=(30, 2)) # ---===--- Loop taking in user input and using it to query HowDoI web oracle --- # while True: event, (value,) = window.read() if event != 'SEND': break
print("I have successfully imported " + str(lineCount) + " rows of info and will now retrain...") if os.path.exists("botData.sqlite3"): os.remove("botData.sqlite3") print("Clearing my old training data.") bot = ChatBot( "Chat Bot", storage_adapter="chatterbot.storage.SQLStorageAdapter", database="botData.sqlite3" ) #You can comment these out for production later since you won't be training everytime: bot.set_trainer(ChatterBotCorpusTrainer) bot.train("data/trainingdata.yml") print('##################################################') print("I am all trained up and ready to chat!") print("If on PythonAnywhere, run this command: cp botData.sqlite3 ../botData.sqlite3") print('##################################################') print('Shall I delete the recent conversation logs?') userConfirm = input('Press y or n: ') if(userConfirm != "y" and userConfirm != "Y"): print('Now exiting log training mode...') sys.exit() else: if os.path.exists("BotLog.csv"): os.remove("BotLog.csv")
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer conversation=[ 'Hellow', 'hi there', 'how r u doing', 'i m doinng great', 'that is good to here' 'what is your name', 'My name is Charlie', 'whats app', 'no thing special', 'what are you doing', 'i am here to help u', 'What is your father name', 'my father name is shah alam', 'thank you' ] chatbot=ChatBot('Bisp') chatbot.set_trainer(ListTrainer) chatbot.train(conversation) while True: userinput=input('You:') if userinput=='bye' or userinput.strip()=='bye': print('ChatBot:Bye') break; else: response=chatbot.get_response(userinput) print('ChatBot:',response)
from flask import Flask, render_template, request from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer from chatterbot.trainers import ListTrainer app = Flask(__name__) bot = ChatBot("Candice") bot.set_trainer(ListTrainer) bot.train(['What is your name?', 'My name is Candice']) bot.train(['Who are you?', 'I am a bot']) bot.train(['Do created you?', 'Tony Stark', 'Sahil Rajput', 'You?']) bot.set_trainer(ChatterBotCorpusTrainer) bot.train("chatterbot.corpus.english") @app.route("/") def home(): return render_template("home.html") @app.route("/get") def get_bot_response(): userText = request.args.get('msg') return str(bot.get_response(userText)) if __name__ == "__main__": app.run()
# -*- coding: utf-8 -*- from chatterbot import ChatBot ''' This is an example showing how to create an export file from an existing chat bot that can then be used to train other bots. ''' chatbot = ChatBot('Export Example Bot', trainer='chatterbot.trainers.ChatterBotCorpusTrainer') # First, lets train our bot with some data chatbot.train('chatterbot.corpus.english') # Now we can export the data to a file chatbot.trainer.export_for_training('./my_export.json')
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import pandas as pd bot = ChatBot('Inspiration Quotes') bot.set_trainer(ListTrainer) df = pd.read_csv('quotes_data.csv', encoding='latin1') new = df["hrefs"].str.split("src=t_", n=1, expand=True) df['quotes_type'] = new[1] author = df["lines"].str.split(".-", n=1, expand=True) df["quotes_lines"] = author[0] dataset = df.drop(['lines', 'hrefs'], axis=1) df_new = dataset.groupby('quotes_type').agg({ 'quotes_lines': ', '.join }).reset_index() final_df = df_new[['quotes_type', 'quotes_lines']] for index, row in final_df.iterrows(): ques = row['quotes_type'] ans = row['quotes_lines'] bot.train([ques, ans]) while True: message = input('You:') if message.strip() != 'Bye': reply = bot.get_response(message) print('Chatbot :', reply) if message.strip() == 'Bye': print('Chatbot : Bye') break
newentry.append(qa) else: qa = entry[j].replace('\n', ' ').replace(' ', '') newentry.append(qa) y.append(newentry) # train chatbot with Q&A training corpus for i in range(len(y)): question = y[i][0] answer = y[i][1] print(question) print(answer) chatbot.train([ question, answer, ]) # now ask the user 2 sample questions to get response. for i in range(2): speak_text('how can I help you?') # record a voice sample sync_record('sample.wav', 5, 16000, 1) # transcribe this voice sample and remove the audio question = transcribe_sphinx('sample.wav') os.remove('sample.wav') # speak_text('okay, processing...') response = chatbot.get_response(question) # speak the response instead of playing it on screen print(str(response)) speak_text(str(response))
from flask_restful import Resource, Api from flask import Flask, request from chatterbot.trainers import ListTrainer from chatterbot import ChatBot app = Flask(__name__) api = Api(app) bot = ChatBot('TW Chat Bot') conversa = [ 'Oi', 'Olá', 'Tudo bem?', 'Tudo ótimo', 'Você gosta de programar?', 'Sim, eu programo em Python' ] bot.set_trainer(ListTrainer) bot.train(conversa) def Model(pergunta): resposta = bot.get_response(pergunta) if float(resposta.confidence) > 0.5: return {"GeorgeBot": str(resposta)} else: return {"GeorgeBot": 'Ainda não sei responder esta pergunta'} class API_NLP_BOT(Resource): def get(self, pergunta_id): pergunta = request.form['pergunta'] bot_resposta = Model(pergunta)
##Chatbot ##Made in Python 3.6.3 import pyttsx #importing text to speech import speech_recognition as sr from chatterbot.trainers import ListTrainer #training the chatbot from chatterbot import ChatBot #importing the actual chatbot bot = ChatBot('Test') #make the Chatbot bot.set_trainer(ListTrainer) #sets the trainer up for _file in os.listdir('Datasets'): chats = open('Datasets/' + _file, 'r').readlines() bot.train(talk) #trains the bot on our text list #find the usb microphone name and enter it mic_name = "USB Device 0x46d:0x825: Audio (hw:1, 0)" #Sample rate sample_rate = 48000 #Chunk is the buffer size chunk_size = 2048 #Initializing the recognition r = sr.Recognizer() #list of microphone names mic_list = sr.Microphone.list_microphone_names() #loop to set device ID for i, microphone_name in enumerate(mic_list):
class DialogueManager(object): def __init__(self, paths): print("Loading resources...") # Intent recognition: self.intent_recognizer = unpickle_file(paths['INTENT_RECOGNIZER']) self.tfidf_vectorizer = unpickle_file(paths['TFIDF_VECTORIZER']) self.ANSWER_TEMPLATE = 'I think its about %s\nThis thread might help you: https://stackoverflow.com/questions/%s' # Goal-oriented part: self.tag_classifier = unpickle_file(paths['TAG_CLASSIFIER']) self.thread_ranker = ThreadRanker(paths) self.__init_chitchat_bot() def __init_chitchat_bot(self): """Initializes self.chitchat_bot with some conversational model.""" # Hint: you might want to create and train chatterbot.ChatBot here. # Create an instance of the ChatBot class. # Set a trainer set_trainer(ChatterBotCorpusTrainer) for the ChatBot. # Train the ChatBot with "chatterbot.corpus.english" param. # Note that we use chatterbot==0.7.6 in this project. # You are welcome to experiment with other versions but they might have slightly different API. ######################## #### YOUR CODE HERE #### ######################## self.chitchat_bot = ChatBot( 'Nim Obvious', trainer='chatterbot.trainers.ChatterBotCorpusTrainer') # Train based on the english corpus self.chitchat_bot.train("chatterbot.corpus.english") def generate_answer(self, question): """Combines stackoverflow and chitchat parts using intent recognition.""" # Recognize intent of the question using `intent_recognizer`. # Don't forget to prepare question and calculate features for the question. prepared_question = text_prepare(question) #### YOUR CODE HERE #### features = self.tfidf_vectorizer.transform( [prepared_question]) #### YOUR CODE HERE #### intent = self.intent_recognizer.predict( features) #### YOUR CODE HERE #### # Chit-chat part: if intent == 'dialogue': # Pass question to chitchat_bot to generate a response. response = self.chitchat_bot.get_response( question) #### YOUR CODE HERE #### return response # Goal-oriented part: else: # Pass features to tag_classifier to get predictions. tag = self.tag_classifier.predict(features)[ 0] #### YOUR CODE HERE #### # Pass prepared_question to thread_ranker to get predictions. thread_id = self.thread_ranker.get_best_thread( question, tag)[0] #### YOUR CODE HERE #### return self.ANSWER_TEMPLATE % (tag, thread_id)
#初始化机器人 #chatbot = ChatBot('Dr.Qian') chatbot = ChatBot( 'Dr.Qian', #指定logic模块 logic_adapters = [ "chatterbot.logic.BestMatch", "chatterbot.logic.MathematicalEvaluation", "chatterbot.logic.TimeLogicAdapter" ], database = 'chatterbot' ) #用中文语料库训练机器人 chatbot.set_trainer(ChatterBotCorpusTrainer) chatbot.train('chatterbot.corpus.chinese') #特定语句训练 #chatbot.set_trainer(ListTrainer) #chatbot.train(['你叫什么', # '你好,我是钱博士,你也可以叫我天才钱']) #接入微信机器人 bot = Bot(cache_path = True) @bot.register(Group, TEXT) def reply(msg): print(msg) if msg.is_at: return chatbot.get_response(msg.text).text
env = os.environ.get("WemadeitEnv") pswd = "" usnm = "" if env == "production": pswd = os.environ.get("password") usnm = os.environ.get("username") else: with open("cred.json") as f: creds = json.load(f) usnm = creds['user'] pswd = creds['pass'] client.login(usnm, pswd) # Chatterbot Client chatbot = ChatBot("BlackWhitby", logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter") chatbot.train("chatterbot.corpus.english") chatbot.train("chatterbot.corpus.english.greetings") chatbot.train("chatterbot.corpus.english.conversations") # Todo add corpus for swearing swearing = {} with open("corpus/swearing.json") as f: swearing = json.load(f) if "f**k" in swearing.keys(): for line in swearing["f**k"]: chatbot.train(line) # Drive API SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'WeMadeItBot'
# Uncomment the following line to enable verbose logging # import logging # logging.basicConfig(level=logging.INFO) # Create a new instance of a ChatBot bot = ChatBot( "Terminal", storage_adapter="chatterbot.storage.SQLStorageAdapter", input_adapter="chatterbot.input.TerminalAdapter", output_adapter="chatterbot.output.TerminalAdapter" ) bot.set_trainer(ChatterBotCorpusTrainer) bot.train("chatterbot.corpus.english") CONVERSATION_ID = bot.storage.create_conversation() def get_feedback(): from chatterbot.utils import input_function text = input_function() if 'yes' in text.lower(): return False elif 'no' in text.lower(): return True else:
# coding: utf-8 from wxpy import * import urllib3 import requests import json from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer chatbot = ChatBot("deepThought", storage_adapter="chatterbot.storage.MongoDatabaseAdapter", database='chatbot') chatbot.set_trainer(ChatterBotCorpusTrainer) chatbot.train("/home/tankh/chatbot/novel.yml") tuling = Tuling(api_key='b85476cd869f416ba5af3e5f30e53fb2') def http_response(msg): requests.packages.urllib3.disable_warnings() http = urllib3.PoolManager() data = {"text": msg} encode_data = json.dumps(data).encode() url = "http://124.202.155.72:60001/nlp/chatbotReply" r = http.request('POST', url, body=encode_data, headers={'Content-Type': 'application/json'}) return json.loads(r.data.decode('utf-8'))['data']
class DataCachingTests(TestCase): def setUp(self): self.test_data_directory = 'test_data' self.test_database_name = self.random_string() + ".db" if not os.path.exists(self.test_data_directory): os.makedirs(self.test_data_directory) database_path = os.path.join( self.test_data_directory, self.test_database_name ) self.chatbot = ChatBot( "Test Bot", io_adapter="chatterbot.adapters.io.NoOutputAdapter", logic_adapter="tests.logic_adapter_tests.test_data_cache.DummyMutatorLogicAdapter", database=database_path ) self.chatbot.train([ "Hello", "How are you?" ]) def random_string(self, start=0, end=9000): """ Generate a string based on a random number. """ from random import randint return str(randint(start, end)) def remove_data(self): import shutil if os.path.exists(self.test_data_directory): shutil.rmtree(self.test_data_directory) def tearDown(self): """ Remove the test database. """ self.chatbot.storage.drop() self.remove_data() def test_additional_attributes_saved(self): """ Test that an additional data attribute can be added to the statement and that this attribute is saved. """ response = self.chatbot.get_response("Hello") found_statement = self.chatbot.storage.find("Hello") self.assertIsNotNone(found_statement) self.assertIn("pos_tags", found_statement.serialize()) self.assertEqual( "NN", found_statement.serialize()["pos_tags"] )