def chat(): if 'message' in request.args: message = request.args['message'] return Chatbot.message(message) else: return "Error: No message."
def news_query(): answer = request.args.get('news') info = Chatbot.recenews(answer) if voice == True: tts = gTTS(text=info) tts.save("news_answer.mp3") playsound("news_answer.mp3") os.remove("news_answer.mp3") return render_template("news.html", message=info)
def wechat_auth(): if request.method == "GET": message = Get(request) message.verify() return message.return_code elif request.method == "POST": message = Reply(request) uid = message.FromUserName session_id = Chatbot.get_session_id(uid) get_message = message.Content session_key, reply_message = Chatbot.chatbot_reply( access_token, session_id, get_message) Chatbot.update_session_id(uid, session_key) message.text(reply_message) return message.reply()
def ChatbotAutograder(ScriptFilename, FAQFilename, LogFilename): print(__doc__.split('.')[0]) try: with open(ScriptFilename, "r", encoding="utf-8") as f: scriptFileasList = f.readlines() except FileNotFoundError: print("Could not find script.") return 1 try: chatbot = Chatbot.Chatbot(FAQFilename) except FileNotFoundError: print("Could not find FAQ.") return 1 if LogFilename: print("Loggin to file: " + LogFilename) logFile = open(LogFilename, "a") score = 0.0 for qa in scriptFileasList: question = qa.split('?')[0] answer = qa.split('?')[1] # We open and close the file to avoid loosing data if we crash if LogFilename: logFile = open(LogFilename, "a") Type, response = chatbot.InputOutput(question) action = "0.0" if Type == True: if response.split('\n')[0] == answer.split('\n')[0]: score += 1.0 action = "1.0" chatbot.UserFeedback("yes") else: score -= 0.1 action = "-0.1" chatbot.UserFeedback("no") if LogFilename: logFile.write("\nInput: " + question) logFile.write("\nResponse: " + response) logFile.write("\nCorrect: " + answer) logFile.write("\nType: " + str(Type)) logFile.write("\nAction: " + action) logFile.write("\n") logFile.close() print() print("Response: " + response) if not Type: print() print() print("Score:", score)
def sent(): messages = message.get() reply = Chatbot.chat(messages) if messages != "": chatpanel.config(state=NORMAL) chatpanel.insert(END, "You: " + messages + '\n') chatpanel.insert(END, "RelaxnChatBot: " + reply + '\n') enterchat.delete(0, 'end') chatpanel.config(state=DISABLED) chatpanel.yview(END) else: return
def ChatbotTester(FAQFilename, LogFilename): print(__doc__.split('.')[0]) #try: cwd = os.getcwd() # Get the current working directory (cwd) files = os.listdir(cwd) # Get all the files in that directory print("Files in '%s': %s" % (cwd, files)) chatbot = Chatbot.Chatbot(FAQFilename) # except FileNotFoundError: # print("Could not find FAQ.") # return 1 if LogFilename: print("Loggin to file: " + LogFilename) logFile = open(LogFilename, "a") # loop while (1): try: userInput = input('Input: ') except KeyboardInterrupt: # User hit ctrl-c if LogFilename: logFile.close() return 1 # We open and close the file to avoid loosing data if we crash if LogFilename: logFile = open(LogFilename, "a") Type, response = chatbot.InputOutput(userInput) if LogFilename: logFile.write("\nInput: " + userInput) logFile.write("\nResponse: " + response) logFile.write("\nType: " + str(Type)) logFile.write("\n") logFile.close() print() print("Response: " + response) if Type == True: try: chatbot.UserFeedback(input()) except KeyboardInterrupt: # User hit ctrl-c if LogFilename: logFile.close() return 1 else: print() print()
def ChatbotAutograder(script_filename, faq_filename, log_filename): print(__doc__.split('.')[0]) try: with open(script_filename, encoding='utf-8') as json_data: autograder_test_script_as_list_of_dicts = json.load(json_data) except: print("Failure opening AutograderScript json file") return 1 try: chatbot = Chatbot.Chatbot(faq_filename) except FileNotFoundError: print("Could not find FAQ.") return 1 if log_filename: print("Loggin to file: "+log_filename) log_file = open(log_filename, "w") score = 0.0 for qa_dict in autograder_test_script_as_list_of_dicts: response = chatbot.input_output(qa_dict["questions"][0]).split('\n')[0] action = "0.0" if "replace" in qa_dict: replace = qa_dict["replace"] else: replace = "" if response == qa_dict["response"]: score += 1.0 action = "1.0" chatbot.user_feedback(True, replace) else: score -= 0.5 action = "-0.5" chatbot.user_feedback(False, replace) if log_filename: log_file.write("\nTest Question: "+qa_dict["questions"][0]) log_file.write("\nAgent Response: "+response) log_file.write("\nTest Answer: "+qa_dict["response"]) log_file.write("\nTest Replace: "+replace) log_file.write("\nAction: "+action) log_file.write("\n") log_file.close() print("Score:", score)
def ChatbotTester(FAQFilename,LogFilename): print(__doc__.split('.')[0]) try: chatbot = Chatbot.Chatbot(FAQFilename) except FileNotFoundError: print("Could not find FAQ.") return 1 if LogFilename: print("Loggin to file: "+LogFilename) logFile = open(LogFilename,"a") # loop while(1): try: userInput = input('Input: ') except KeyboardInterrupt: # User hit ctrl-c if LogFilename: logFile.close() return 1 # We open and close the file to avoid loosing data if we crash if LogFilename: logFile = open(LogFilename,"a") Type,response = chatbot.InputOutput(userInput) if LogFilename: logFile.write("\nInput: "+userInput) logFile.write("\nResponse: "+response) logFile.write("\nType: "+str(Type)) logFile.write("\n") logFile.close() print() print("Response: "+response) if Type == True: try: chatbot.UserFeedback(input()) except KeyboardInterrupt: # User hit ctrl-c if LogFilename: logFile.close() return 1 else: print() print()
def ChatbotAutograder(ScriptFilename, FAQFilename, LogFilename): print(__doc__.split('.')[0]) try: with open(ScriptFilename, "r", encoding="utf-8") as f: scriptFileasList = f.readlines() except FileNotFoundError: print("Could not find script.") return 1 try: chatbot = Chatbot.Chatbot(FAQFilename) except FileNotFoundError: print("Could not find FAQ.") return 1 if LogFilename: print("Loggin to file: " + LogFilename) logFile = open(LogFilename, "a") score = 0.0 total_questions = 0 total_correct = 0 total_skipped = 0 total_meant_to_skip = 0 total_correctly_skipped = 0 total_wrong = 0 wrong_answers = [] for qa in scriptFileasList: question = qa.split('?')[0] answer = qa.split('?')[1] #.strip() # We open and close the file to avoid loosing data if we crash if LogFilename: logFile = open(LogFilename, "a") Type, response = chatbot.InputOutput(question) action = "0.0" total_questions += 1 if Type == True: if answer.split('\n')[0] == "I do not know.": total_meant_to_skip += 1 score -= 0.1 action = "-0.1" total_wrong += 1 wrong_answers.append({ '1_question': question, '2_expected_answer': answer.split('\n')[0], '3_actual_answer': response.split('\n')[0] }) chatbot.UserFeedback("no") elif response.split('\n')[0] == answer.split('\n')[0]: score += 1.0 action = "1.0" total_correct += 1 chatbot.UserFeedback("yes") else: score -= 0.1 action = "-0.1" total_wrong += 1 wrong_answers.append({ '1_question': question, '2_expected_answer': answer.split('\n')[0], '3_actual_answer': response.split('\n')[0] }) chatbot.UserFeedback("no") else: if not question.startswith("Who are you"): if answer.split('\n')[0] == "I do not know.": total_meant_to_skip += 1 if response.split('\n')[0] == answer.split('\n')[0]: total_correctly_skipped += 1 else: wrong_answers.append({ '1_question': question, '2_expected_answer': answer.split('\n')[0], '3_actual_answer': response.split('\n')[0] }) total_skipped += 1 if LogFilename: logFile.write("\nInput: " + question) logFile.write("\nResponse: " + response) logFile.write("\nCorrect: " + answer) logFile.write("\nType: " + str(Type)) logFile.write("\nAction: " + action) logFile.write("\n") logFile.close() print() print("Response: " + response) if not Type: print() print() if LogFilename: logFile = open(LogFilename, "a") logFile.write("\nScore: " + str(score)) logFile.write("\nTotal Questions: " + str(total_questions)) logFile.write("\nTotal Correct: " + str(total_correct)) logFile.write("\nTotal Skipped: " + str(total_skipped)) logFile.write("\nTotal Meant to Skip: " + str(total_meant_to_skip)) logFile.write("\nTotal Correctly Skipped: " + str(total_correctly_skipped)) logFile.write("\nTotal Wrong: " + str(total_wrong)) if total_wrong > 0: logFile.write("\nWrong Answer Breakdown:\n") pprint.pprint(wrong_answers, logFile) logFile.write("\n") logFile.close() print("Score:", str(score)) print("Total Questions: " + str(total_questions)) print("Total Correct: " + str(total_correct)) print("Total Skipped: " + str(total_skipped)) print("Total Meant to Skip: " + str(total_meant_to_skip)) print("Total Correctly Skipped: " + str(total_correctly_skipped)) print("Total Wrong: " + str(total_wrong)) if total_wrong > 0: print("(Wrong Answer Breakdown in logfile)") print("\n")
def chatbot_test(self): response = Chatbot.get_response('!! help') self.assertEquals( response, 'EXCITED YOU ASKED!!!! Type in any of these words: !! about, !! say something, !! excited, !! bored, !! encourage, !! bye' )
def chatbot_test_encourage(self): response = Chatbot.get_response('!! encourage') self.assertEquals( response, "You are special" or "The best is yet to come" or "Relax and do not stress" or "Cheer up")
def chatbot_test_bye(self): response = Chatbot.get_response('!! bye') self.assertEquals(response, ':( Thanks for visiting, I love you!')
def chatbot_test_excited(self): response = Chatbot.get_response('!! excited') self.assertEquals( response, ":) I am happy you are excited. We should all be happy!")
def chatbot_test_say_something(self): response = Chatbot.get_response('!! say something') self.assertEquals(response, "Make youself happy!")
def ChatbotAutograder(script_filename, faq_filename, log_filename): print(__doc__.split('.')[0]) try: with open(script_filename, encoding='utf-8') as json_data: autograder_test_script_as_list_of_dicts = json.load(json_data) except: print("Failure opening AutograderScript json file") return 1 try: chatbot = Chatbot.Chatbot(faq_filename) except FileNotFoundError: print("Could not find FAQ.") return 1 if log_filename: print("Logging to file: "+log_filename) log_file = open(log_filename, "w") score = 0.0 total_questions = 0 total_correct = 0 total_wrong = 0 wrong_answers = [] for qa_dict in autograder_test_script_as_list_of_dicts: response = chatbot.input_output(qa_dict["questions"][0]).split('\n')[0] action = "0.0" total_questions += 1 if "replace" in qa_dict: replace = qa_dict["replace"] else: replace = "" if response == qa_dict["response"]: score += 1.0 action = "1.0" total_correct += 1 chatbot.user_feedback(True, replace) else: score -= 0.5 action = "-0.5" total_wrong += 1 chatbot.user_feedback(False, replace) wrong_answers.append({'1_question': qa_dict["questions"][0], '2_expected_answer': qa_dict["response"], '3_actual_answer': response.split('\n')[0]}) if log_filename: log_file.write("\nTest Question: "+qa_dict["questions"][0]) log_file.write("\nAgent Response: "+response) log_file.write("\nTest Answer: "+qa_dict["response"]) log_file.write("\nTest Replace: "+replace) log_file.write("\nAction: "+action) log_file.write("\n") if log_filename: # log_file = open(log_filename,"a") log_file.write("\nScore: " + str(score)) log_file.write("\nTotal Questions: " + str(total_questions)) log_file.write("\nTotal Correct: " + str(total_correct)) log_file.write("\nTotal Wrong: " + str(total_wrong)) if total_wrong > 0: log_file.write("\nWrong Answer Breakdown:\n") pprint.pprint(wrong_answers, log_file) log_file.write("\n") log_file.close() print("Score:", str(score)) print("Total Questions: " + str(total_questions)) print("Total Correct: " + str(total_correct)) print("Total Wrong: " + str(total_wrong))
def chatbot_test_bored(self): response = Chatbot.get_response('!! bored') self.assertEquals(response, 'me too! But I am happy!!!!!')
return (recievedMessage, addr[0]) try: srvrPort = int(input("Enter the port number to host the server on:\n")) except ValueError: print("Error. Bad port number. Invalid port number. Port number must be an integer.") exit() print("Your Local IP Address is:") ipSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ipSock.connect(("8.8.8.8",80)) #TODO This is the only way to get the IP accurately regardless of network setups, is to connect to something, but this will fail if there is no internet. Maybe add a try except? print(ipSock.getsockname()[0]) ipSock.close() print("Starting server...") Chatbot.processInput('') # Chatbot knows not to store blank strings (safeToStore stops them), and this will prompt to create the pickle files if needed num = random.randint(0, 1000000) print("Server started. Waiting for connections. Press Ctrl + C to exit.") while True: r = receive(srvrPort) msg = r[0] ip = r[1] if msg[msg.find("\n\n\n:::\n\n\n")+9:] == "server: print code": # If the user says 'server: print code' print(num) # Print the number on the server screen send(ip, srvrPort, "Code is now on server console.") elif msg[msg.find("\n\n\n:::\n\n\n")+9:] == "server: exit " + str(num): # If the user says 'server: exit' and the correct code, exit send(ip, srvrPort, "Correct code. Server exiting.") exit()
# Chatbot-test.py # This short program tests out some of the Chatbot, making sure it won't crash. Needs Chatbot v0.2.0 or later. import Chatbot # PyCharm seems to think this is an error, but it seems fine. import random import os import sys __author__ = 'Peter Maar' __version__ = '1.0.0' Chatbot.debugTestMode = True humanSayList = ["Hello!", "How are you?", "What is your name?", "What time is it?", "How's the weather?", "DFTBA", "Good Morning!", "Bye!", "I gtg", "Just FYI idk who u are."] outstuff = '' for i in range(100): humanSays = humanSayList[random.randint(0, len(humanSayList)-1)] print("Human says:", humanSays) stuff = outstuff + "\n\n\n:::\n\n\n" + humanSays outstuff = Chatbot.processInput(stuff) print("Bot says:", outstuff) humanSayList.append(outstuff) print("\n\n\n\n\n\n\n\n\n\n") print(Chatbot.thingsToSayOld) print("\n\n\n\n\n") print(Chatbot.smartSayDict) os.remove(sys.path[0] + "/DEBUG-smartSayDict.pickle") os.remove(sys.path[0] + "/DEBUG-thingsToSayOld.pickle")
def summary(): return Chatbot.summary()
def get_bot_response(): userText = request.args.get('msg') return str(Chatbot.gelen(userText))
# -*- coding: utf-8 -*- """ Inicio de chatbot Primeiramente deve ler o nome e reconhecer o nome da pessoa """ """ Imports """ from Chatbot import * # Separação das funcões principais do chatbot from chat_funcoes import * """ Globais """ chatbot = Chatbot("Teste") """ ########## """ def main(): while True: frase = normalizar_frase(chatbot.escutar()) resposta = chatbot.pensar(frase) if (frase == "sair"): break else: chatbot.fala(resposta) pass pass print("Até mais %s" % (chatbot.nome_pessoa))
import Chatbot if __name__ == '__main__': tokenTelegram = '1255840202:AAESK__tlVGY63FVPJOJufa70DLej8UfXrI' ibm_apiKey = 'VZHzvjelK9YsjuYtBGOkXhFLhoDGruweoDcYIfKhE7hT' ibm_url = 'https://api.us-east.assistant.watson.cloud.ibm.com/instances/1b62e879-1f7e-4e0b-9d72-5ab9c1d9328b' ibm_assitantId = 'a8817251-2b48-47d0-a208-09f7fde9b369' chatbot = Chatbot.Chatbot(tokenTelegram, ibm_apiKey, ibm_url, ibm_assitantId)
def chatbot_test_invalid_response(self): response = Chatbot.get_response('!! heyyy') self.assertEquals( response, "Invalid response. Valid responses are !! help, !! about, !! say something, !! bored, !! excited, !! encourage, !! bye" )
def ChatbotAutograder(script_filename, verbose): print(__doc__.split('.')[0]) print("Opening script: " + script_filename) try: with open(script_filename, encoding='utf-8') as json_data: autograder_test_script = json.load(json_data) except Exception as e: print("Failure opening or reading script: " + str(e)) return 1 if 'version' in autograder_test_script: print("Script version: " + autograder_test_script['version']) else: print("Version not identified") return 1 if 'script' not in autograder_test_script: print("Test script not identified") return 1 if 'faq' not in autograder_test_script: print("FAQ filename not identified") return 1 try: logit = Logger(autograder_test_script) except: print("Failed to open log file") return 1 print("Redirecting to file: " + autograder_test_script['log'] + ".out") try: redirect = open(autograder_test_script['log'] + ".out", "w") except: print("Failed to open redirection file") return 1 feedback = False if autograder_test_script['feedback'] == 'on': feedback = True regrade_list_of_dicts = [] print("Opening FAQ: " + autograder_test_script['faq']) print("Instantiating Chatbot") try: chatbot = Chatbot.Chatbot(autograder_test_script['faq']) except FileNotFoundError: print("Could not find FAQ.") return 1 try: grader = Grader() print("Running script") for qa_dict in autograder_test_script['script']: question = qa_dict['questions'][0] with redirect_stdout(redirect): agent_response = chatbot.input_output(question).split('\n')[0] try: feedback_to_agent = grader.grade(agent_response, qa_dict['type'], qa_dict['response']) except ValueError as e: print("Grader Error: {0}".format(e)) logit.logmsg("Grader Error: {0}".format(e)) raise if not verbose: if feedback_to_agent: print('+', end='') else: print('-', end='') if len(qa_dict['questions'] ) > 1 and feedback and not feedback_to_agent: qa_dict_copy = qa_dict.copy() qa_dict_copy['type'] = '2nd' regrade_list_of_dicts.append(qa_dict_copy) if verbose: print("Added to re-ask") if 'replace' in qa_dict: replace = qa_dict['replace'] else: replace = "" if feedback: with redirect_stdout(redirect): chatbot.user_feedback(feedback_to_agent, replace) logmsg = logit.logformat(replace, qa_dict['type'], question, agent_response, qa_dict['response'], grader.result_string(feedback)) logit.logmsg(logmsg) if verbose: print(logmsg) if not verbose: print('|', end='') # Ask questions in regrade_list_of_dicts again for qa_dict in regrade_list_of_dicts: question = qa_dict['questions'][1] with redirect_stdout(redirect): agent_response = chatbot.input_output(question).split('\n')[0] try: feedback_to_agent = grader.grade(agent_response, qa_dict['type'], qa_dict['response']) except ValueError as e: print("Grader Error: {0}".format(e)) raise if not verbose: if feedback_to_agent: print('+', end='') else: print('-', end='') logmsg = logit.logformat("", qa_dict['type'], question, agent_response, qa_dict['response'], grader.result_string(feedback)) logit.logmsg(logmsg) if verbose: print(logmsg) logit.logmsg("\n\n\nScript version: " + autograder_test_script['version']) logit.logmsg("\nFAQ: " + autograder_test_script['faq']) if feedback: logit.logmsg("\nFeedback: ON") logit.logmsg("\n" + grader.header_string(feedback)) logit.logmsg("\nResult: " + grader.result_string(feedback)) print("\n\nResults") print(grader.header_string(feedback)) print(grader.result_string(feedback)) except Exception as e: logit.logmsg("Error during grading: " + str(e)) print("Error during grading: " + str(e)) print(traceback.print_exc(file=sys.stdout)) finally: logit.logclose() return 1
def chatbot_test_about(self): response = Chatbot.get_response('!! about') self.assertEquals( response, 'Welcome to my Happiness chatbot. Feel free to chat with your friends, post images, and post links that you would like to share.' )
secondSymptom.addCat("Throat") secondSymptom.addSeverity(4) # Creating first patient patient1 = patient("Bob", 29, "Male") # Adding symptom objects to Patient patient1.addSymptom(first) patient1.addSymptom(secondSymptom) # Get patient info(Auto prints) patient1.patientInfo() # Creating Second Patient patient2 = patient("Joe", 29, "Male") # Adding symptom object to patient patient2.addSymptom(first) # Creating third Symptom third = Symptom("Fatigue") third.addCat("neurological") third.addSeverity(10) # Adding symptom to patient patient2.addSymptom(third) # Get patient info(Auto prints) patient2.patientInfo() print() # Start Chatbot chatbot1 = Chatbot() chatbot1.startChat()