示例#1
0
 def __init__(self, username):
     self.db = Database()
     self.flag = 'yes'
     data = self.db.getStudentInfo(username)
     for entry in data:
         self.username = entry[0]
         self.password = entry[1]
         self.firstName = entry[2]
         self.middle = entry[3]
         self.lastName = entry[4]
         self.unsettled = entry[5]
示例#2
0
    def __init__(self, username='', user='', parent=None):
        super(LoginWindow, self).__init__(parent)
        self.setupUi(self)
        self.setFixedSize(341, 481)

        # icons and images
        self.setWindowIcon(QtGui.QIcon('./UI/CardinalAIDS-icofile.ico'))
        self.logo.setPixmap(QtGui.QPixmap('./UI/CardinalAIDS-full.jpg'))
        self.logoAdmin.setPixmap(QtGui.QPixmap('./UI/CardinalAIDS-full.jpg'))
        self.logo_3.setPixmap(QtGui.QPixmap('./UI/CardinalAIDS-full.jpg'))

        # connects the login buttons to respective functions
        self.loginBtn.clicked.connect(self.authenticateStd)
        self.loginAdBtn.clicked.connect(self.authenticateAdm)

        # masks the password text fields
        self.passText.setEchoMode(QtWidgets.QLineEdit.Password)
        self.passAdText.setEchoMode(QtWidgets.QLineEdit.Password)

        # enables the use of the 'ENTER' key to activate function
        self.userText.returnPressed.connect(self.authenticateStd)
        self.passText.returnPressed.connect(self.authenticateStd)
        self.userAdText.returnPressed.connect(self.authenticateAdm)
        self.passAdText.returnPressed.connect(self.authenticateAdm)

        # enables use of the 'TAB' key to move between widgets/elements in the window
        tabFocus = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Tab),
                                       self)
        tabFocus.activated.connect(self.changeFocus)

        # messages initially not visible
        self.incorrrectLbl.setVisible(False)
        self.incorrrecAdmLbl.setVisible(False)

        #initialize database
        self.db = Database()
        if user == 'students':  # applicable after logging out and seeing login screen
            self.userText.setText(
                username)  # puts the previous username on text field and
            self.passText.setFocus()  # sets the current tab to recent user
            self.tabWidget.setCurrentIndex(0)
        if user == 'admins':
            self.userAdText.setText(username)
            self.passAdText.setFocus()
            self.tabWidget.setCurrentIndex(1)
