Making simple chatbot with pyqt5 without pushbutton

Viewed 590

I want to make simplest chatbot.

Aim- Taking input from single textEdit on pressing Enter button on Keyboard and show output on same textEdit like console.

My Problem - can't connect chatbot with Pyqt5 gui.

from PyQt5 import QtCore, QtGui, QtWidgets
from nltk.chat.util import Chat,reflections
from functools import partial
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(640, 480)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setObjectName("textEdit")
        self.gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        #self.shortcut=QtGui.QShortcut(QtGui.QKeySequence("Return"),self)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 25))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        self.textEdit.setPlainText("hello your welcome ask anything.Type 'quit' in lower case for leave")

        self.pairs = [
                [r"my name is (.*)",
                 ["Hello %1 , how are you today?",]],

                [r"(what is your name?|who are you?)",
                 ["my name is chhatty.\n And yours?"]],

                [r"(what is your (location|city)?|from where you are talking)",
                ["i am here, in front of you \n have you any sense same location as yours"]],

                [r"(you) are (.*)",
                 ["i am very very intelligent computer  \n %1 not %2 may be you are %2"]],

                 [r"is human (.*)",
                  [" i think human is not very intelligent but may be %1"]],

                  [r"(.*)",
                   ["what!\n Sorry,i can't understand "]]
                ] 

        self.chat =Chat(self.pairs,reflections)
        self.chat.converse()


if __name__ == "__main__":
    import sys
    app =QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

and this is not working on pyqt5, i want to take input on pressing enter button.

self.shortcut=QtGui.QShortcut(QtGui.QKeySequence("Return"),self)

and how to connect this chat with textEdit.

 self.chat =Chat(self.pairs,reflections)
 self.chat.converse()
1 Answers

Using a QTextEdit as input and output is complicated since with an eventfilter it can be detected when pressing enter it is difficult to obtain the text added by the user since he could modify another previous part of the text, in addition to other problems.

Therefore, I propose to modify your widget so that the text added by the user is through a QLineEdit.

To get the response from the chat bot you must use the respond() method instead of converse().

from PyQt5 import QtCore, QtGui, QtWidgets
from nltk.chat.util import Chat, reflections


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.output_te = QtWidgets.QTextEdit(readOnly=True)
        self.input_le = QtWidgets.QLineEdit(returnPressed=self.on_return_pressed)

        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        lay = QtWidgets.QVBoxLayout(central_widget)
        lay.addWidget(self.output_te)
        lay.addWidget(self.input_le)

        self.output_te.setPlainText(
            "hello your welcome ask anything.Type 'quit' in lower case for leave"
        )

        pairs = [
            [r"my name is (.*)", ["Hello %1 , how are you today?",]],
            [
                r"(what is your name?|who are you?)",
                ["my name is chhatty.\n And yours?"],
            ],
            [
                r"(what is your (location|city)?|from where you are talking)",
                [
                    "i am here, in front of you \n have you any sense same location as yours"
                ],
            ],
            [
                r"(you) are (.*)",
                ["i am very very intelligent computer  \n %1 not %2 may be you are %2"],
            ],
            [
                r"is human (.*)",
                [" i think human is not very intelligent but may be %1"],
            ],
            [r"(.*)", ["what!\n Sorry,i can't understand "]],
        ]

        self._chat = Chat(pairs, reflections)

    @property
    def chat(self):
        return self._chat

    @QtCore.pyqtSlot()
    def on_return_pressed(self):
        text = self.input_le.text()
        if text:
            res = self.chat.respond(text)
            self.output_te.append("[me]: {}".format(text))
            self.output_te.append("[bot]: {}".format(res))
            self.input_le.clear()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
Related