示例#1
0
    def __init__(self, app):
        super().__init__()
        self.app = app
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.connected = False
        self.messageInformer = QMessageBox()
        self.fileManager = PassnerFileManager()
        self.database = PassnerDatabase(self.fileManager.getDir() + '/data.db')

        self.temp = list()
        self.currentAccountId = None

        self.ui.connectBtn.clicked.connect(self.connect)
        self.ui.addBtn.clicked.connect(self.addUsername)
        self.ui.deleteBtn.clicked.connect(self.deleteAccount)
        self.ui.editBtn.clicked.connect(self.checkChanges)

        self.ui.tableWidget.setSelectionBehavior(QTableView.SelectRows)
        self.ui.tableWidget.cellClicked.connect(self.selectAccount)

        self.verifyDirectory()
        self.verifyDatabase()
        self.verifyKeyMaster()
示例#2
0
class CorrectText(QtWidgets.QMainWindow):
    def __init__(self):
        super(CorrectText, self).__init__()
        self.dialog = Ui_MainWindow()
        self.dialog.setupUi(self)
        self.init_UI()

    def init_UI(self):
        self.setWindowTitle('Исправление ошибок')
        self.setWindowIcon(QIcon('Alice1.jpg'))
        self.dialog.textEdit.setPlaceholderText('Текст с ошибками')
        self.dialog.textEdit_2.setPlaceholderText('Исправленный текст')
        self.dialog.pushButton.clicked.connect(self.generate_button_clicked)
        self.dialog.textEdit_2.setReadOnly(True)

    def generate_button_clicked(self):
        #pass
        self.dialog.textEdit_2.clear()
        input_text = self.dialog.textEdit
        if input_text.toPlainText() == "":
            self.dialog.textEdit_2.insertPlainText(
                "Пожалуйста, введите текст!")
        else:
            self.dialog.textEdit_2.insertPlainText(
                generate_from_text(model_new,
                                   input_text.toPlainText(),
                                   num_beams=10))
示例#3
0
文件: main.py 项目: GaboGomezT/sali
    def __init__(self):
        super().__init__()

        title = "Sali"
        self.setWindowTitle(title)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.openFileDialog)

        self.show()