示例#3
0
class AIchat():
    def __init__(self, username):
        self.db = Database()
        self.flag = 'yes'
        data = self.db.getStudentInfo(username)
        for entry in data:
            self.username = entry[0]
            self.password = entry[1]
            self.firstName = entry[2]
            self.middle = entry[3]
            self.lastName = entry[4]
            self.unsettled = entry[5]

    def convert(self, lst):
        bad_chars = [';', ':', '!', "*", '?', '.', ',']
        test_string = lst
        test_string = filter(lambda i: i not in bad_chars, test_string)
        return ''.join(test_string).split()

    def unsettledFees(self, ln, fn, mi, uc):
        ans = "Unsettled charges for " + ln + ", " + fn + " " + mi + ". amounts to: " + str(
            uc)
        return ans

    def scholarship(self, lst1):
        def fallback():
            fallbackOptions = [
                "Can you be more specific for me?",
                "I don't quite get what you're asking about scholarships.",
                "Can you be more specific on scholarships?"
            ]
            rngFallback = random.choice(fallbackOptions)
            return rngFallback

        for x in range(0, len(lst1) + 1):
            if x == len(lst1):
                return fallback()
            elif lst1[x] == "keb" or lst1[x] == "hana" or lst1[x] == "kebhana":
                self.code = "keb"
                break
            elif lst1[x] == "refinitiv":
                self.code = "refinitiv"
                break
            elif lst1[x] == "maasd" or lst1[x] == "san" or lst1[
                    x] == "diego" or lst1[x] == "sandiego" or lst1[
                        x] == "alumni":
                self.code = "maasd"
                break
            elif lst1[x] == "ety" or lst1[x] == "et" or lst1[x] == "yuchengco":
                self.code = "ety"
                break
            elif lst1[x] == "list" or lst1[x] == "available" or lst1[
                    x] == "all":
                data = self.db.getScholarshipList()
                return self.printScho(data)
            else:
                x = x + 1

        data = self.db.getScholarship(self.code)
        for entry in data:
            code = entry[0]
            name = entry[1]
            deadline = entry[2]
            status = entry[3]
            requirements = entry[4]

        if deadline == "no data":
            response = "The " + name + " is " + status
        else:
            response = "The " + name + " is deadlined until " + deadline
        return response

    def printScho(self, data):
        all = 'List of all scholarships: '
        count = len(data)
        count = count - 1
        while count >= 0:
            all = all + '\n' + str(data[count]).translate(
                str.maketrans({
                    ',': '',
                    '(': '- ',
                    '[': '',
                    ')': '',
                    ']': '',
                    "'": ''
                }))
            count = count - 1
        return all

    def schedEnroll(self, lst1):
        def fallback():
            fallbackOptions = [
                "You have either entered an invalid batch number or didn't specify one. Could you specify a valid batch number? ",
                "I don't think you've entered a valid batch number. Can you re-enter that?",
                "Please enter a valid batch number."
            ]
            rngFallback = random.choice(fallbackOptions)
            return rngFallback

        for x in range(0, len(lst1) + 1):
            if x == len(lst1):
                return fallback()
            if (lst1[x].isdigit()):
                if int(lst1[x]) <= 2014 and int(lst1[x]) >= 2008:
                    number = 1
                    break
            if lst1[x] == "2015" or lst1[x] == "2016" or lst1[
                    x] == "2017" or lst1[x] == "17" or lst1[x] == "16" or lst1[
                        x] == "15":
                number = 2
                break
            if lst1[x] == "2018" or lst1[x] == "18":
                number = 3
                break
            if lst1[x] == "2019" or lst1[x] == "19":
                number = 4
                break
            else:
                x = x + 1

        data = self.db.getEnrollment(number)
        for entry in data:
            number = entry[0]
            batch = entry[1]
            date = entry[2]
            time = entry[3]

        response = "The schedule of enrollment for Batch " + str(
            batch) + " is on " + date + " from " + time + " for all programs."
        return response

    def schedConsult(self, lst1):
        def fallback():
            fallbackOptions = [
                "You have either entered an invalid batch number or didn't specify one. Could you specify a valid batch number? ",
                "I don't think you've entered a valid batch number. Can you re-enter that?",
                "Please enter a valid batch number."
            ]
            rngFallback = random.choice(fallbackOptions)
            return rngFallback

        for x in range(0, len(lst1) + 1):
            if x == len(lst1):
                return fallback()

            if (lst1[x].isdigit()):
                if int(lst1[x]) <= 2014 and int(lst1[x]) >= 2008:
                    number = 1
                    break

            if lst1[x] == "2015" or lst1[x] == "2016" or lst1[
                    x] == "2017" or lst1[x] == "17" or lst1[x] == "16" or lst1[
                        x] == "15":
                number = 2
                break
            if lst1[x] == "2018" or lst1[x] == "18":
                number = 3
                break
            if lst1[x] == "2019" or lst1[x] == "19":
                number = 4
                break
            else:
                x = x + 1

        data = self.db.getConsultation(number)
        for entry in data:
            number = entry[0]
            batch = entry[1]
            date = entry[2]
            time = entry[3]
        response = "The schedule of consultations for Batch " + str(
            batch) + " is on " + date + " from " + time + " for all programs."
        return response

    def contact(self, lst1):
        def fallback():
            fallbackOptions = [
                "Can you be more specific for me?",
                "I don't quite understand on  what you ask about the email/contact number of your desired department.",
                "Can you be more specific on your inquiry?"
            ]
            rngFallback = random.choice(fallbackOptions)
            return rngFallback

        for x in range(0, len(lst1) + 1):
            if x == len(lst1):
                return fallback()
            if lst1[x] == "registrar":
                code = "registrar"
                break
            if lst1[x] == "treasurer" or lst1[x] == "treasury" or lst1[
                    x] == "treasurers":
                code = "treasury"
                break
            if lst1[x] == "admissions" or lst1[x] == "admission":
                code = "admissions"
                break
            if lst1[x] == "bookstore" or lst1[x] == "store":
                code = "bookstore"
                break
            if lst1[x] == "cdmo" or lst1[x] == "maintenance":
                code = "cdmo"
                break
            if lst1[x] == "pe":
                code = "pe"
                break
            if lst1[x] == "math" or lst1[x] == "mathematics":
                code = "math"
                break
            if lst1[x] == "physics":
                code = "physics"
                break
            if lst1[x] == "doit" or lst1[x] == "development" or lst1[x] == "it":
                code = "doit"
                break
            if lst1[x] == "etybsm" or lst1[x] == "business" or lst1[
                    x] == "yuchengco":
                code = "etybsm"
                break
            if lst1[x] == "aridbe" or lst1[x] == "architecture":
                code = "aridbe"
                break
            if lst1[x] == "cege" or lst1[x] == "civil" or lst1[
                    x] == "geological" or lst1[x] == "environmental":
                code = "cege"
                break
            if lst1[x] == "cbmes" or lst1[x] == "chem" or lst1[
                    x] == "chemical" or lst1[x] == "biological" or lst1[
                        x] == "materials":
                code = "cbmes"
                break
            if lst1[x] == "eece" or lst1[x] == "electrical" or lst1[
                    x] == "electronics" or lst1[x] == "computer" or lst1[
                        x] == "cpe" or lst1[x] == "ee" or lst1[x] == "ece":
                code = "eece"
                break
            if lst1[x] == "gs" or lst1[x] == "graduate":
                code = "gs"
                break
            if lst1[x] == "ie-emg" or lst1[x] == "ieemg" or lst1[
                    x] == "management" or lst1[x] == "industrial" or lst1[
                        x] == "ie" or lst1[x] == "mfge":
                code = "ie-emg"
                break
            if lst1[x] == "soit":
                code = "soit"
                break
            if lst1[x] == "mme" or lst1[x] == "mechanical" or lst1[
                    x] == "manufacturing":
                code = "mme"
                break
            if lst1[x] == "sms" or lst1[x] == "media":
                code = "sms"
                break
            if lst1[x] == "ssse" or lst1[x] == "social" or lst1[
                    x] == "education":
                code = "ssse"
                break
            if lst1[x] == "dal" or lst1[x] == "arts" or lst1[x] == "letters":
                code = "dal"
                break
            else:
                x = x + 1

        data = self.db.getContact(code)
        for entry in data:
            code = entry[0]
            department = entry[1]
            contact = entry[2]
            email = entry[3]

        mes = "Contact number of " + department + " is " + str(
            contact) + "\nAvailable email of " + department + " is " + email
        return mes

    def profSched(self, lst1):
        def fallback():
            fallbackOptions = [
                "Can you please be more specific on the class of the professor you're asking?",
                "I can't seem to find the name of the professor you're asking.",
                "Please make sure the name of the professor is correct."
            ]
            rngFallback = random.choice(fallbackOptions)
            return rngFallback

        for x in range(0, len(lst1) + 1):
            if x == len(lst1):
                return fallback()
            elif lst1[x] == "rafael" or lst1[x] == "maramba":
                for x in range(0, len(lst1) + 1):
                    if x == len(lst1):
                        return fallback()
                    elif lst1[x] == "logic" or lst1[x] == "circuits" or lst1[
                            x] == "cpe107" or lst1[x] == "107" or lst1[
                                x] == "logics":
                        for x in range(0, len(lst1) + 1):
                            if x == len(lst1):
                                return fallback()
                            elif lst1[x] == "b1":
                                code = "maramba_107_b1"
                                break
                            elif lst1[x] == "b2":
                                code = "maramba_107_b2"
                                break
                            else:
                                x = x + 1
                        break
                    elif lst1[x] == "comorg" or lst1[
                            x] == "organization" or lst1[
                                x] == "architecture" or lst1[
                                    x] == "110" or lst1[x] == "cpe110":
                        for x in range(0, len(lst1) + 1):
                            if x == len(lst1):
                                return fallback()
                            elif lst1[x] == "b1":
                                code = "maramba_110_b1"
                                break
                            elif lst1[x] == "b2":
                                code = "maramba_110_b2"
                                break
                            else:
                                x = x + 1
                        break
                    else:
                        x = x + 1
                break

            elif lst1[x] == "padilla" or lst1[x] == "dionis":
                for x in range(0, len(lst1) + 1):
                    if x == len(lst1):
                        return fallback()
                    elif lst1[x] == "software" or lst1[x] == "design" or lst1[
                            x] == "softdes" or lst1[x] == "106" or lst1[
                                x] == "cpe106":
                        for x in range(0, len(lst1) + 1):
                            if x == len(lst1):
                                return fallback()
                            elif lst1[x] == "b1":
                                code = "padilla_106_b1"
                                break
                            elif lst1[x] == "b2":
                                code = "padilla_106_b2"
                                break
                            else:
                                x = x + 1
                        break
                    else:
                        x = x + 1
                break

            elif lst1[x] == "manlises" or lst1[x] == "cyrel":
                for x in range(0, len(lst1) + 1):
                    if x == len(lst1):
                        return fallback()
                    elif lst1[x] == "microproccesor" or lst1[
                            x] == "microprocessors" or lst1[
                                x] == "micro" or lst1[x] == "108" or lst1[
                                    x] == "cpe108":
                        for x in range(0, len(lst1) + 1):
                            if x == len(lst1):
                                return fallback()
                            elif lst1[x] == "b1":
                                code = "manlises_108_b1"
                                break
                            elif lst1[x] == "b2":
                                code = "manlises_108_b2"
                                break
                            else:
                                x = x + 1
                        break
                    else:
                        x = x + 1
                break

        data = self.db.getProfSched(code)
        for entry in data:
            code = entry[0]
            profLast = entry[1]
            profFirst = entry[2]
            course = entry[3]
            section = entry[4]
            startTime = entry[5]
            endTime = entry[6]
            room = entry[7]
            day = entry[8]

        mes = "\nClass Information: \nProfessor: " + profLast + ", " + profFirst + "\nCourse and Section: " + course + "-" + section + "\nDay: " + day + "\nTime: " + startTime + "-" + endTime + "\nRoom: " + room
        return mes

    def news(self, lst1):
        def fallback():
            fallbackOptions = [
                "Can you be more specific for me?",
                "I don't quite understand on  what you ask about that news.",
                "Can you be more specific on your inquiry?"
            ]
            rngFallback = random.choice(fallbackOptions)
            return rngFallback

        for x in range(0, len(lst1) + 1):
            if x == len(lst1):
                return fallback()
            if lst1[x] == "medical" or lst1[x] == "assistance" or lst1[
                    x] == "checkup" or lst1[x] == "check-up" or lst1[
                        x] == "diagnosis":
                code = "medical"
                break
            if lst1[x] == "cybersecurity" or lst1[x] == "cybersec" or lst1[
                    x] == "sophos":
                code = "cybersec"
                break
            if lst1[x] == "dole" or lst1[x] == "solidarity":
                code = "dole"
                break
            if lst1[x] == "alvin" or lst1[x] == "caparanga" or lst1[
                    x] == "chemical" or lst1[x] == "engineer" or lst1[
                        x] == "piche" or lst1[x] == "national" or lst1[
                            x] == "convention":
                code = "caparanga"
                break
            if lst1[x] == "filmmaker" or lst1[x] == "donation" or lst1[
                    x] == "donations" or lst1[x] == "frontliners":
                code = "filmmaker"
                break
            if lst1[x] == "rising" or lst1[x] == "challenge" or lst1[
                    x] == "vea" or lst1[x] == "reynaldo" or lst1[
                        x] == "covid-19" or lst1[x] == "covid":
                code = "rising"
            if lst1[x] == "ranking" or lst1[x] == "THE" or lst1[
                    x] == "times" or lst1[x] == "higher" or lst1[
                        x] == "impact" or lst1[x] == "rankings":
                code = "ranking"
                break

        data = self.db.getNews(code)
        for entry in data:
            code = entry[0]
            headline = entry[1]
            link = entry[2]

        mes = headline + "\nRead more at: " + link
        return mes

    def randomAsk(self):
        askResponses = [
            "What can I do for you?", "What kind of assistance can I give?",
            "What brought you to me?"
        ]
        rngResponse = random.choice(askResponses)
        return rngResponse

    def randomGreeting(self):
        greetings = [
            "Hi, welcome to CardinalAIDS+!", "Hi, I hope you're doing well."
        ]
        greet = random.choice(greetings)
        return greet

    def getQues(self, question):
        while self.flag == "yes":

            lst1 = self.convert(question.lower())

            for x in range(0, len(lst1) + 1):
                if x == len(lst1):
                    return self.randomAsk()

                elif lst1[x] == "unsettled" or lst1[x] == "charges" or lst1[
                        x] == "fees" or lst1[x] == "balance" or lst1[
                            x] == "balances":
                    ans = self.unsettledFees(self.lastName, self.firstName,
                                             self.middle, self.unsettled)

                    return ans
                elif lst1[x] == "scholarships" or lst1[
                        x] == "scholarship" or lst1[x] == "scho":
                    ans = self.scholarship(lst1)

                    return ans
                elif lst1[x] == "contact" or lst1[x] == "number" or lst1[
                        x] == "email" or lst1[x] == "e-mail":
                    ans = self.contact(lst1)

                    return ans
                elif lst1[x] == "enrollment" or lst1[x] == "enrolment" or lst1[
                        x] == "enrol" or lst1[x] == "enroll":
                    ans = self.schedEnroll(lst1)

                    return ans
                elif lst1[x] == lst1[x] == "consult" or lst1[
                        x] == "consultation":
                    ans = self.schedConsult(lst1)

                    return ans
                elif lst1[x] == "professor" or lst1[x] == "prof" or lst1[
                        x] == "mam" or lst1[x] == "ma'am" or lst1[
                            x] == "ms." or lst1[x] == "ms" or lst1[
                                x] == "miss" or lst1[x] == "sir" or lst1[
                                    x] == "mr." or lst1[x] == "mr" or lst1[
                                        x] == "mister" or lst1[
                                            x] == "engr" or lst1[
                                                x] == "engineer" or lst1[
                                                    x] == "class":
                    ans = self.profSched(lst1)

                    return ans
                elif lst1[x] == "news" or lst1[x] == "updates" or lst1[
                        x] == "info" or lst1[x] == "information":
                    ans = self.news(lst1)

                    return ans
                else:
                    x = x + 1
