Exemplo n.º 1
0
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()
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
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 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))
Exemplo n.º 5
0
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
Exemplo n.º 6
0
# -*- 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))
Exemplo n.º 7
0
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")
Exemplo n.º 8
0
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()