示例#4
0
 def __init__(self):
     super(ApplicationWindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.btnBrowse.clicked.connect(self.Browse_clicked2)
     self.ui.btnStart.clicked.connect(self.btnStart_clicked)
     self.ui.btnPause.clicked.connect(self.btnPause_clicked)
     self.progressSignal.connect(self.progressBar)
     self.ui.progressBar.setRange(0, 64)
     self.progressBarValue = 0
     self.ui.btnStart.setEnabled(True)
示例#5
0
 def __init__(self):
     super(CorrectText, self).__init__()
     self.dialog = Ui_MainWindow()
     self.dialog.setupUi(self)
     self.init_UI()
示例#6
0
class PassnerApp(QDialog):
    def __init__(self, app):
        super().__init__()
        self.app = app
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.connected = False
        self.messageInformer = QMessageBox()
        self.fileManager = PassnerFileManager()
        self.database = PassnerDatabase(self.fileManager.getDir() + '/data.db')

        self.temp = list()
        self.currentAccountId = None

        self.ui.connectBtn.clicked.connect(self.connect)
        self.ui.addBtn.clicked.connect(self.addUsername)
        self.ui.deleteBtn.clicked.connect(self.deleteAccount)
        self.ui.editBtn.clicked.connect(self.checkChanges)

        self.ui.tableWidget.setSelectionBehavior(QTableView.SelectRows)
        self.ui.tableWidget.cellClicked.connect(self.selectAccount)

        self.verifyDirectory()
        self.verifyDatabase()
        self.verifyKeyMaster()

    def showMessage(self, title, msg, ty, desc=None):
        if desc != None: self.messageInformer.setInformativeText(desc)
        self.messageInformer.setIcon(ty)
        self.messageInformer.setText(msg)
        self.messageInformer.setFixedHeight(400)
        self.messageInformer.setFixedWidth(400)
        self.messageInformer.setWindowTitle(title)
        self.messageInformer.exec_()
        self.messageInformer.setInformativeText('')

    def verifyKeyMaster(self):
        if not self.database.getKeyMaster():
            key, r = QInputDialog.getText(
                self,
                'Clave maestra',
                'Escribe la clave maestra que usaras para la aplicación',
                echo=QLineEdit.Password)
            if not r: return sys.exit(self.app.exec_())
            if not bool(key): return self.verifyKeyMaster()
            keye = pbkdf2_sha256.hash(key)
            self.database.addKeyMaster(keye)

    def closeEvent(self, event):
        self.database.closeConnection()
        event.accept()

    def checkChanges(self):
        if not self.connected:
            return self.showMessage('Error', 'No hay conexión',
                                    QMessageBox.Warning,
                                    'Conectate con tu clave maestra')
        originalData = self.database.getAccounts()
        for row in range(self.ui.tableWidget.rowCount()):
            for column in range(4):
                if column == 0: continue
                targetItem = self.ui.tableWidget.item(row, column)
                if targetItem:
                    if self.ui.tableWidget.item(
                            row, column).text() != originalData[row][column]:
                        pass
                        # next update

    def verifyDatabase(self):
        self.database.createConnection()
        if not self.database.existTables():
            self.database.createTables()
        else:
            pass

    def verifyDirectory(self):
        if not self.fileManager.existDir():
            res, msg = self.fileManager.createDir()
            if not res:
                self.showMessage('Error', str(msg), QMessageBox.Critical,
                                 'No se pudo acceder a los archivos internos')
                sys.exit(app.exec_())

    def addUsername(self):
        if not self.connected:
            return self.showMessage('Error', 'No hay conexión',
                                    QMessageBox.Warning,
                                    'Conectate con tu clave maestra')
        else:
            username, r = QInputDialog.getText(
                self, 'Usuario', 'Especifica el nombre de usuario')
            if not r or not bool(username): return False
            self.temp.append(username)
            return self.addPassword()

    def addPassword(self):
        password, r = QInputDialog.getText(self,
                                           'Contraseña',
                                           'Especifica la contraseña',
                                           echo=QLineEdit.Password)
        if not r or not bool(password): return False
        self.temp.append(password)
        return self.addInformation()

    def addInformation(self):
        text, r = QInputDialog.getText(
            self, 'Informacion', 'Especifica de donde proviene esta cuenta')
        if not r or not bool(text): return False

        self.temp.append(text)
        if self.database.addAccount(tuple(self.temp)):
            self.showMessage('Cuenta', 'Nueva cuenta agregada correctamente',
                             QMessageBox.Information)
            self.temp.clear()
            self.refreshTable()

    def selectAccount(self, row, column):
        self.currentAccountId = int(self.ui.tableWidget.item(row, 0).text())
        self.currentCell = self.ui.tableWidget.item(row, column)

    def refreshTable(self):
        self.ui.tableWidget.clearContents()
        self.ui.tableWidget.setRowCount(0)
        self.addAccountsOnTable()

    def editAccount(self):
        if not self.connected: return False
        if self.currentAccountId == None:
            return self.showMessage('Error',
                                    'Selecciona que cuenta quieres eliminar',
                                    QMessageBox.Warning)

    def deleteAccount(self):
        if not self.connected: return False
        if self.currentAccountId == None:
            return self.showMessage('Error',
                                    'Selecciona que cuenta quieres eliminar',
                                    QMessageBox.Warning)

        if self.database.deleteAccount(self.currentAccountId):
            self.showMessage('Cuenta', 'Cuenta eliminada correctamente',
                             QMessageBox.Information)
            self.refreshTable()
        else:
            return self.showMessage('Error', 'No se pudo eliminar la cuenta',
                                    QMessageBox.Warning)

    def addAccountsOnTable(self):
        if not self.connected: return False

        accounts = self.database.getAccounts()
        if not accounts: return False

        row = 0
        for account in accounts:
            column = 0
            self.ui.tableWidget.insertRow(row)
            for element in account:
                cell = QTableWidgetItem(str(element))
                if (column == 0): cell.setFlags(QtCore.Qt.ItemIsEnabled)
                self.ui.tableWidget.setItem(row, column, cell)
                column += 1
            row += 1

    def connect(self):
        if self.connected:
            return self.showMessage('Error', 'Ya estas conectado',
                                    QMessageBox.Warning)

        self.connected = self.database.createConnection()
        key = self.database.getKeyMaster()

        match = pbkdf2_sha256.verify(self.ui.keyInput.text(), key)
        self.ui.keyInput.setText('')

        if not match:
            self.connected = False
            self.database.closeConnection()
            return self.showMessage('Error', 'Clave maestra incorrecta',
                                    QMessageBox.Warning)

        self.showMessage('Info', 'Te has conectado correctamente',
                         QMessageBox.Information)
        self.addAccountsOnTable()
示例#7
0
class ApplicationWindow(QtWidgets.QMainWindow):

    progressSignal = pyqtSignal()

    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btnBrowse.clicked.connect(self.Browse_clicked2)
        self.ui.btnStart.clicked.connect(self.btnStart_clicked)
        self.ui.btnPause.clicked.connect(self.btnPause_clicked)
        self.progressSignal.connect(self.progressBar)
        self.ui.progressBar.setRange(0, 64)
        self.progressBarValue = 0
        self.ui.btnStart.setEnabled(True)

    def Browse_clicked2(self):
        fileName, _filter = QFileDialog.getOpenFileName(
            self, "Title", "Default File",
            "Filter -- All Files (*);;Image Files (*.jpeg)")
        try:
            numPix = int(self.ui.TextBoxPixel.toPlainText())
        except ValueError:
            QMessageBox.question(self, 'Error',
                                 "Please!!  Enter number of pixels frist.",
                                 QMessageBox.Ok)

        if 64 % numPix != 0:
            QMessageBox.question(
                self, 'Error',
                "Please!!  Enter number of pixels. or make sure it is factor of 64",
                QMessageBox.Ok)
            return

        try:
            if fileName:

                global myImage
                myImage = cv2.imread(fileName, cv2.IMREAD_GRAYSCALE)
                height, width = myImage.shape
                if height != width or height != 128:
                    QMessageBox.question(self, 'Error',
                                         "please insert 128 x 128 photo",
                                         QMessageBox.Ok)
                    return
                try:

                    qImg = QImage(myImage.data, width, height,
                                  QImage.Format_Grayscale8).rgbSwapped()
                    pixmap = QPixmap.fromImage(qImg)
                    x = 128 / pixmap.width()
                    y = 128 / pixmap.height()
                    pixmap = pixmap.scaled(int(pixmap.height() * y),
                                           int(pixmap.width() * x))
                    #self.ui.btnStart.setEnabled(True)

                    self.ui.btnPause.setEnabled(False)
                    self.ui.lblImg.setPixmap(QPixmap.fromImage(qImg))
                    self.ui.lblImg.setAlignment(QtCore.Qt.AlignHCenter
                                                | QtCore.Qt.AlignVCenter)
                except:
                    QMessageBox.question(self, 'Error', "It is not an Image",
                                         QMessageBox.Ok)
                    return
        except:
            self.ui.btnStart.setEnabled(True)
            QMessageBox.question(self, 'Error', "Please insert only images",
                                 QMessageBox.Ok)
            return

    def theLastModification(self):
        try:
            img = copy.deepcopy(myImage)
            compareImg = copy.deepcopy(myImage)
            numPix = int(self.ui.TextBoxPixel.toPlainText())
            if 64 % numPix != 0:
                QMessageBox.question(self, 'Error',
                                     "number of pixels must be factor of 64",
                                     QMessageBox.Ok)
                return
        except:
            self.ui.btnStart.setEnabled(True)
            self.ui.btnPause.setEnabled(False)
            self.ui.btnBrowse.setEnabled(True)
            return

        for i in range(0, 64, numPix):
            self.progressBarValue = i
            self.progressSignal.emit()
            try:
                self.ui.btnPause.setEnabled(True)
                numPix = int(self.ui.TextBoxPixel.toPlainText())
            except:
                self.ui.btnStart.setEnabled(True)
                self.ui.btnBrowse.setEnabled(True)
                return
            try:

                if i == 0:
                    imgFft = numpy.fft.fft2(img)
                    imgFftShift = numpy.fft.fftshift(imgFft)
                    with errstate(divide='ignore'):
                        magspec = 20 * numpy.log(numpy.abs(imgFftShift))
                    #magspec = numpy.asarray(magspec, dtype=numpy.uint8)
                    qImg = qimage2ndarray.array2qimage(magspec)
                    self.ui.lblImgFft.setPixmap(QPixmap.fromImage(qImg))
                    self.ui.lblImgFft.setAlignment(QtCore.Qt.AlignHCenter
                                                   | QtCore.Qt.AlignVCenter)

                try:
                    for r in range(numPix):
                        for c in range(128):
                            magspec[r + i, c] = 0
                            imgFftShift[r + i, c] = 0
                    for r in range(128 - numPix, 128):
                        for c in range(128):
                            magspec[128 - i - numPix - r, c] = 0
                            imgFftShift[128 - i - numPix - r, c] = 0
                    for r in range(128):
                        for c in range(numPix):
                            magspec[r, c + i] = 0
                            imgFftShift[r, c + i] = 0
                    for r in range(128):
                        for c in range(numPix):
                            magspec[r, 128 - i - numPix + c] = 0
                            imgFftShift[r, 128 - i - numPix + c] = 0
                    q1img = qimage2ndarray.array2qimage(magspec)
                    self.ui.lblImgFft.setPixmap(QPixmap.fromImage(q1img))

                    imgtry = numpy.fft.ifftshift(imgFftShift)
                    imgtry = numpy.fft.ifft2(imgtry)

                    #imagspec = numpy.asarray(imgtry, dtype=numpy.uint8)
                    q2img = qimage2ndarray.array2qimage(imgtry)
                    time.sleep(0.1)

                    self.ui.lblImg.setPixmap(QPixmap.fromImage(q2img))
                    self.ui.lblImg.setAlignment(QtCore.Qt.AlignHCenter
                                                | QtCore.Qt.AlignVCenter)
                except:
                    img = copy.deepcopy(myImage)
                    i = 0
                    self.ui.btnStart.setEnabled(True)
                    return
            except:
                self.ui.btnStart.setEnabled(True)
                return
        try:
            if myImage.all() == compareImg.all():
                self.theLastModification2()
            else:
                self.ui.btnStart.setEnabled(True)
                return
        except:
            self.ui.btnStart.setEnabled(True)
            return

    def theLastModification2(self, ):
        try:
            img = copy.deepcopy(myImage)
            compareImg = copy.deepcopy(myImage)
            numPix = int(self.ui.TextBoxPixel.toPlainText())
            if 64 % numPix != 0:
                QMessageBox.question(self, 'Error',
                                     "number of pixels must be factor of 64",
                                     QMessageBox.Ok)
        except NameError:
            self.ui.btnStart.setEnabled(True)
            self.ui.btnPause.setEnabled(False)
            self.ui.btnBrowse.setEnabled(True)
            return

        for i in range(0, 64, numPix):
            self.progressBarValue = 64 - i
            self.progressSignal.emit()

            try:
                numPix = int(self.ui.TextBoxPixel.toPlainText())
            except:
                self.ui.btnStart.setEnabled(True)
                self.ui.btnBrowse.setEnabled(True)
                return

            try:
                if i == 0:
                    imgFft = numpy.fft.fft2(img)
                    imgFftShift = numpy.fft.fftshift(imgFft)
                    with errstate(divide='ignore'):
                        magspec = 20 * numpy.log(numpy.abs(imgFftShift))
                    #magspec = numpy.asarray(magspec, dtype=numpy.uint8)

                    qImg = qimage2ndarray.array2qimage(magspec)
                    self.ui.lblImgFft.setPixmap(QPixmap.fromImage(qImg))
                    self.ui.lblImgFft.setAlignment(QtCore.Qt.AlignHCenter
                                                   | QtCore.Qt.AlignVCenter)

                try:
                    for r in range(i + numPix):
                        for c in range(i + numPix):
                            magspec[64 - r, 64 - c] = 0
                            imgFftShift[64 - r, 64 - c] = 0

                    for r in range(i + numPix):
                        for c in range(i + numPix):
                            magspec[64 + r, 64 + c] = 0
                            imgFftShift[64 + r, 64 + c] = 0

                    for r in range(i + numPix):
                        for c in range(i + numPix):
                            magspec[64 - r, 64 + c] = 0
                            imgFftShift[64 - r, 64 + c] = 0

                    for r in range(i + numPix):
                        for c in range(i + numPix):
                            magspec[64 + r, 64 - c] = 0
                            imgFftShift[64 + r, 64 - c] = 0

                    q1img = qimage2ndarray.array2qimage(magspec)
                    self.ui.lblImgFft.setPixmap(QPixmap.fromImage(q1img))

                    imgtry = numpy.fft.ifftshift(imgFftShift)
                    imgtry = numpy.fft.ifft2(imgtry)

                    #imagspec = numpy.asarray(imgtry, dtype=numpy.uint8)
                    q2img = qimage2ndarray.array2qimage(imgtry)

                    self.ui.lblImg.setPixmap(QPixmap.fromImage(q2img))
                    self.ui.lblImg.setAlignment(QtCore.Qt.AlignHCenter
                                                | QtCore.Qt.AlignVCenter)

                    time.sleep(0.1)

                except:
                    img = copy.deepcopy(myImage)
                    i = 0
                    self.ui.btnStart.setEnabled(True)
                    return
            except:
                self.ui.btnStart.setEnabled(True)
                return
        try:
            if myImage.all() == compareImg.all():
                self.theLastModification()
            else:
                self.ui.btnStart.setEnabled(True)
                return
        except:
            self.ui.btnStart.setEnabled(True)
            return

    def btnStart_clicked(self):
        global numPix
        try:
            numPix = int(self.ui.TextBoxPixel.toPlainText())
        except:
            QMessageBox.question(self, 'Error',
                                 "Please enter number of pixels")
        if 64 % numPix != 0:
            QMessageBox.question(self, 'Error',
                                 "number of pixels must be factor of 64",
                                 QMessageBox.Ok)
            self.ui.btnStart.setEnabled(True)
            return

        try:

            self.ui.btnPause.setEnabled(True)
            self.ui.btnStart.setEnabled(False)
            self.ui.TextBoxPixel.setEnabled(False)
            numPix = int(self.ui.TextBoxPixel.toPlainText())
            global t1
            t1 = threading.Thread(target=self.theLastModification)
            t1.start()
        except IndexError:
            QMessageBox.question(
                self, 'Error',
                "Index error ! please reduce number of pixels or change the photo",
                QMessageBox.Ok)
        except NameError:
            QMessageBox.question(self, 'Error',
                                 "Please insert the photo frist",
                                 QMessageBox.Ok)
        except:
            QMessageBox.question(self, 'Error',
                                 "Please!! enter a proper integer",
                                 QMessageBox.Ok)
            self.ui.btnPause.setEnabled(False)
            self.ui.btnStart.setEnabled(True)
            self.ui.TextBoxPixel.setEnabled(True)
            self.ui.btnBrowse.setEnabled(True)

    def btnPause_clicked(self):
        try:
            timeToWait = float(self.ui.timeText.toPlainText())
            self.ui.btnPause.setEnabled(False)
            self.ui.TextBoxPixel.setEnabled(True)
            self.ui.btnBrowse.setEnabled(True)
        except:
            timeToWait = 0
            self.ui.btnPause.setEnabled(False)
            self.ui.TextBoxPixel.setEnabled(True)
            self.ui.btnBrowse.setEnabled(True)
            return
        time.sleep(timeToWait)
        return

    progressSignal = pyqtSignal()

    @pyqtSlot()
    def progressBar(self):
        self.ui.progressBar.setValue(self.progressBarValue)
示例#8
0
 def __init__(self, parent=None):
     super(MyMainWindow, self).__init__(parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
示例#9
0
class MyMainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

    def do_something(self):
        print "I'm doing something!"

    def accept(self):
        """save the path var and exit"""

        items = []
        for i in xrange(self.ui.pathList.count()):
            items.append(self.ui.pathList.item(i).text())
        print items

        box = QMessageBox()
        box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        box.setText("Are you sure you want to save?")
        ret = box.exec_()

        if ret == QMessageBox.Yes:
            envars.set_path(items)
            envars.broadcast_change()
            QtGui.QApplication.exit()


    def reject(self):
        """exit the applicaiton if the user is sure"""

        box = QMessageBox()
        box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        box.setText("Are you sure you want to exist?")
        ret = box.exec_()

        if ret == QMessageBox.Yes:
            QtGui.QApplication.exit()

    def itemclick(self):
        currentItemText = self.ui.pathList.currentItem().text()
        self.ui.lineEdit.setText(currentItemText)

    def additem(self):
        print "Add item"
        myapp.ui.pathList.addItem("New Entry")

    def removeitem(self):
        """delete the item at the current row"""

        print "Remove Item" 
        currentRow = self.ui.pathList.currentRow()
        self.ui.pathList.takeItem(currentRow)

    def saveitem(self):
        print "Save Item"
        self.ui.pathList.currentItem().setText(self.ui.lineEdit.text())

    def moveup(self):
        # swap the current item's text with the item above it
        currentRow = self.ui.pathList.currentRow()
        if currentRow <= 0:
            return
        
        tempItem = self.ui.pathList.item(currentRow).text()
        self.ui.pathList.item(currentRow).setText(self.ui.pathList.item(currentRow - 1).text())
        self.ui.pathList.item(currentRow - 1).setText(tempItem)
        self.ui.pathList.setCurrentRow(currentRow - 1)
        
        print "Moved up"
    
    
    def movedown(self):
        # swap the current item's text with the item below it
        currentRow = self.ui.pathList.currentRow()
        if currentRow >= self.ui.pathList.count() - 1:
            return
        
        tempItem = self.ui.pathList.item(currentRow).text()
        self.ui.pathList.item(currentRow).setText(self.ui.pathList.item(currentRow + 1).text())
        self.ui.pathList.item(currentRow + 1).setText(tempItem)
        self.ui.pathList.setCurrentRow(currentRow + 1)
        
        print "Moved down"
示例#10
0
文件: main.py 项目: GaboGomezT/sali
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        title = "Sali"
        self.setWindowTitle(title)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.openFileDialog)

        self.show()

    def openFileDialog(self):
        #fname = QFileDialog.getOpenFileName(self, 'Open file', '/home', 'Text files (*.txt)')
        dirname = QFileDialog.getExistingDirectory(None, 'Select a folder:',
                                                   'C:\\',
                                                   QFileDialog.ShowDirsOnly)
        print(dirname)
        if dirname:
            self.showAnalitics(dirname + '/')
            #self.showGraphic(fname[0])

    def showGraphic(self, fname):
        filename = fname
        df = pd.read_csv(filename,
                         header=None,
                         error_bad_lines=False,
                         encoding='utf8')
        df = df.drop(0)
        df.columns = ['Date', 'Chat']
        Message = df['Chat'].str.split('-', n=1, expand=True)
        df['Date'] = df['Date'].str.replace(',', '')
        df['Time'] = Message[0]
        df['content'] = Message[1]
        Message1 = df['content'].str.split(':', n=1, expand=True)
        df['content'] = Message1[1]
        df['sender_name'] = Message1[0]
        df = df.drop(columns=['Chat'])
        df['content'] = df['content'].str.lower()
        df['content'] = df['content'].str.replace('<media omitted>',
                                                  'MediaShared')
        df['content'] = df['content'].str.replace('this message was deleted',
                                                  'DeletedMsg')
        df.dropna(inplace=True)
        df["date_time"] = pd.to_datetime(df.Date + df.Time)
        df = df.reindex(columns=['date_time', 'sender_name', 'content'])
        df["delta_mensajes_minutos"] = df.date_time.diff()[:].astype(
            'timedelta64[m]')
        df["delta_mensajes_horas"] = df.date_time.diff()[:].astype(
            'timedelta64[h]')
        df = df.set_index("date_time")

        y = df.sender_name.groupby(df.index.hour).count()

        fig = plt.figure()
        ax = plt.axes()
        plt.title("Frecuencia de mensajes x hora del día")
        plt.xlabel("horas")
        plt.ylabel("cantidad de mensajes")
        ax.plot(y.index, y)

        plt.show()

    def parse_chat(self, chat_path):
        filename = chat_path
        df = pd.read_csv(filename,
                         header=None,
                         error_bad_lines=False,
                         encoding='utf8')
        df = df.drop(0)
        df.columns = ['Date', 'Chat']
        Message = df['Chat'].str.split('-', n=1, expand=True)
        df['Date'] = df['Date'].str.replace(',', '')
        df['Time'] = Message[0]
        df['content'] = Message[1]
        Message1 = df['content'].str.split(':', n=1, expand=True)
        df['content'] = Message1[1]
        df['sender_name'] = Message1[0]
        df = df.drop(columns=['Chat'])
        df['content'] = df['content'].str.lower()
        df['content'] = df['content'].str.replace('<media omitted>',
                                                  'MediaShared')
        df['content'] = df['content'].str.replace('this message was deleted',
                                                  'DeletedMsg')
        df.dropna(inplace=True)
        df["date_time"] = pd.to_datetime(df.Date + df.Time)
        df = df.reindex(columns=['date_time', 'sender_name', 'content'])
        df["delta_mensajes_minutos"] = df.date_time.diff()[:].astype(
            'timedelta64[m]')
        df["delta_mensajes_horas"] = df.date_time.diff()[:].astype(
            'timedelta64[h]')
        df = df.set_index("date_time")
        return df

    def showAnalitics(self, dir_chats):
        chats = listdir(dir_chats)

        chat_dfs = []
        for conversation in chats:
            sender_name = conversation[21:]
            conv = self.parse_chat(dir_chats + conversation)
            chat_dfs.append(conv)

        all_chats = pd.concat(chat_dfs)
        name_filter = all_chats["sender_name"].str.strip() != 'A n e m o n e'
        client_messages = all_chats[name_filter]

        y = client_messages.sender_name.groupby(
            client_messages.index.hour).count()

        # Horarios con más chats
        horarios = y.sort_values(ascending=False)[:3].index
        mensaje_horarios = f"Sus horarios en donde recibe más mensajes son a las {horarios[0]}hrs, las {horarios[1]}hrs y las {horarios[2]}hrs."

        # ¿Quienes son los clientes más activos?
        client_most_messages = client_messages.groupby(
            client_messages.sender_name).count().sort_values(
                "content", ascending=False)[:3].index
        most_active_client_message = f"Sus top tres clientes más activos son 1.{client_most_messages[0]}, 2.{client_most_messages[1]}, y 3.{client_most_messages[2]}"

        # ¿Cuál es el tiempo promedio que tardamos en responder?
        pyme_filter = all_chats["sender_name"].str.strip() == 'A n e m o n e'
        pyme_messages = all_chats[pyme_filter]
        mean_response = pyme_messages.delta_mensajes_minutos.mean()
        mensaje_respuesta_promedio = f"Usted se tarda en promedio {int(mean_response)} minutos en responder a sus clientes."

        # Tiempo promedio de respuesta de clientes
        mean_client_response = client_messages.delta_mensajes_horas.mean()
        mensaje_respuesta_promedio_cliente = f"Sus clientes se tardan en promedio {int(mean_client_response)} horas en responderle."

        # # Palabras más usadas por Pyme
        # spanish_stopwords = stopwords.words('spanish')
        # words = " ".join(pyme_messages["content"]).split()
        # filtered_words = [word for word in words if word not in spanish_stopwords]
        # pyme_top_20_palabras = list(Counter(filtered_words).most_common(20))

        # # Palabras más usadas por Clientes
        # spanish_stopwords = stopwords.words('spanish')
        # words = " ".join(client_messages["content"]).split()
        # filtered_words = [word for word in words if word not in spanish_stopwords]
        # clientes_top_20_palabras = list(Counter(filtered_words).most_common(20))

        self.ui.lblInfo1.setText("Horarios con más chats")
        self.ui.lbl1.setText(mensaje_horarios)
        self.ui.lblInfo2.setText("¿Quienes son los clientes más activos?")
        self.ui.lbl2.setText(most_active_client_message)
        self.ui.lblInfo3.setText(
            "¿Cuál es el tiempo promedio que tardamos en responder?")
        self.ui.lbl3.setText(mensaje_respuesta_promedio)
        self.ui.lblInfo4.setText("Tiempo promedio de respuesta de clientes")
        self.ui.lbl4.setText(mensaje_respuesta_promedio_cliente)