示例#4
0
class LoginWindow(QtWidgets.QDialog, Ui_LoginWindow):
    stdAccept = QtCore.pyqtSignal(str, str)
    admAccept = QtCore.pyqtSignal(str, str)

    def __init__(self, username='', user='', parent=None):
        super(LoginWindow, self).__init__(parent)
        self.setupUi(self)
        self.setFixedSize(341, 481)

        # icons and images
        self.setWindowIcon(QtGui.QIcon('./UI/CardinalAIDS-icofile.ico'))
        self.logo.setPixmap(QtGui.QPixmap('./UI/CardinalAIDS-full.jpg'))
        self.logoAdmin.setPixmap(QtGui.QPixmap('./UI/CardinalAIDS-full.jpg'))
        self.logo_3.setPixmap(QtGui.QPixmap('./UI/CardinalAIDS-full.jpg'))

        # connects the login buttons to respective functions
        self.loginBtn.clicked.connect(self.authenticateStd)
        self.loginAdBtn.clicked.connect(self.authenticateAdm)

        # masks the password text fields
        self.passText.setEchoMode(QtWidgets.QLineEdit.Password)
        self.passAdText.setEchoMode(QtWidgets.QLineEdit.Password)

        # enables the use of the 'ENTER' key to activate function
        self.userText.returnPressed.connect(self.authenticateStd)
        self.passText.returnPressed.connect(self.authenticateStd)
        self.userAdText.returnPressed.connect(self.authenticateAdm)
        self.passAdText.returnPressed.connect(self.authenticateAdm)

        # enables use of the 'TAB' key to move between widgets/elements in the window
        tabFocus = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Tab),
                                       self)
        tabFocus.activated.connect(self.changeFocus)

        # messages initially not visible
        self.incorrrectLbl.setVisible(False)
        self.incorrrecAdmLbl.setVisible(False)

        #initialize database
        self.db = Database()
        if user == 'students':  # applicable after logging out and seeing login screen
            self.userText.setText(
                username)  # puts the previous username on text field and
            self.passText.setFocus()  # sets the current tab to recent user
            self.tabWidget.setCurrentIndex(0)
        if user == 'admins':
            self.userAdText.setText(username)
            self.passAdText.setFocus()
            self.tabWidget.setCurrentIndex(1)

    @QtCore.pyqtSlot(
    )  # called by 'TAB' keypress to allow next focus on widget/element
    def changeFocus(self):
        self.focusNextChild()

    # prevents entering empty/no values in text boxes
    def checkWhiteSpace(self, word):
        checker = True
        if word.isspace() or word == '':
            checker = False
        else:
            checker = True
        return checker

    # gets the student info from respective text fields
    def getStudentInfo(self, username, password):
        username = self.userText.text()
        password = self.passText.text()

    # gets the student info from respective text fields
    def getAdminInfo(self, username, password):
        username = self.userAdText.text()
        password = self.passAdText.text()

    @QtCore.pyqtSlot()  # function for logging in a student account
    def authenticateStd(self):
        userStd = self.userText.text()
        passStd = self.passText.text()
        checkUser = self.checkWhiteSpace(userStd)
        checkPass = self.checkWhiteSpace(passStd)
        if checkUser and checkPass:
            if self.db.checkPassword(userStd, passStd, 'students'):
                self.stdAccept.emit(userStd, 'students')
                self.accept()
            else:
                self.passText.clear()
                self.incorrrectLbl.setVisible(True)
        else:
            self.userText.clear()
            self.passText.clear()
            self.incorrrectLbl.setVisible(True)

    @QtCore.pyqtSlot()  # function for logging in an admin account
    def authenticateAdm(self):
        userAdm = self.userAdText.text()
        passAdm = self.passAdText.text()
        checkAdmUser = self.checkWhiteSpace(userAdm)
        checkAdmPass = self.checkWhiteSpace(passAdm)
        if checkAdmUser and checkAdmPass:
            if self.db.checkPassword(userAdm, passAdm, 'admins'):
                self.admAccept.emit(userAdm, 'admins')
                self.accept()
            else:
                self.passAdText.clear()
                self.incorrrecAdmLbl.setVisible(True)
        else:
            self.userAdText.clear()
            self.passAdText.clear()
            self.incorrrecAdmLbl.setVisible(True)
示例#5
0
    def __init__(self, username='', user='', parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.setFixedSize(540, 499)
        self.setWindowIcon(QtGui.QIcon('./UI/CardinalAIDS-icofile.ico'))

        self.username = username
        self.user = user
        self.db = Database()

        # store tab references for dynamic changing of main window tabs
        self.resetTabRef = self.cardinalTabWidget
        self.chatTabRef = self.chatTab
        self.historyTabRef = self.historyTab
        self.askedTabRef = self.askedTab
        self.invalidTabRef = self.invalidTab
        self.updateTabRef = self.updateTab
        self.accTabRef = self.accTab

        # button connections to functions
        self.logoutBtn.clicked.connect(self.logout)
        self.sendBtn.clicked.connect(self.chat)
        self.changePW.clicked.connect(self.change)
        self.invalidBtn.clicked.connect(self.invalid)
        self.deleteAskedBtn.clicked.connect(self.deleteAskedEntry)
        self.deleteInvalidBtn.clicked.connect(self.deleteInvalidEntry)
        self.addBtn.clicked.connect(self.addStudent)
        self.removeBtn.clicked.connect(self.removeStudent)
        self.updateBtn.clicked.connect(self.updateStudent)

        # connect pw text boxes to message to detect changes
        self.oldPWText.textEdited.connect(self.checkPW)
        self.newPWText.textEdited.connect(self.checkPW)
        self.confirmPWText.textEdited.connect(self.checkPW)

        # mask the password textboxes
        self.oldPWText.setEchoMode(QtWidgets.QLineEdit.Password)
        self.newPWText.setEchoMode(QtWidgets.QLineEdit.Password)
        self.confirmPWText.setEchoMode(QtWidgets.QLineEdit.Password)

        # widgets' parameters
        self.listWidget.setWordWrap(True)
        self.matchPassword.setVisible(False)
        self.incorrectChange.setVisible(False)
        self.updateMessage.setVisible(False)
        histHeader = self.historyTable.horizontalHeader()
        self.historyTable.setColumnCount(2)
        histHeader.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
        histHeader.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
        self.historyTable.setHorizontalHeaderLabels(["QUESTIONS", "ANSWERS"])
        self.askedTable.verticalHeader().setVisible(True)
        self.askedTable.setColumnCount(3)
        self.askedTable.resizeColumnsToContents()
        askedHeader = self.askedTable.horizontalHeader()
        askedHeader.setSectionResizeMode(
            0, QtWidgets.QHeaderView.ResizeToContents)
        askedHeader.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        askedVertHeader = self.askedTable.verticalHeader()
        askedVertHeader.setSectionResizeMode(
            QtWidgets.QHeaderView.ResizeToContents)
        invalidHeader = self.invalidTable.horizontalHeader()
        invalidHeader.setSectionResizeMode(
            0, QtWidgets.QHeaderView.ResizeToContents)
        self.askedTable.setColumnWidth(1, 60)
        self.invalidTable.verticalHeader().setVisible(True)
        self.invalidTable.setColumnCount(3)
        invalidHeader.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        invalidVertHeader = self.invalidTable.verticalHeader()
        invalidVertHeader.setSectionResizeMode(
            QtWidgets.QHeaderView.ResizeToContents)
        self.invalidTable.setHorizontalHeaderLabels(
            ["USER", "QUESTIONS", "ANSWERS"])
        self.askedTable.setHorizontalHeaderLabels(
            ["USER", "QUESTIONS", "ANSWERS"])
        self.invalidTable.setColumnWidth(1, 60)

        # begin interface with login
        self.showLogin()
示例#6
0
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, username='', user='', parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.setFixedSize(540, 499)
        self.setWindowIcon(QtGui.QIcon('./UI/CardinalAIDS-icofile.ico'))

        self.username = username
        self.user = user
        self.db = Database()

        # store tab references for dynamic changing of main window tabs
        self.resetTabRef = self.cardinalTabWidget
        self.chatTabRef = self.chatTab
        self.historyTabRef = self.historyTab
        self.askedTabRef = self.askedTab
        self.invalidTabRef = self.invalidTab
        self.updateTabRef = self.updateTab
        self.accTabRef = self.accTab

        # button connections to functions
        self.logoutBtn.clicked.connect(self.logout)
        self.sendBtn.clicked.connect(self.chat)
        self.changePW.clicked.connect(self.change)
        self.invalidBtn.clicked.connect(self.invalid)
        self.deleteAskedBtn.clicked.connect(self.deleteAskedEntry)
        self.deleteInvalidBtn.clicked.connect(self.deleteInvalidEntry)
        self.addBtn.clicked.connect(self.addStudent)
        self.removeBtn.clicked.connect(self.removeStudent)
        self.updateBtn.clicked.connect(self.updateStudent)

        # connect pw text boxes to message to detect changes
        self.oldPWText.textEdited.connect(self.checkPW)
        self.newPWText.textEdited.connect(self.checkPW)
        self.confirmPWText.textEdited.connect(self.checkPW)

        # mask the password textboxes
        self.oldPWText.setEchoMode(QtWidgets.QLineEdit.Password)
        self.newPWText.setEchoMode(QtWidgets.QLineEdit.Password)
        self.confirmPWText.setEchoMode(QtWidgets.QLineEdit.Password)

        # widgets' parameters
        self.listWidget.setWordWrap(True)
        self.matchPassword.setVisible(False)
        self.incorrectChange.setVisible(False)
        self.updateMessage.setVisible(False)
        histHeader = self.historyTable.horizontalHeader()
        self.historyTable.setColumnCount(2)
        histHeader.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
        histHeader.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
        self.historyTable.setHorizontalHeaderLabels(["QUESTIONS", "ANSWERS"])
        self.askedTable.verticalHeader().setVisible(True)
        self.askedTable.setColumnCount(3)
        self.askedTable.resizeColumnsToContents()
        askedHeader = self.askedTable.horizontalHeader()
        askedHeader.setSectionResizeMode(
            0, QtWidgets.QHeaderView.ResizeToContents)
        askedHeader.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        askedVertHeader = self.askedTable.verticalHeader()
        askedVertHeader.setSectionResizeMode(
            QtWidgets.QHeaderView.ResizeToContents)
        invalidHeader = self.invalidTable.horizontalHeader()
        invalidHeader.setSectionResizeMode(
            0, QtWidgets.QHeaderView.ResizeToContents)
        self.askedTable.setColumnWidth(1, 60)
        self.invalidTable.verticalHeader().setVisible(True)
        self.invalidTable.setColumnCount(3)
        invalidHeader.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        invalidVertHeader = self.invalidTable.verticalHeader()
        invalidVertHeader.setSectionResizeMode(
            QtWidgets.QHeaderView.ResizeToContents)
        self.invalidTable.setHorizontalHeaderLabels(
            ["USER", "QUESTIONS", "ANSWERS"])
        self.askedTable.setHorizontalHeaderLabels(
            ["USER", "QUESTIONS", "ANSWERS"])
        self.invalidTable.setColumnWidth(1, 60)

        # begin interface with login
        self.showLogin()

    # sets the tabs in the widget for a student login/user
    @QtCore.pyqtSlot(str, str)
    def studentUser(self, std, user):
        self.username = std
        self.user = user
        self.bot = AIchat(self.username)
        self.giveGreeting()
        self.cardinalTabWidget.removeTab(2)
        self.cardinalTabWidget.removeTab(2)
        self.cardinalTabWidget.removeTab(2)
        self.load_stdData()  # loads the history of the student's chats

    # sets the tabs in the widget for an admin login/user
    @QtCore.pyqtSlot(str, str)
    def adminUser(self, adm, user):
        self.username = adm
        self.user = user
        self.cardinalTabWidget.removeTab(0)
        self.cardinalTabWidget.removeTab(0)
        self.load_askedData()  # loads the valid history of all student chats
        self.load_invalidData(
        )  # loads the invalid history of the all student chats

    # shows the login
    def showLogin(self):
        login = LoginWindow(self.username, self.user)
        login.stdAccept.connect(self.studentUser)
        login.admAccept.connect(self.adminUser)
        if login.exec_() == QtWidgets.QDialog.Accepted:
            self.show()

    # clears tabs and resets them using references
    def resetTabs(self):
        self.cardinalTabWidget.clear()
        self.cardinalTabWidget.insertTab(0, self.chatTabRef, 'CHAT')
        self.cardinalTabWidget.insertTab(1, self.historyTabRef, 'HISTORY')
        self.cardinalTabWidget.insertTab(2, self.askedTabRef,
                                         'ASKED QUESTIONS')
        self.cardinalTabWidget.insertTab(3, self.invalidTabRef,
                                         'INVALID ANSWERS')
        self.cardinalTabWidget.insertTab(4, self.updateTabRef,
                                         'UPDATE STUDENT INFO')
        self.cardinalTabWidget.insertTab(5, self.accTabRef, 'ACCOUNT')

    # first chat of the bot; greets the student
    def giveGreeting(self):
        self.listWidget.addItem("CardinalAIDS+: " + self.bot.randomGreeting())
        replies = self.listWidget.findItems("CardinalAIDS+:",
                                            QtCore.Qt.MatchStartsWith)
        self.colorReply(replies)

    # changes the color of the bot's replies to distinguish messages
    def colorReply(self, replies):
        if len(replies) > 0:
            for reply in replies:
                reply.setForeground(QtGui.QColor("white"))
                reply.setBackground(QtGui.QColor("#cc0000"))

    # prevents entering empty/no values in text boxes
    def checkWhiteSpace(self, word):
        checker = True
        if word.isspace() or word == '':
            checker = False
        else:
            checker = True
        return checker

    # accesses the database to get info and display it in the UI
    def load_stdData(self):
        self.historyTable.verticalHeader().setVisible(True)
        rows = self.db.loadStudentTableData(self.username)
        for row in rows:
            inx = rows.index(row)
            self.historyTable.insertRow(inx)
            self.historyTable.setItem(inx, 0,
                                      QtWidgets.QTableWidgetItem(row[1]))
            self.historyTable.setItem(inx, 1,
                                      QtWidgets.QTableWidgetItem(row[2]))

    # next two functions used for admin users
    def load_askedData(self):
        rows = self.db.loadAdminTableData('valid')
        for row in rows:
            inx = rows.index(row)
            self.askedTable.insertRow(inx)
            self.askedTable.setItem(inx, 0, QtWidgets.QTableWidgetItem(row[0]))
            self.askedTable.setItem(inx, 1, QtWidgets.QTableWidgetItem(row[1]))
            self.askedTable.setItem(inx, 2, QtWidgets.QTableWidgetItem(row[2]))

    def load_invalidData(self):
        rows = self.db.loadAdminTableData('invalid')
        for row in rows:
            inx = rows.index(row)
            self.invalidTable.insertRow(inx)
            self.invalidTable.setItem(inx, 0,
                                      QtWidgets.QTableWidgetItem(row[0]))
            self.invalidTable.setItem(inx, 1,
                                      QtWidgets.QTableWidgetItem(row[1]))
            self.invalidTable.setItem(inx, 2,
                                      QtWidgets.QTableWidgetItem(row[2]))

    @QtCore.pyqtSlot()  # processes the chat, adds in the list and the database
    def chat(self):
        self.question = self.questionText.text()
        checkQues = self.checkWhiteSpace(self.question)
        if checkQues:
            self.listWidget.addItem("You: " + self.question)
            self.answer = self.bot.getQues(self.question)
            self.listWidget.addItem("CardinalAIDS: " + self.answer)
            replies = self.listWidget.findItems("CardinalAIDS:",
                                                QtCore.Qt.MatchStartsWith)
            self.colorReply(replies)
            numRows = self.historyTable.rowCount()
            self.historyTable.insertRow(numRows)
            self.historyTable.setItem(
                numRows, 0, QtWidgets.QTableWidgetItem(self.question))
            self.historyTable.setItem(numRows, 1,
                                      QtWidgets.QTableWidgetItem(self.answer))
            self.historyTable.resizeRowsToContents()
            self.db.addToHistory(self.username, self.question, self.answer)
            self.questionText.clear()

    @QtCore.pyqtSlot(
    )  # sets the last two messages (question and answer) as invalid
    def invalid(self):
        row = self.listWidget.count()
        if row > 2:
            question = self.listWidget.item(row - 2).text().replace(
                'You: ', '')
            answer = self.listWidget.item(row - 1).text().replace(
                'CardinalAIDS: ', '')
            self.db.makeInvalid(self.username, question, answer)

    @QtCore.pyqtSlot()  # admin use; deletes entry when a row is selected
    def deleteAskedEntry(self):
        indexList = []
        indexes = self.askedTable.selectionModel().selectedRows()

        for index in sorted(indexes):
            user = index.sibling(index.row(), index.column()).data()
            question = index.sibling(index.row(), index.column() + 1).data()
            answer = index.sibling(index.row(), index.column() + 2).data()
            row = QtCore.QPersistentModelIndex(index)
            indexList.append(row)
            self.db.deleteTableData(user, question, answer)

        for rowIndex in indexList:
            self.askedTable.removeRow(rowIndex.row())

    @QtCore.pyqtSlot()  # admin use; deletes entry when a row is selected
    def deleteInvalidEntry(self):
        indexList = []
        indexes = self.invalidTable.selectionModel().selectedRows()

        for index in sorted(indexes):
            user = index.sibling(index.row(), index.column()).data()
            question = index.sibling(index.row(), index.column() + 1).data()
            answer = index.sibling(index.row(), index.column() + 2).data()
            row = QtCore.QPersistentModelIndex(index)
            indexList.append(row)
            self.db.deleteTableData(user, question, answer)

        for rowIndex in indexList:
            self.invalidTable.removeRow(rowIndex.row())

    # retrieves info for adding, removing, updating student info
    def getStudentInfo(self):
        self.usernameStd = self.updateUserText.text()
        self.passwordStd = self.updatePassText.text()
        self.firstStd = self.updateFirstText.text()
        self.middleStd = self.updateMiddleText.text()
        self.lastStd = self.updateLastText.text()
        self.feesStd = self.updateFeesText.text()
        self.canUpdate = False
        if self.passwordStd != '' or self.firstStd != '' or self.middleStd != '' or self.lastStd != '' or self.feesStd != '':
            self.canUpdate = True

        self.updateList = []
        if self.passwordStd != '':
            self.updateList.append('password')
            self.updateList.append(self.passwordStd)
        if self.firstStd != '':
            self.updateList.append('firstName')
            self.updateList.append(self.firstStd)
        if self.middleStd != '':
            self.updateList.append('middleInitial')
            self.updateList.append(self.middleStd)
        if self.lastStd != '':
            self.updateList.append('lastName')
            self.updateList.append(self.lastStd)
        if self.feesStd != '':
            self.updateList.append('unsettled')
            self.updateList.append(self.feesStd)

    def clearInfo(self):
        self.updateUserText.clear()
        self.updatePassText.clear()
        self.updateFirstText.clear()
        self.updateMiddleText.clear()
        self.updateLastText.clear()
        self.updateFeesText.clear()
        self.updateList.clear()

    # changes update message colors and visibility
    def messageColors(self, message, check):
        if check:
            message.setStyleSheet('color: green; background: white')
        else:
            message.setStyleSheet('color: red; background: white')
        message.setVisible(True)

    @QtCore.pyqtSlot()  # adds student to database with data from text fields
    def addStudent(self):
        self.getStudentInfo()
        if self.usernameStd == '' or self.passwordStd == '' or self.firstStd == '' or self.middleStd == '' or self.lastStd == '' or self.feesStd == '':
            self.updateMessage.setText('Required field(s) empty.')
            self.messageColors(self.updateMessage, False)
        else:
            existStd = self.db.checkStudent(self.usernameStd)
            if existStd:
                self.updateMessage.setText('Username already exists.')
                self.messageColors(self.updateMessage, False)
                self.updateUserText.setFocus()
            else:
                self.db.addToStudents(self.usernameStd, self.passwordStd,
                                      self.firstStd, self.middleStd,
                                      self.lastStd, self.feesStd)
                self.clearInfo()
                self.updateUserText.setFocus()
                self.updateMessage.setText('Added student info to database.')
                self.messageColors(self.updateMessage, True)

    @QtCore.pyqtSlot(
    )  # deletes a student's info from the database using their username
    def removeStudent(self):
        self.getStudentInfo()
        if self.usernameStd == '':
            self.updateMessage.setText(
                'Requires username to remove student from database.')
            self.messageColors(self.updateMessage, False)
        else:
            existStd = self.db.checkStudent(self.usernameStd)
            if existStd:
                self.db.delFromStudents(self.usernameStd)
                self.clearInfo()
                self.updateUserText.setFocus()
                self.updateMessage.setText(
                    'Removed student info from database.')
                self.messageColors(self.updateMessage, True)
            else:
                self.updateMessage.setText('Username/Student does not exist.')
                self.messageColors(self.updateMessage, False)
                self.updateUserText.setFocus()

    @QtCore.pyqtSlot(
    )  # updates a student's info by getting username and at least one field
    def updateStudent(self):
        self.getStudentInfo()
        if self.usernameStd == '' or not self.canUpdate:
            self.updateMessage.setText(
                'Requires username and another entry to update student info in database.'
            )
            self.messageColors(self.updateMessage, False)
        else:
            existStd = self.db.checkStudent(self.usernameStd)
            if existStd:
                self.db.updateStudents(self.usernameStd, self.updateList)
                self.clearInfo()
                self.updateUserText.setFocus()
                self.updateMessage.setText(
                    'Updated student info from database.')
                self.messageColors(self.updateMessage, True)
            else:
                self.updateMessage.setText('Username/Student does not exist.')
                self.messageColors(self.updateMessage, False)
                self.updateUserText.setFocus()

    def checkPW(
            self
    ):  # checks if passwords entered are valid and displays messages
        check = False
        self.old = self.oldPWText.text()
        self.new = self.newPWText.text()
        if self.db.checkPassword(self.username, self.old, self.user):
            self.incorrectChange.setText("Current password correct.")
            self.messageColors(self.incorrectChange, True)
            if self.newPWText.text() != '' or self.confirmPWText.text() != '':
                if self.newPWText.text() == self.confirmPWText.text():
                    check = True
                    self.matchPassword.setText("Passwords match.")
                    self.messageColors(self.matchPassword, True)
                else:
                    check = False
                    if self.newPWText.text() == '' or self.confirmPWText.text(
                    ) == '':
                        self.matchPassword.setText('Empty password field(s).')
                        self.messageColors(self.matchPassword, False)
                    else:
                        self.matchPassword.setText("Passwords do not match.")
                        self.messageColors(self.matchPassword, False)
            else:
                check = False
                self.matchPassword.setText('Empty password field(s).')
                self.messageColors(self.matchPassword, False)
        else:
            check = False
            self.incorrectChange.setText("Current password incorrect.")
            self.messageColors(self.incorrectChange, False)
        return check

    @QtCore.pyqtSlot(
    )  # handles the change of passwords by students and admins
    def change(self):
        if self.checkPW:
            self.db.changePassword(self.username, self.user, self.old,
                                   self.new)
            self.oldPWText.clear()
            self.newPWText.clear()
            self.confirmPWText.clear()
            self.incorrectChange.setVisible(False)
            self.matchPassword.setVisible(False)

    # resets tabs, tables within and messages
    def cleanUp(self):
        self.resetTabs()
        self.listWidget.clear()
        self.cardinalTabWidget.setCurrentIndex(0)
        self.historyTable.clearContents()
        self.historyTable.setRowCount(0)
        self.askedTable.clearContents()
        self.invalidTable.clearContents()
        self.askedTable.setRowCount(0)
        self.invalidTable.setRowCount(0)
        self.updateMessage.setVisible(False)

    @QtCore.pyqtSlot(
    )  # logout function; resets main window and call login again
    def logout(self):
        self.cleanUp()
        self.close()
        self.showLogin()