Ejemplo n.º 1
0
class PrintText(PBDialog):
    """Create a window for printing text of command line output"""

    stopped = Signal()
    pbMax = Signal(float)
    pbVal = Signal(float)

    def __init__(self,
                 parent=None,
                 title="",
                 progressBar=True,
                 noStopButton=False,
                 message=None):
        """Constructor.
        Set some properties and create the GUI of the dialog

        Parameters:
            parent: the parent widget
            title: the window title. If an empty string,
                "Redirect print" will be used
            progressBar: True (default) if the widget must have a progress bar
            noStopButton (default False): True if the widget must have
                a "stop" button to stop the iterations
            message: a text to be inserted as a `PBLabel` in the dialog
        """
        super(PrintText, self).__init__(parent)
        self._wantToClose = False
        self.grid = None
        self.progressBar = None
        self.textEdit = None
        self.closeButton = None
        self.cancelButton = None
        if title != "":
            self.title = title
        else:
            self.title = dwstr.redirectPrint
        self.setProgressBar = progressBar
        self.noStopButton = noStopButton
        self.message = message
        self.pbMax.connect(self.progressBarMax)
        self.pbVal.connect(self.progressBarValue)
        self.initUI()

    def keyPressEvent(self, e):
        """Intercept press keys and only exit if escape is pressed
        when closing is enabled

        Parameters:
            e: the `PySide2.QtGui.QKeyEvent`
        """
        if e.key() == Qt.Key_Escape and self._wantToClose:
            self.close()

    def closeEvent(self, event):
        """Manage the `closeEvent` of the dialog.
        Reject unless `self._wantToClose` is True

        Parameter:
            event: a `QEvent`
        """
        if self._wantToClose:
            super(PrintText, self).closeEvent(event)
        else:
            event.ignore()

    def initUI(self):
        """Create the main `QTextEdit`, the buttons and the `QProgressBar`"""
        self.setWindowTitle(self.title)

        grid = QGridLayout()
        self.grid = grid
        grid.setSpacing(1)

        if self.message is not None and self.message.strip() != "":
            grid.addWidget(PBLabel("%s" % self.message))

        self.textEdit = QTextEdit()
        grid.addWidget(self.textEdit)

        if self.setProgressBar:
            self.progressBar = QProgressBar(self)
            grid.addWidget(self.progressBar)

        # cancel button...should learn how to connect it with a thread kill
        if not self.noStopButton:
            self.cancelButton = QPushButton(dwstr.stop, self)
            self.cancelButton.clicked.connect(self.stopExec)
            self.cancelButton.setAutoDefault(True)
            grid.addWidget(self.cancelButton)
        self.closeButton = QPushButton(dwstr.close, self)
        self.closeButton.setDisabled(True)
        grid.addWidget(self.closeButton)

        self.setGeometry(100, 100, 600, 600)
        self.setLayout(grid)
        self.centerWindow()

    def appendText(self, text):
        """Add the given text to the end of the `self.textEdit` content.

        Parameter:
            text: the string to be appended
        """
        self.textEdit.moveCursor(QTextCursor.End)
        self.textEdit.insertPlainText(text)

    def progressBarMin(self, minimum):
        """Set the minimum value for the progress bar

        Parameter:
            minimum (int or float): the value
        """
        if self.setProgressBar:
            self.progressBar.setMinimum(minimum)

    def progressBarMax(self, maximum):
        """Set the maximum value for the progress bar

        Parameter:
            maximum (int or float): the value
        """
        if self.setProgressBar:
            self.progressBar.setMaximum(maximum)

    def progressBarValue(self, value):
        """Set the current value for the progress bar

        Parameter:
            value (int or float): the value
        """
        if self.setProgressBar:
            self.progressBar.setValue(value)

    def stopExec(self):
        """Stop the iterations through the `stopped` Signal
        and disable the `cancelButton`
        """
        self.cancelButton.setDisabled(True)
        self.stopped.emit()

    def enableClose(self):
        """Enable the close button and set `self._wantToClose` to True"""
        self._wantToClose = True
        self.closeButton.setEnabled(True)
        try:
            self.cancelButton.setEnabled(False)
        except Exception:
            pass
Ejemplo n.º 2
0
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle(
            "Automation.... WITH KITTENS!!!! AHHH I LOVE KITTENS")
        # Create Widgets
        self.fileLoader = QPushButton("Load Files")
        self.stopButton = QPushButton("Stop")
        self.fileBox = QComboBox()  # Holds name of files
        self.filePreview = QTextBrowser()  # Preview Files
        self.loadingBar = QProgressBar(self)
        self.preview = QTextBrowser()
        self.ConfirmButton = QPushButton("Start")
        # Variable Creation Area
        self.pictureDic = {}  # Holds the tings
        self.timerBool = bool
        # Create layout and add widgets
        layout = QVBoxLayout()
        # Design Area
        self.label2 = QLabel()
        self.label2.setText("Automating Kittens!")
        self.label2.setStyleSheet(
            "QLabel { background-color : black; color : white; font-size: 20px; text-align : "
            "center; }")
        self.label = QLabel()
        pixmap = QPixmap('pictures/helloKitten.png')
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.timer = QBasicTimer()
        self.step = 0
        self.label.setPixmap(pixmap)

        # Adding widgets to the layout
        layout.addWidget(self.label2)
        layout.addWidget(self.label)
        layout.addWidget(self.fileLoader)
        layout.addWidget(self.fileBox)
        layout.addWidget(self.filePreview)
        layout.addWidget(self.ConfirmButton)
        layout.addWidget(self.stopButton)
        self.loadingBar.setStyleSheet(
            "QProgressBar::chunk {background-color: red}")
        layout.addWidget(self.loadingBar)
        # Enable Minimize and maximize
        self.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
        self.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
        # Set layout
        self.setLayout(layout)
        p = self.palette()
        p.setColor(self.foregroundRole(), QColor(10, 10, 10, 127))
        p.setColor(self.backgroundRole(), QColor(0, 0, 127, 127))
        self.setPalette(p)
        self.setFixedWidth(450)
        self.setFixedHeight(700)
        # Connecting functions to buttons
        self.fileLoader.clicked.connect(self.loadFiles)
        self.ConfirmButton.clicked.connect(self.newStart)
        self.stopButton.clicked.connect(self.stop)
        self.fileBox.activated.connect(self.updatePreview)
    def __init__(self):
        super(IpSubnetCalculation, self).__init__()

        # Use language settings
        self.ml = ManageLng()

        # App attributes
        self.network_ip = None
        self.needed_networks = None
        self.subnet_bits = None
        self.default_networkbits = None
        self.calculation_worker = None

        main_layout = QVBoxLayout()
        main_layout.setSpacing(10)
        main_layout.setAlignment(Qt.AlignTop)
        self.setLayout(main_layout)

        top_bar = QGridLayout()

        # Left, top, right and bottom margins
        top_bar.setContentsMargins(40, 15, 40, 15)
        top_bar.setHorizontalSpacing(40)
        main_layout.addLayout(top_bar)

        self.starting_network_address_label = QLabel(self.ml.get_tr_text("tab_ipsubnet_starting_net"))
        self.number_of_subnets_label = QLabel(self.ml.get_tr_text("tab_ipsubnet_required_subnet_num"))

        self.starting_network_address_input = QLineEdit()
        self.starting_network_address_input.returnPressed.connect(self.calculation_action)
        self.number_of_subnets_input = QLineEdit()
        self.number_of_subnets_input.returnPressed.connect(self.calculation_action)

        top_bar.addWidget(self.starting_network_address_label, 0, 0)
        top_bar.addWidget(self.starting_network_address_input, 0, 1)
        top_bar.addWidget(self.number_of_subnets_label, 1, 0)
        top_bar.addWidget(self.number_of_subnets_input, 1, 1)

        self.calculation_button = QPushButton(self.ml.get_tr_text("tab_ipsubnet_calc_btn"))
        self.calculation_button.clicked.connect(self.calculation_action)
        self.calculation_button.setIcon(QIcon("static/images/get_info.png"))
        main_layout.addWidget(self.calculation_button, alignment=Qt.AlignCenter)

        self.table = QTableWidget()
        self.table.itemDoubleClicked.connect(copy_text_action)
        self.table.setColumnCount(6)

        self.table_column_names = [self.ml.get_tr_text("table_column_network_add"),
                                   self.ml.get_tr_text("table_column_ip_range"),
                                   self.ml.get_tr_text("table_column_broadcast_add"),
                                   self.ml.get_tr_text("table_column_subnet_mask"),
                                   self.ml.get_tr_text("table_column_prefix"),
                                   self.ml.get_tr_text("table_column_addressable_host")]

        self.table.setHorizontalHeaderLabels(self.table_column_names)

        # Automatic resizing of the columns to the content
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)

        # Set table text align of vertical header
        self.table.verticalHeader().setDefaultAlignment(Qt.AlignCenter)

        # Fixed height of table rows
        self.table.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)

        main_layout.addWidget(self.table)

        # Bottom bar
        bottom_bar = QHBoxLayout()

        # Create progressbar
        self.progressbar = QProgressBar()
        self.progressbar.setVisible(False)

        # Create cancel button
        self.cancel_btn = QPushButton(self.ml.get_tr_text("tab_ipsubnet_cancel_btn"))
        self.cancel_btn.setVisible(False)
        self.cancel_btn.clicked.connect(self.terminate_calculation)

        bottom_bar.addWidget(self.progressbar)
        bottom_bar.addWidget(self.cancel_btn)
        main_layout.addLayout(bottom_bar)
Ejemplo n.º 4
0
    def setupUi(self, MainWindow):
        if not MainWindow.objectName():
            MainWindow.setObjectName(u"MainWindow")
        MainWindow.resize(1024, 768)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(u"centralwidget")
        self.verticalLayoutWidget_2 = QWidget(self.centralwidget)
        self.verticalLayoutWidget_2.setObjectName(u"verticalLayoutWidget_2")
        self.verticalLayoutWidget_2.setGeometry(QRect(0, 0, 1021, 511))
        self.pictureLayout = QVBoxLayout(self.verticalLayoutWidget_2)
        self.pictureLayout.setObjectName(u"pictureLayout")
        self.pictureLayout.setContentsMargins(0, 0, 0, 0)
        self.picture_label = QLabel(self.verticalLayoutWidget_2)
        self.picture_label.setObjectName(u"picture_label")

        self.pictureLayout.addWidget(self.picture_label)

        self.picture_button = QPushButton(self.verticalLayoutWidget_2)
        self.picture_button.setObjectName(u"picture_button")

        self.pictureLayout.addWidget(self.picture_button)

        self.horizontalLayoutWidget = QWidget(self.centralwidget)
        self.horizontalLayoutWidget.setObjectName(u"horizontalLayoutWidget")
        self.horizontalLayoutWidget.setGeometry(QRect(10, 520, 1011, 120))
        self.horizontalLayout_2 = QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName(u"verticalLayout_3")
        self.label_2 = QLabel(self.horizontalLayoutWidget)
        self.label_2.setObjectName(u"label_2")

        self.verticalLayout_3.addWidget(self.label_2)

        self.DCT_encode = QPushButton(self.horizontalLayoutWidget)
        self.DCT_encode.setObjectName(u"DCT_encode")

        self.verticalLayout_3.addWidget(self.DCT_encode)

        self.DCT_decode = QPushButton(self.horizontalLayoutWidget)
        self.DCT_decode.setObjectName(u"DCT_decode")

        self.verticalLayout_3.addWidget(self.DCT_decode)

        self.label_4 = QLabel(self.horizontalLayoutWidget)
        self.label_4.setObjectName(u"label_4")

        self.verticalLayout_3.addWidget(self.label_4)

        self.DCT_masg = QLineEdit(self.horizontalLayoutWidget)
        self.DCT_masg.setObjectName(u"DCT_masg")

        self.verticalLayout_3.addWidget(self.DCT_masg)

        self.horizontalLayout_2.addLayout(self.verticalLayout_3)

        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.label_3 = QLabel(self.horizontalLayoutWidget)
        self.label_3.setObjectName(u"label_3")

        self.verticalLayout.addWidget(self.label_3)

        self.LSB_encode = QPushButton(self.horizontalLayoutWidget)
        self.LSB_encode.setObjectName(u"LSB_encode")

        self.verticalLayout.addWidget(self.LSB_encode)

        self.LSB_decode = QPushButton(self.horizontalLayoutWidget)
        self.LSB_decode.setObjectName(u"LSB_decode")

        self.verticalLayout.addWidget(self.LSB_decode)

        self.lsb_encode_msg = QLabel(self.horizontalLayoutWidget)
        self.lsb_encode_msg.setObjectName(u"lsb_encode_msg")

        self.verticalLayout.addWidget(self.lsb_encode_msg)

        self.LSB_msg = QLineEdit(self.horizontalLayoutWidget)
        self.LSB_msg.setObjectName(u"LSB_msg")

        self.verticalLayout.addWidget(self.LSB_msg)

        self.horizontalLayout_2.addLayout(self.verticalLayout)

        self.verticalLayoutWidget_3 = QWidget(self.centralwidget)
        self.verticalLayoutWidget_3.setObjectName(u"verticalLayoutWidget_3")
        self.verticalLayoutWidget_3.setGeometry(QRect(20, 650, 981, 51))
        self.verticalLayout_2 = QVBoxLayout(self.verticalLayoutWidget_3)
        self.verticalLayout_2.setObjectName(u"verticalLayout_2")
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.label_6 = QLabel(self.verticalLayoutWidget_3)
        self.label_6.setObjectName(u"label_6")

        self.verticalLayout_2.addWidget(self.label_6)

        self.progressBar = QProgressBar(self.verticalLayoutWidget_3)
        self.progressBar.setObjectName(u"progressBar")
        self.progressBar.setValue(0)

        self.verticalLayout_2.addWidget(self.progressBar)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setObjectName(u"menubar")
        self.menubar.setGeometry(QRect(0, 0, 1024, 21))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName(u"statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        # bind functions
        self.picture_button.clicked.connect(self.open_file)
        self.LSB_encode.clicked.connect(self.call_lsb_encode)
        self.LSB_decode.clicked.connect(self.call_lsb_decode)
        self.DCT_encode.clicked.connect(self.call_dct_encode)
        self.DCT_decode.clicked.connect(self.call_dct_decode)
        # end bind functions()
        self.hide_progress_bar()
        self.disable_Methods(True)

        QMetaObject.connectSlotsByName(MainWindow)
Ejemplo n.º 5
0
class MainWindow(QMainWindow):
    """
    The main window of angr management.
    """
    def __init__(self, file_to_open=None, parent=None):
        super(MainWindow, self).__init__(parent)

        icon_location = os.path.join(IMG_LOCATION, 'angr.png')
        self.setWindowIcon(QIcon(icon_location))

        GlobalInfo.main_window = self

        # initialization
        self.caption = "angr Management"
        self.setMinimumSize(QSize(400, 400))
        self.setDockNestingEnabled(True)

        self.workspace = None
        self.central_widget = None

        self._file_toolbar = None  # type: FileToolbar
        self._states_toolbar = None  # type: StatesToolbar
        self._analysis_toolbar = None  # type: AnalysisToolbar
        self._progressbar = None  # type: QProgressBar
        self._load_binary_dialog = None

        self._status = ""
        self._progress = None

        self._init_menus()
        self._init_toolbars()
        self._init_statusbar()
        self._init_workspace()

        self.showMaximized()

        # I'm ready to show off!
        self.show()

        self.status = "Ready."

        if file_to_open is not None:
            # load a binary
            self._open_loadbinary_dialog(file_to_open)

    #
    # Properties
    #

    @property
    def caption(self):
        return self.getWindowTitle()

    @caption.setter
    def caption(self, v):
        self.setWindowTitle(v)

    @property
    def status(self):
        return self._status

    @status.setter
    def status(self, v):
        self._status = v

        self.statusBar().showMessage(v)

    @property
    def progress(self):
        return self._progress

    @progress.setter
    def progress(self, v):
        self._progress = v
        self._progressbar.show()
        self._progressbar.setValue(v)

    #
    # Dialogs
    #

    def _open_loadbinary_dialog(self, file_to_open):
        try:
            self._load_binary_dialog = LoadBinary(file_to_open)
            self._load_binary_dialog.setModal(True)
            self._load_binary_dialog.exec_()

            if self._load_binary_dialog.cfg_args is not None:
                # load the binary
                self._load_binary(
                    file_to_open,
                    load_options=self._load_binary_dialog.load_options,
                    cfg_args=self._load_binary_dialog.cfg_args)
        except LoadBinaryError:
            pass

    def open_newstate_dialog(self):
        new_state_dialog = NewState(self.workspace, parent=self)
        new_state_dialog.exec_()

    #
    # Widgets
    #

    def _init_statusbar(self):

        self._progressbar = QProgressBar()

        self._progressbar.setMinimum(0)
        self._progressbar.setMaximum(100)
        self._progressbar.hide()

        self.statusBar().addPermanentWidget(self._progressbar)

    def _init_toolbars(self):

        self._file_toolbar = FileToolbar(self)
        self._states_toolbar = StatesToolbar(self)
        self._analysis_toolbar = AnalysisToolbar(self)

        self.addToolBar(Qt.TopToolBarArea, self._file_toolbar.qtoolbar())
        self.addToolBar(Qt.TopToolBarArea, self._states_toolbar.qtoolbar())
        self.addToolBar(Qt.TopToolBarArea, self._analysis_toolbar.qtoolbar())

    #
    # Menus
    #

    def _init_menus(self):
        fileMenu = FileMenu(self)
        self.menuBar().addMenu(fileMenu.qmenu())

    #
    # Workspace
    #

    def _init_workspace(self):
        self.central_widget = QMainWindow()
        self.setCentralWidget(self.central_widget)

        wk = Workspace(self, Instance())
        self.workspace = wk

        right_dockable_views = [
            dock for dock in self.workspace.dockable_views
            if dock.widget().default_docking_position == 'right'
        ]

        for d0, d1 in zip(right_dockable_views, right_dockable_views[1:]):
            self.central_widget.tabifyDockWidget(d0, d1)
        right_dockable_views[0].raise_()

        self.central_widget.setTabPosition(Qt.RightDockWidgetArea,
                                           QTabWidget.North)

    #
    # Event
    #

    def resizeEvent(self, event):
        """

        :param QResizeEvent event:
        :return:
        """

        pass
        # self._recalculate_view_sizes(event.oldSize())

    def event(self, event):

        if event.type() == QEvent.User:
            # our event callback

            try:
                event.result = event.execute()
            except Exception as e:
                event.exception = e
            event.event.set()

            return True

        return super(MainWindow, self).event(event)

    #
    # Actions
    #

    def reload(self):
        self.workspace.reload()

    def load_binary(self):

        # Open File window
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "Open a binary",
            ".",
            "All executables (*);;Windows PE files (*.exe);;Core Dumps (*.core)",
        )

        if os.path.isfile(file_path):
            self._open_loadbinary_dialog(file_path)

    def quit(self):
        self.close()

    def run_variable_recovery(self):
        self.workspace.views_by_category['disassembly'][
            0].variable_recovery_flavor = 'accurate'

    def run_induction_variable_analysis(self):
        self.workspace.views_by_category['disassembly'][
            0].run_induction_variable_analysis()

    #
    # Other public methods
    #

    def progress_done(self):
        self._progress = None
        self._progressbar.hide()

    #
    # Private methods
    #

    def _load_binary(self, file_path, load_options=None, cfg_args=None):
        if load_options is None:
            load_options = {}

        if cfg_args is None:
            cfg_args = {}

        proj = angr.Project(file_path, load_options=load_options)
        self.workspace.instance.set_project(proj)
        self.workspace.instance.initialize(cfg_args=cfg_args)

    def _recalculate_view_sizes(self, old_size):
        adjustable_dockable_views = [
            dock for dock in self.workspace.dockable_views
            if dock.widget().default_docking_position in ('left', 'bottom',
                                                          'right')
        ]

        if not adjustable_dockable_views:
            return

        for dock in adjustable_dockable_views:
            widget = dock.widget()

            if old_size.width() < 0:
                dock.old_size = widget.sizeHint()
                continue

            if old_size != self.size():
                # calculate the width ratio

                if widget.default_docking_position == 'left':
                    # we want to adjust the width
                    ratio = dock.old_size.width() * 1.0 / old_size.width()
                    new_width = int(self.width() * ratio)
                    self._resize_dock_widget(dock, new_width, widget.height())
                elif widget.default_docking_position == 'bottom':
                    # we want to adjust the height
                    ratio = dock.old_size.height() * 1.0 / old_size.height()
                    new_height = int(self.height() * ratio)
                    self._resize_dock_widget(dock, widget.width(), new_height)

                dock.old_size = widget.size()

    def _resize_dock_widget(self, dock_widget, new_width, new_height):

        original_size = dock_widget.size()
        original_min = dock_widget.minimumSize()
        original_max = dock_widget.maximumSize()

        dock_widget.resize(new_width, new_height)

        if new_width != original_size.width():
            if original_size.width() > new_width:
                dock_widget.setMaximumWidth(new_width)
            else:
                dock_widget.setMinimumWidth(new_width)

        if new_height != original_size.height():
            if original_size.height() > new_height:
                dock_widget.setMaximumHeight(new_height)
            else:
                dock_widget.setMinimumHeight(new_height)

        dock_widget.original_min = original_min
        dock_widget.original_max = original_max

        QTimer.singleShot(1, dock_widget.restore_original_size)
Ejemplo n.º 6
0
    def __init__(self):
        QWidget.__init__(self)

        self.driveLabel = QLabel('Serial Number:')
        self.sizeLabel = QLabel('Size:')
        self.statusLabel = QLabel('Status:')
        self.partitionLabel = QLabel('Partitions:')
        self.indexLabel = QLabel('Index:')
        self.checkLabel = QLabel('Master:')
        self.progress = QProgressBar()
        self.wipeButton = QPushButton('Wipe')
        self.cancelButton = QPushButton('Cancel')
        self.bottomStatus = QLabel('Ready to Wipe')
        self.refactor = QPushButton('Refactor')

        # TODO: Add a group box to make this look better
        # EDIT TODO: Use GUI application to build a really good looking app!
        # TODO: Add selection of wipe method, verification, and certificate output

        self.layout = QGridLayout()

        self.layout.addWidget(self.driveLabel, 0, 0, 1, 2)
        self.layout.addWidget(self.sizeLabel, 0, 3)
        self.layout.addWidget(self.statusLabel, 0, 5, 1, 2)
        self.layout.addWidget(self.partitionLabel, 0, 7)
        self.layout.addWidget(self.indexLabel, 0, 8)
        self.layout.addWidget(self.checkLabel, 0, 9)
        self.layout.addWidget(self.progress, 26, 0, 1, 10)
        self.layout.addWidget(self.wipeButton, 27, 2, 1, 2)
        self.layout.addWidget(self.cancelButton, 27, 4, 1, 2)
        self.layout.addWidget(self.bottomStatus, 28, 0, 1, 10)
        self.layout.addWidget(self.refactor, 27, 0, 1, 2)
        self.drivesSet = 0
        self.driveNames = []
        self.driveStatus = []
        self.driveSize = []
        self.drivePartitions = []
        self.driveIndex = []
        self.masterRadio = []
        self.master = self.getMaster()
        self.progressInt = 10
        for i in range(25):
            toAdd = QLabel('')
            self.driveNames.append(toAdd)
            toAdd2 = QLabel('')
            self.driveSize.append(toAdd2)
            toAdd3 = QLabel('')
            self.driveStatus.append(toAdd3)
            toAdd4 = QLabel('')
            self.drivePartitions.append(toAdd4)
            toAdd5 = QLabel('')
            self.driveIndex.append(toAdd5)

        self.setWindowTitle('Auto Kill Disk')
        #icon =
        #self.setWindowIcon()
        self.wipeButton.clicked.connect(self.startButtonClicked)
        self.refactor.clicked.connect(self.refactorDrives)

        self.worker = refactorThread()
        self.worker.refSig.connect(self.refactorDrives)
        self.worker.start()
Ejemplo n.º 7
0
    def Add_Download(self):
        self.add_download_dialog = QDialog()

        self.add_download_dialog.setWindowTitle("Add_Download")
        # self.setWindowIcon(QIcon("logo.png"))
        self.init_themes_add_dialog()
        self.add_download_dialog.setFixedSize(325, 275)
        self.add_download_dialog.setMinimumSize(325, 240)

        self.isim = QLabel("İndir", self.add_download_dialog)
        self.isim.setFont(QFont("Hack Nerd Font", 15))
        self.isim.setGeometry(124, 13, 125, 34)

        # İlerleme/Progress
        # self.progressBar =

        # URL KUTUSU
        self.urlbox = QLineEdit("", self.add_download_dialog)
        # self.urlbox.setFixedSize(100,4)
        self.urlbox.setGeometry(35, 60, 250, 34)
        self.urlbox.setPlaceholderText("URL Gir")
        self.urlbox.setFont(QFont("Hack Nerd Font", 11))

        # INDIRME KONUMU
        self.downdirectory = QLineEdit(str(Path.home()),
                                       self.add_download_dialog)
        self.downdirectory.setGeometry(35, 100, 210, 34)
        self.downdirectory.setPlaceholderText("İndirilecek Konum")
        self.downdirectory.setFont(QFont("Hack Nerd Font", 11))

        # Dosya İsmi
        self.enterfilename = QLineEdit("", self.add_download_dialog)
        # self.filename.setFixedSize(100,4)
        self.enterfilename.setGeometry(35, 140, 210, 34)
        self.enterfilename.setPlaceholderText("Dosya İsmi(Opsiyonel)")
        self.enterfilename.setFont(QFont("Hack Nerd Font", 11))

        def connectfilename():
            fnameloop = asyncio.get_event_loop()
            fnameloop.run_until_complete(self.detect_fname())

        self.connectfilename = QPushButton(".", self.add_download_dialog)
        self.connectfilename.setGeometry(249, 140, 36, 34)
        self.connectfilename.setFont(QFont("Hack Nerd Font", 11))
        self.connectfilename.clicked.connect(connectfilename)

        # KONUM SEÇ BUTONU
        def download_dir():
            if self.sel_lang == "tr":
                try:
                    self.dirselectdialog = QFileDialog.getExistingDirectory(
                        self.add_download_dialog, 'İndirilecek Konumu Seç')
                except Exception as e:
                    print(e)
            elif self.sel_lang == "en":
                try:
                    self.dirselectdialog = QFileDialog.getExistingDirectory(
                        self.add_download_dialog, 'Select Dir')
                except Exception as e:
                    print(e)
            if self.dirselectdialog == "":
                self.downdirectory.setText(str(Path.home()))
            else:
                self.downdirectory.setText(str(self.dirselectdialog))

        self.selectdirbutton = QPushButton("...", self.add_download_dialog)
        self.selectdirbutton.setGeometry(249, 100, 36, 34)
        self.selectdirbutton.setFont(QFont("Hack Nerd Font", 11))
        self.selectdirbutton.clicked.connect(download_dir)

        # ProgressBar/İlerleme
        self.progressbar = QProgressBar(self.add_download_dialog)
        self.progressbar.setGeometry(35, 180, 250, 34)
        self.progressbar.setValue(0)

        # self.progressbar.hide()

        # INDIR BUTONU

        def start_downloading_process():
            url = str(self.urlbox.text())
            if url == "":
                if self.sel_lang == "tr":
                    self.urlboxempty = QMessageBox.warning(
                        self.add_download_dialog, "URL Kutusu Boş",
                        "Lütfen bir url giriniz!", QMessageBox.Ok,
                        QMessageBox.Ok)
                elif self.sel_lang == "en":
                    self.urlboxempty = QMessageBox.warning(
                        self.add_download_dialog, "URL Box Empty",
                        "Please enter a URL!", QMessageBox.Ok, QMessageBox.Ok)
            else:
                # self.add_download_dialog.close()
                # self.downloading_file()
                # self.add_download_dialog.close()
                self.download()

        self.downloadbutton = QPushButton("İndir", self.add_download_dialog)
        self.downloadbutton.setGeometry(85, 220, 70, 40)
        self.downloadbutton.setFont(QFont("Hack Nerd Font", 11))
        self.downloadbutton.clicked.connect(start_downloading_process)
        # self.downloadbutton.setStyleSheet("background-color: #268bd2;")

        # ÇIKIŞ BUTONU
        self.iptalbutton = QPushButton("İptal", self.add_download_dialog)
        self.iptalbutton.setGeometry(160, 220, 70, 40)
        self.iptalbutton.setFont(QFont("Hack Nerd Font", 11))
        self.iptalbutton.clicked.connect(self.add_download_dialog.close)
        # self.iptalbutton.setStyleSheet("background-color: #ed0b0b;")
        self.reTranslateAddDownload()
        self.add_download_dialog.show()
Ejemplo n.º 8
0
class SetupWizLoadPage(QWizardPage):
    """

    :param parent:
    :type parent:
    :param version:
    :type version:
    """

    def __init__(self, parent, version):
        super(SetupWizLoadPage, self).__init__(parent)

        self.version = version
        self.complete = False
        self.setTitle('Browse for the IDD file')
        self.setSubTitle('Browse for the specified IDD version below.')
        self.setup_page()

    def setup_page(self):
        """Create intro text
        """

        text = "The file being loaded requires an IDD file of <b>Version {}</b>. " \
               "Please choose the 'Energy+.idd' file from the installation directory " \
               "for this version of EnergyPlus.".format(self.version)
        intro_text = QLabel(text)
        intro_text.setWordWrap(True)

        # Create the button to browse for the idd file
        browse_button = QPushButton("Browse for Energy+.idd v{} in the EnergyPlus "
                                          "install directory".format(self.version))
        browse_button.clicked.connect(self.load_idd)

        # Create and configure the progress bar
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setRange(0, 100)
        self.progress_bar.hide()

        # Create and assign layout
        layout = QVBoxLayout()
        layout.addWidget(intro_text)
        layout.addWidget(browse_button)
        layout.addWidget(self.progress_bar)
        self.setLayout(layout)

    def load_idd(self):
        """Create and open file dialog
        """

        directory = os.path.expanduser('~')
        formats = "EnergyPlus IDD Files (*.idd)"
        dialog_name = 'Select EnergyPlus IDD File (Version: {})'.format(self.version)
        file_dialog = QFileDialog()
        dir_name, filt = file_dialog.getOpenFileName(self, dialog_name,
                                                     directory, formats)

        if not dir_name:
            self.complete = False
            return

        # Show progress bar and parse IDD file
        self.progress_bar.show()
        log.debug("Processing IDD file")
        idd_parser = parser.IDDParser()
        for progress in idd_parser.parse_idd(dir_name):
            self.progress_bar.setValue(progress)

        # Upon completion set complete status to true and inform object
        self.complete = True
        self.completeChanged.emit()

    def isComplete(self):
        """

        :return: :rtype:
        """

        return True if self.complete else False
Ejemplo n.º 9
0
class View(QMainWindow):
    def __init__(self, model):
        super().__init__()

        self.setWindowTitle("OpenHRV")
        self.setWindowIcon(QIcon(":/logo.png"))
        self.setGeometry(50, 50, 1750, 850)

        self.model = model
        self.signals = ViewSignals()

        self.scanner = SensorScanner()
        self.scanner_thread = QThread(self)
        self.scanner.moveToThread(self.scanner_thread)
        self.scanner.mac_update.connect(self.model.set_mac_addresses)

        self.sensor = SensorClient()
        self.sensor_thread = QThread(self)
        self.sensor.moveToThread(self.sensor_thread)
        self.sensor.ibi_update.connect(self.model.set_ibis_buffer)
        self.sensor_thread.started.connect(self.sensor.run)

        self.redis_publisher = RedisPublisher()
        self.redis_publisher_thread = QThread(self)
        self.redis_publisher.moveToThread(self.redis_publisher_thread)
        self.model.ibis_buffer_update.connect(self.redis_publisher.publish)
        self.model.mean_hrv_update.connect(self.redis_publisher.publish)
        self.model.mac_addresses_update.connect(self.redis_publisher.publish)
        self.model.pacer_rate_update.connect(self.redis_publisher.publish)
        self.model.hrv_target_update.connect(self.redis_publisher.publish)
        self.model.biofeedback_update.connect(self.redis_publisher.publish)
        self.signals.annotation.connect(self.redis_publisher.publish)
        self.redis_publisher_thread.started.connect(
            self.redis_publisher.monitor.start)

        self.redis_logger = RedisLogger()
        self.redis_logger_thread = QThread(self)
        self.redis_logger.moveToThread(self.redis_logger_thread)
        self.redis_logger_thread.finished.connect(
            self.redis_logger.save_recording)
        self.redis_logger.recording_status.connect(self.show_recording_status)

        self.ibis_plot = pg.PlotWidget()
        self.ibis_plot.setBackground("w")
        self.ibis_plot.setLabel("left", "Inter-Beat-Interval (msec)",
                                **{"font-size": "25px"})
        self.ibis_plot.setLabel("bottom", "Seconds", **{"font-size": "25px"})
        self.ibis_plot.showGrid(y=True)
        self.ibis_plot.setYRange(300, 1500, padding=0)
        self.ibis_plot.setMouseEnabled(x=False, y=False)

        self.ibis_signal = pg.PlotCurveItem()
        pen = pg.mkPen(color=(0, 191, 255), width=7.5)
        self.ibis_signal.setPen(pen)
        self.ibis_signal.setData(self.model.ibis_seconds,
                                 self.model.ibis_buffer)
        self.ibis_plot.addItem(self.ibis_signal)

        self.mean_hrv_plot = pg.PlotWidget()
        self.mean_hrv_plot.setBackground("w")
        self.mean_hrv_plot.setLabel("left", "HRV (msec)",
                                    **{"font-size": "25px"})
        self.mean_hrv_plot.setLabel("bottom", "Seconds",
                                    **{"font-size": "25px"})
        self.mean_hrv_plot.showGrid(y=True)
        self.mean_hrv_plot.setYRange(0, 600, padding=0)
        self.mean_hrv_plot.setMouseEnabled(x=False, y=False)
        colorgrad = QLinearGradient(0, 0, 0, 1)  # horizontal gradient
        colorgrad.setCoordinateMode(QGradient.ObjectMode)
        colorgrad.setColorAt(0, pg.mkColor("g"))
        colorgrad.setColorAt(.5, pg.mkColor("y"))
        colorgrad.setColorAt(1, pg.mkColor("r"))
        brush = QBrush(colorgrad)
        self.mean_hrv_plot.getViewBox().setBackgroundColor(brush)

        self.mean_hrv_signal = pg.PlotCurveItem()
        pen = pg.mkPen(color="w", width=7.5)
        self.mean_hrv_signal.setPen(pen)
        self.mean_hrv_signal.setData(self.model.mean_hrv_seconds,
                                     self.model.mean_hrv_buffer)
        self.mean_hrv_plot.addItem(self.mean_hrv_signal)

        self.pacer_plot = pg.PlotWidget()
        self.pacer_plot.setBackground("w")
        self.pacer_plot.setAspectLocked(lock=True, ratio=1)
        self.pacer_plot.setMouseEnabled(x=False, y=False)
        self.pacer_plot.disableAutoRange()
        self.pacer_plot.setXRange(-1, 1, padding=0)
        self.pacer_plot.setYRange(-1, 1, padding=0)
        self.pacer_plot.hideAxis("left")
        self.pacer_plot.hideAxis("bottom")

        self.pacer_disc = pg.PlotCurveItem()
        brush = pg.mkBrush(color=(135, 206, 250))
        self.pacer_disc.setBrush(brush)
        self.pacer_disc.setFillLevel(1)
        self.pacer_plot.addItem(self.pacer_disc)

        self.pacer_rate = QSlider(Qt.Horizontal)
        self.pacer_rate.setTracking(False)
        self.pacer_rate.setRange(
            0, 6)  # transformed to bpm [4, 7], step .5 by model
        self.pacer_rate.valueChanged.connect(self.model.set_breathing_rate)
        self.pacer_rate.setSliderPosition(4)  # corresponds to 6 bpm
        self.pacer_label = QLabel(f"Rate: {self.model.breathing_rate}")

        self.pacer_toggle = QCheckBox("Show pacer", self)
        self.pacer_toggle.setChecked(True)
        self.pacer_toggle.stateChanged.connect(self.toggle_pacer)

        self.hrv_target_label = QLabel(f"Target: {self.model.hrv_target}")

        self.hrv_target = QSlider(Qt.Horizontal)
        self.hrv_target.setRange(50, 600)
        self.hrv_target.setSingleStep(10)
        self.hrv_target.valueChanged.connect(self.model.set_hrv_target)
        self.hrv_target.setSliderPosition(self.model.hrv_target)
        self.mean_hrv_plot.setYRange(0, self.model.hrv_target, padding=0)

        self.scan_button = QPushButton("Scan")
        self.scan_button.clicked.connect(self.scanner.scan)

        self.mac_menu = QComboBox()

        self.connect_button = QPushButton("Connect")
        self.connect_button.clicked.connect(self.connect_sensor)

        self.start_recording_button = QPushButton("Start")
        self.start_recording_button.clicked.connect(
            self.redis_logger.start_recording)

        self.save_recording_button = QPushButton("Save")
        self.save_recording_button.clicked.connect(
            self.redis_logger.save_recording)

        self.annotation = QComboBox()
        self.annotation.setEditable(True)
        self.annotation.setDuplicatesEnabled(False)
        self.annotation.addItems([
            "start_baseline", "end_baseline", "start_bf", "end_bf",
            "start_nobf", "end_nobf"
        ])
        self.annotation.setMaxCount(
            10)  # user can configure up to 4 additional custom annotations
        self.annotation_button = QPushButton("Annotate")
        self.annotation_button.clicked.connect(self.emit_annotation)
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.recording_status_label = QLabel("Status:")
        self.recording_statusbar = QProgressBar()
        self.recording_statusbar.setRange(0, 1)

        self.vlayout0 = QVBoxLayout(self.central_widget)

        self.hlayout0 = QHBoxLayout()
        self.hlayout0.addWidget(self.ibis_plot, stretch=80)
        self.hlayout0.addWidget(self.pacer_plot, stretch=20)
        self.vlayout0.addLayout(self.hlayout0)

        self.vlayout0.addWidget(self.mean_hrv_plot)

        self.hlayout1 = QHBoxLayout()

        self.device_config = QFormLayout()
        self.device_config.addRow(self.scan_button, self.mac_menu)
        self.device_config.addRow(self.connect_button)
        self.device_panel = QGroupBox("ECG Devices")
        self.device_panel.setLayout(self.device_config)
        self.hlayout1.addWidget(self.device_panel, stretch=25)

        self.hrv_config = QFormLayout()
        self.hrv_config.addRow(self.hrv_target_label, self.hrv_target)
        self.hrv_panel = QGroupBox("HRV Settings")
        self.hrv_panel.setLayout(self.hrv_config)
        self.hlayout1.addWidget(self.hrv_panel, stretch=25)

        self.pacer_config = QFormLayout()
        self.pacer_config.addRow(self.pacer_label, self.pacer_rate)
        self.pacer_config.addRow(self.pacer_toggle)
        self.pacer_panel = QGroupBox("Breathing Pacer")
        self.pacer_panel.setLayout(self.pacer_config)
        self.hlayout1.addWidget(self.pacer_panel, stretch=25)

        self.recording_config = QGridLayout()
        self.recording_config.addWidget(self.start_recording_button, 0, 0)
        self.recording_config.addWidget(self.save_recording_button, 0, 1)
        self.recording_config.addWidget(self.recording_statusbar, 0, 2)
        self.recording_config.addWidget(self.annotation, 1, 0, 1,
                                        2)  # row, column, rowspan, columnspan
        self.recording_config.addWidget(self.annotation_button, 1, 2)

        self.recording_panel = QGroupBox("Recording")
        self.recording_panel.setLayout(self.recording_config)
        self.hlayout1.addWidget(self.recording_panel, stretch=25)

        self.vlayout0.addLayout(self.hlayout1)

        self.model.ibis_buffer_update.connect(self.plot_ibis)
        self.model.mean_hrv_update.connect(self.plot_hrv)
        self.model.mac_addresses_update.connect(self.list_macs)
        self.model.pacer_disk_update.connect(self.plot_pacer_disk)
        self.model.pacer_rate_update.connect(self.update_pacer_label)
        self.model.hrv_target_update.connect(self.update_hrv_target)

        self.scanner_thread.start()
        self.sensor_thread.start()
        self.redis_publisher_thread.start()
        self.redis_logger_thread.start()

    def closeEvent(self, event):
        """Properly shut down all threads."""
        print("Closing threads...")
        self.scanner_thread.quit()
        self.scanner_thread.wait()

        self.sensor_thread.quit(
        )  # since quit() only works if the thread has a running event loop...
        asyncio.run_coroutine_threadsafe(
            self.sensor.stop(), self.sensor.loop
        )  # ...the event loop must only be stopped AFTER quit() has been called!
        self.sensor_thread.wait()

        self.redis_publisher_thread.quit()
        self.redis_publisher_thread.wait()

        self.redis_logger_thread.quit()
        self.redis_logger_thread.wait()

    def connect_sensor(self):
        mac = self.mac_menu.currentText()
        if not valid_mac(mac):
            print("Invalid MAC.")
            return
        asyncio.run_coroutine_threadsafe(self.sensor.connect_client(mac),
                                         self.sensor.loop)

    def plot_ibis(self, ibis):
        self.ibis_signal.setData(self.model.ibis_seconds, ibis[1])

    def plot_hrv(self, hrv):
        self.mean_hrv_signal.setData(self.model.mean_hrv_seconds, hrv[1])

    def list_macs(self, macs):
        self.mac_menu.clear()
        self.mac_menu.addItems(macs[1])

    def plot_pacer_disk(self, coordinates):
        self.pacer_disc.setData(*coordinates[1])

    def update_pacer_label(self, rate):
        self.pacer_label.setText(f"Rate: {rate[1]}")

    def update_hrv_target(self, target):
        self.mean_hrv_plot.setYRange(0, target[1], padding=0)
        self.hrv_target_label.setText(f"Target: {target[1]}")

    def toggle_pacer(self):
        visible = self.pacer_plot.isVisible()
        self.pacer_plot.setVisible(not visible)

    def show_recording_status(self, status):
        self.recording_statusbar.setRange(
            0, status)  # indicates busy state if progress is 0

    def emit_annotation(self):
        self.signals.annotation.emit(
            ("eventmarker", self.annotation.currentText()))
Ejemplo n.º 10
0
    def __init__(self, model):
        super().__init__()

        self.setWindowTitle("OpenHRV")
        self.setWindowIcon(QIcon(":/logo.png"))
        self.setGeometry(50, 50, 1750, 850)

        self.model = model
        self.signals = ViewSignals()

        self.scanner = SensorScanner()
        self.scanner_thread = QThread(self)
        self.scanner.moveToThread(self.scanner_thread)
        self.scanner.mac_update.connect(self.model.set_mac_addresses)

        self.sensor = SensorClient()
        self.sensor_thread = QThread(self)
        self.sensor.moveToThread(self.sensor_thread)
        self.sensor.ibi_update.connect(self.model.set_ibis_buffer)
        self.sensor_thread.started.connect(self.sensor.run)

        self.redis_publisher = RedisPublisher()
        self.redis_publisher_thread = QThread(self)
        self.redis_publisher.moveToThread(self.redis_publisher_thread)
        self.model.ibis_buffer_update.connect(self.redis_publisher.publish)
        self.model.mean_hrv_update.connect(self.redis_publisher.publish)
        self.model.mac_addresses_update.connect(self.redis_publisher.publish)
        self.model.pacer_rate_update.connect(self.redis_publisher.publish)
        self.model.hrv_target_update.connect(self.redis_publisher.publish)
        self.model.biofeedback_update.connect(self.redis_publisher.publish)
        self.signals.annotation.connect(self.redis_publisher.publish)
        self.redis_publisher_thread.started.connect(
            self.redis_publisher.monitor.start)

        self.redis_logger = RedisLogger()
        self.redis_logger_thread = QThread(self)
        self.redis_logger.moveToThread(self.redis_logger_thread)
        self.redis_logger_thread.finished.connect(
            self.redis_logger.save_recording)
        self.redis_logger.recording_status.connect(self.show_recording_status)

        self.ibis_plot = pg.PlotWidget()
        self.ibis_plot.setBackground("w")
        self.ibis_plot.setLabel("left", "Inter-Beat-Interval (msec)",
                                **{"font-size": "25px"})
        self.ibis_plot.setLabel("bottom", "Seconds", **{"font-size": "25px"})
        self.ibis_plot.showGrid(y=True)
        self.ibis_plot.setYRange(300, 1500, padding=0)
        self.ibis_plot.setMouseEnabled(x=False, y=False)

        self.ibis_signal = pg.PlotCurveItem()
        pen = pg.mkPen(color=(0, 191, 255), width=7.5)
        self.ibis_signal.setPen(pen)
        self.ibis_signal.setData(self.model.ibis_seconds,
                                 self.model.ibis_buffer)
        self.ibis_plot.addItem(self.ibis_signal)

        self.mean_hrv_plot = pg.PlotWidget()
        self.mean_hrv_plot.setBackground("w")
        self.mean_hrv_plot.setLabel("left", "HRV (msec)",
                                    **{"font-size": "25px"})
        self.mean_hrv_plot.setLabel("bottom", "Seconds",
                                    **{"font-size": "25px"})
        self.mean_hrv_plot.showGrid(y=True)
        self.mean_hrv_plot.setYRange(0, 600, padding=0)
        self.mean_hrv_plot.setMouseEnabled(x=False, y=False)
        colorgrad = QLinearGradient(0, 0, 0, 1)  # horizontal gradient
        colorgrad.setCoordinateMode(QGradient.ObjectMode)
        colorgrad.setColorAt(0, pg.mkColor("g"))
        colorgrad.setColorAt(.5, pg.mkColor("y"))
        colorgrad.setColorAt(1, pg.mkColor("r"))
        brush = QBrush(colorgrad)
        self.mean_hrv_plot.getViewBox().setBackgroundColor(brush)

        self.mean_hrv_signal = pg.PlotCurveItem()
        pen = pg.mkPen(color="w", width=7.5)
        self.mean_hrv_signal.setPen(pen)
        self.mean_hrv_signal.setData(self.model.mean_hrv_seconds,
                                     self.model.mean_hrv_buffer)
        self.mean_hrv_plot.addItem(self.mean_hrv_signal)

        self.pacer_plot = pg.PlotWidget()
        self.pacer_plot.setBackground("w")
        self.pacer_plot.setAspectLocked(lock=True, ratio=1)
        self.pacer_plot.setMouseEnabled(x=False, y=False)
        self.pacer_plot.disableAutoRange()
        self.pacer_plot.setXRange(-1, 1, padding=0)
        self.pacer_plot.setYRange(-1, 1, padding=0)
        self.pacer_plot.hideAxis("left")
        self.pacer_plot.hideAxis("bottom")

        self.pacer_disc = pg.PlotCurveItem()
        brush = pg.mkBrush(color=(135, 206, 250))
        self.pacer_disc.setBrush(brush)
        self.pacer_disc.setFillLevel(1)
        self.pacer_plot.addItem(self.pacer_disc)

        self.pacer_rate = QSlider(Qt.Horizontal)
        self.pacer_rate.setTracking(False)
        self.pacer_rate.setRange(
            0, 6)  # transformed to bpm [4, 7], step .5 by model
        self.pacer_rate.valueChanged.connect(self.model.set_breathing_rate)
        self.pacer_rate.setSliderPosition(4)  # corresponds to 6 bpm
        self.pacer_label = QLabel(f"Rate: {self.model.breathing_rate}")

        self.pacer_toggle = QCheckBox("Show pacer", self)
        self.pacer_toggle.setChecked(True)
        self.pacer_toggle.stateChanged.connect(self.toggle_pacer)

        self.hrv_target_label = QLabel(f"Target: {self.model.hrv_target}")

        self.hrv_target = QSlider(Qt.Horizontal)
        self.hrv_target.setRange(50, 600)
        self.hrv_target.setSingleStep(10)
        self.hrv_target.valueChanged.connect(self.model.set_hrv_target)
        self.hrv_target.setSliderPosition(self.model.hrv_target)
        self.mean_hrv_plot.setYRange(0, self.model.hrv_target, padding=0)

        self.scan_button = QPushButton("Scan")
        self.scan_button.clicked.connect(self.scanner.scan)

        self.mac_menu = QComboBox()

        self.connect_button = QPushButton("Connect")
        self.connect_button.clicked.connect(self.connect_sensor)

        self.start_recording_button = QPushButton("Start")
        self.start_recording_button.clicked.connect(
            self.redis_logger.start_recording)

        self.save_recording_button = QPushButton("Save")
        self.save_recording_button.clicked.connect(
            self.redis_logger.save_recording)

        self.annotation = QComboBox()
        self.annotation.setEditable(True)
        self.annotation.setDuplicatesEnabled(False)
        self.annotation.addItems([
            "start_baseline", "end_baseline", "start_bf", "end_bf",
            "start_nobf", "end_nobf"
        ])
        self.annotation.setMaxCount(
            10)  # user can configure up to 4 additional custom annotations
        self.annotation_button = QPushButton("Annotate")
        self.annotation_button.clicked.connect(self.emit_annotation)
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.recording_status_label = QLabel("Status:")
        self.recording_statusbar = QProgressBar()
        self.recording_statusbar.setRange(0, 1)

        self.vlayout0 = QVBoxLayout(self.central_widget)

        self.hlayout0 = QHBoxLayout()
        self.hlayout0.addWidget(self.ibis_plot, stretch=80)
        self.hlayout0.addWidget(self.pacer_plot, stretch=20)
        self.vlayout0.addLayout(self.hlayout0)

        self.vlayout0.addWidget(self.mean_hrv_plot)

        self.hlayout1 = QHBoxLayout()

        self.device_config = QFormLayout()
        self.device_config.addRow(self.scan_button, self.mac_menu)
        self.device_config.addRow(self.connect_button)
        self.device_panel = QGroupBox("ECG Devices")
        self.device_panel.setLayout(self.device_config)
        self.hlayout1.addWidget(self.device_panel, stretch=25)

        self.hrv_config = QFormLayout()
        self.hrv_config.addRow(self.hrv_target_label, self.hrv_target)
        self.hrv_panel = QGroupBox("HRV Settings")
        self.hrv_panel.setLayout(self.hrv_config)
        self.hlayout1.addWidget(self.hrv_panel, stretch=25)

        self.pacer_config = QFormLayout()
        self.pacer_config.addRow(self.pacer_label, self.pacer_rate)
        self.pacer_config.addRow(self.pacer_toggle)
        self.pacer_panel = QGroupBox("Breathing Pacer")
        self.pacer_panel.setLayout(self.pacer_config)
        self.hlayout1.addWidget(self.pacer_panel, stretch=25)

        self.recording_config = QGridLayout()
        self.recording_config.addWidget(self.start_recording_button, 0, 0)
        self.recording_config.addWidget(self.save_recording_button, 0, 1)
        self.recording_config.addWidget(self.recording_statusbar, 0, 2)
        self.recording_config.addWidget(self.annotation, 1, 0, 1,
                                        2)  # row, column, rowspan, columnspan
        self.recording_config.addWidget(self.annotation_button, 1, 2)

        self.recording_panel = QGroupBox("Recording")
        self.recording_panel.setLayout(self.recording_config)
        self.hlayout1.addWidget(self.recording_panel, stretch=25)

        self.vlayout0.addLayout(self.hlayout1)

        self.model.ibis_buffer_update.connect(self.plot_ibis)
        self.model.mean_hrv_update.connect(self.plot_hrv)
        self.model.mac_addresses_update.connect(self.list_macs)
        self.model.pacer_disk_update.connect(self.plot_pacer_disk)
        self.model.pacer_rate_update.connect(self.update_pacer_label)
        self.model.hrv_target_update.connect(self.update_hrv_target)

        self.scanner_thread.start()
        self.sensor_thread.start()
        self.redis_publisher_thread.start()
        self.redis_logger_thread.start()
Ejemplo n.º 11
0
from PySide2.QtWidgets import QLabel, QWidget, QPushButton, QApplication, QVBoxLayout, QProgressBar
app = QApplication([])

mainWidget = QWidget()

layout = QVBoxLayout()

label = QLabel('SALUT')
button = QPushButton('Bouton')
barre = QProgressBar()

layout.addWidget(label)
layout.addWidget(button)
layout.addWidget(barre)

mainWidget.setLayout(layout)

mainWidget.show()
app.exec_()
Ejemplo n.º 12
0
class ProgressMessageBox(QDialog):
    def __init__(self, parent, title: str, text: str, min: int, max: int):
        super().__init__(
            parent, Qt.WindowSystemMenuHint | Qt.WindowTitleHint
            | Qt.WindowCloseButtonHint)

        self.setWindowTitle(title)

        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(10)

        self._label = QLabel(text, self)
        self._label.setAlignment(Qt.AlignCenter)

        self._progress = QProgressBar(self)
        self._progress.setRange(min, max)

        if min == 0 and max == 0:
            self._progress.setTextVisible(False)

        main_layout.addWidget(self._label)
        main_layout.addWidget(self._progress)

    def setText(self, text: str):
        self._label.setText(text)

    def setRange(self, min: int, max: int):
        self._progress.setRange(min, max)

        if min == 0 and max == 0:
            self._progress.setTextVisible(False)
        else:
            self._progress.setTextVisible(True)

    def setValue(self, val: int):
        self._progress.setValue(val)
 def testPB():
     pb = QProgressBar()
     pb.setMaximum(6)
     return pb
Ejemplo n.º 14
0
    def paint(self, painter, option, index):
        progressBar = QProgressBar()

        progressBar.setAlignment(Qt.AlignCenter)
        progressBar.setTextVisible(True)

        progressBar.resize(option.rect.size())
        progressBar.setMinimum(0)
        progressBar.setMaximum(100)

        if self.parent():
            progressBar.setStyleSheet(self.parent().styleSheet())

        dw = index.data()[0]
        tot = index.data()[1]
        if tot != 0:
            progressBar.setValue(round(dw / tot * 100, 2))
        else:
            progressBar.setValue(0)
        progressBar.setFormat("{}/{} MB".format(round(dw / (1024 * 1024), 2),
                                                round(tot / (1024 * 1024), 2)))

        painter.save()
        painter.translate(option.rect.topLeft())
        progressBar.render(painter, QPoint(0, 0))
        painter.restore()
Ejemplo n.º 15
0
class DDMWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.ConfigSettings()
        self.init_themes_main()

        self.MainMenuItems()

        self.MenuCreate()

        self.WindowSettings()
        self.show()

    def download_Cache(self):
        self.list_widget.clear()
        for i in getData():
            items = QListWidgetItem(i[0], self.list_widget)

    def download_CacheDelete(self):
        try:
            name = self.list_widget.currentItem().text()
            #print(f"Removing {name}")
            for i in getData():
                if name in i:
                    fname = i
                    break
            delData(name, fname[1], fname[2])
            myfile = Path(f"{fname[1]}/{fname[2]}")
            print(myfile)
            if myfile.exists():
                if self.sel_lang == "tr":
                    dosya_silme = QMessageBox.warning(
                        self, "Dosyayı Sil",
                        "Dosyayı diskten silmeli miyiz?\n\nDiskten silmek için evete basın!",
                        QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                elif self.sel_lang == "en":
                    dosya_silme = QMessageBox.warning(
                        self, "Delete File",
                        "Should we delete file from disk?\n\nTo delete file from disk press yes!",
                        QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if dosya_silme == QMessageBox.Yes:
                    try:
                        myfile.unlink()
                        if self.sel_lang == "tr":
                            dosya_silme = QMessageBox.information(
                                self, "Dosya Silindi",
                                "Dosya Başarıyla Silindi!", QMessageBox.Ok,
                                QMessageBox.Ok)
                        elif self.sel_lang == "en":
                            dosya_silme = QMessageBox.information(
                                self, "File Deleted",
                                "File Succesfuly Deleted!", QMessageBox.Ok,
                                QMessageBox.Ok)
                    except Exception as e:
                        print(e)
                elif dosya_silme == QMessageBox.No:
                    pass
            self.download_Cache()
        except Exception as e:
            print(e)

    def slideLeftMenu(self):
        width = self.left_side_menu.width()

        if width == 50:
            newWidth = 150
        else:
            newWidth = 50

        self.animation = QPropertyAnimation(self.left_side_menu,
                                            b"minimumWidth")
        self.animation.setDuration(250)
        self.animation.setStartValue(width)
        self.animation.setEndValue(newWidth)
        self.animation.setEasingCurve(QtCore.QEasingCurve.InOutQuart)
        self.animation.start()

    def Add_Download(self):
        self.add_download_dialog = QDialog()

        self.add_download_dialog.setWindowTitle("Add_Download")
        # self.setWindowIcon(QIcon("logo.png"))
        self.init_themes_add_dialog()
        self.add_download_dialog.setFixedSize(325, 275)
        self.add_download_dialog.setMinimumSize(325, 240)

        self.isim = QLabel("İndir", self.add_download_dialog)
        self.isim.setFont(QFont("Hack Nerd Font", 15))
        self.isim.setGeometry(124, 13, 125, 34)

        # İlerleme/Progress
        # self.progressBar =

        # URL KUTUSU
        self.urlbox = QLineEdit("", self.add_download_dialog)
        # self.urlbox.setFixedSize(100,4)
        self.urlbox.setGeometry(35, 60, 250, 34)
        self.urlbox.setPlaceholderText("URL Gir")
        self.urlbox.setFont(QFont("Hack Nerd Font", 11))

        # INDIRME KONUMU
        self.downdirectory = QLineEdit(str(Path.home()),
                                       self.add_download_dialog)
        self.downdirectory.setGeometry(35, 100, 210, 34)
        self.downdirectory.setPlaceholderText("İndirilecek Konum")
        self.downdirectory.setFont(QFont("Hack Nerd Font", 11))

        # Dosya İsmi
        self.enterfilename = QLineEdit("", self.add_download_dialog)
        # self.filename.setFixedSize(100,4)
        self.enterfilename.setGeometry(35, 140, 210, 34)
        self.enterfilename.setPlaceholderText("Dosya İsmi(Opsiyonel)")
        self.enterfilename.setFont(QFont("Hack Nerd Font", 11))

        def connectfilename():
            fnameloop = asyncio.get_event_loop()
            fnameloop.run_until_complete(self.detect_fname())

        self.connectfilename = QPushButton(".", self.add_download_dialog)
        self.connectfilename.setGeometry(249, 140, 36, 34)
        self.connectfilename.setFont(QFont("Hack Nerd Font", 11))
        self.connectfilename.clicked.connect(connectfilename)

        # KONUM SEÇ BUTONU
        def download_dir():
            if self.sel_lang == "tr":
                try:
                    self.dirselectdialog = QFileDialog.getExistingDirectory(
                        self.add_download_dialog, 'İndirilecek Konumu Seç')
                except Exception as e:
                    print(e)
            elif self.sel_lang == "en":
                try:
                    self.dirselectdialog = QFileDialog.getExistingDirectory(
                        self.add_download_dialog, 'Select Dir')
                except Exception as e:
                    print(e)
            if self.dirselectdialog == "":
                self.downdirectory.setText(str(Path.home()))
            else:
                self.downdirectory.setText(str(self.dirselectdialog))

        self.selectdirbutton = QPushButton("...", self.add_download_dialog)
        self.selectdirbutton.setGeometry(249, 100, 36, 34)
        self.selectdirbutton.setFont(QFont("Hack Nerd Font", 11))
        self.selectdirbutton.clicked.connect(download_dir)

        # ProgressBar/İlerleme
        self.progressbar = QProgressBar(self.add_download_dialog)
        self.progressbar.setGeometry(35, 180, 250, 34)
        self.progressbar.setValue(0)

        # self.progressbar.hide()

        # INDIR BUTONU

        def start_downloading_process():
            url = str(self.urlbox.text())
            if url == "":
                if self.sel_lang == "tr":
                    self.urlboxempty = QMessageBox.warning(
                        self.add_download_dialog, "URL Kutusu Boş",
                        "Lütfen bir url giriniz!", QMessageBox.Ok,
                        QMessageBox.Ok)
                elif self.sel_lang == "en":
                    self.urlboxempty = QMessageBox.warning(
                        self.add_download_dialog, "URL Box Empty",
                        "Please enter a URL!", QMessageBox.Ok, QMessageBox.Ok)
            else:
                # self.add_download_dialog.close()
                # self.downloading_file()
                # self.add_download_dialog.close()
                self.download()

        self.downloadbutton = QPushButton("İndir", self.add_download_dialog)
        self.downloadbutton.setGeometry(85, 220, 70, 40)
        self.downloadbutton.setFont(QFont("Hack Nerd Font", 11))
        self.downloadbutton.clicked.connect(start_downloading_process)
        # self.downloadbutton.setStyleSheet("background-color: #268bd2;")

        # ÇIKIŞ BUTONU
        self.iptalbutton = QPushButton("İptal", self.add_download_dialog)
        self.iptalbutton.setGeometry(160, 220, 70, 40)
        self.iptalbutton.setFont(QFont("Hack Nerd Font", 11))
        self.iptalbutton.clicked.connect(self.add_download_dialog.close)
        # self.iptalbutton.setStyleSheet("background-color: #ed0b0b;")
        self.reTranslateAddDownload()
        self.add_download_dialog.show()

    # def downloading_file(self):
    #    self.downloading_dialog = QDialog()
    #    self.init_themes_add_dialog()
    #    self.downloading_dialog.setFixedSize(240, 240)
    #    #self.downloading_dialog.setMinimumSize(325, 240)

    # self.downloading_dialog.exec()
    def reTranslateAddDownload(self):
        if self.sel_lang == "en":
            self.isim.setText("Download")
            self.isim.setGeometry(110, 13, 125, 34)

            self.downloadbutton.setText("Download")
            self.downloadbutton.setGeometry(65, 220, 90, 40)

            self.iptalbutton.setText("Cancel")

            self.enterfilename.setPlaceholderText("File Name(Optional)")
            self.downdirectory.setPlaceholderText("Enter Directory")
            self.urlbox.setPlaceholderText("Enter the URL")

    def eventFilter(self, source, event):
        try:
            if (event.type() == QtCore.QEvent.ContextMenu
                    and source is self.list_widget):
                try:
                    self.menu = QMenu()
                    self.menu.addAction('In Future')
                    if self.menu.exec_(event.globalPos()):
                        item = source.itemAt(event.pos())
                        print(item.text())
                    return True
                except Exception as e:
                    print(e)
            return super().eventFilter(source, event)
        except Exception as e:
            print(e)

    from mainUI import MainMenuItems
    from mainUI import reTranslateMain

    from download_script import detect_fname
    from download_script import detect_fsize
    from download_script import check_connection
    from download_script import download

    # MenuBar things
    from MenuBar import exitAction
    from MenuBar import MenuCreate

    from MenuBar import about
    from MenuBar import reTranslateAbout

    from MenuBar import SettingsMenu
    from MenuBar import SetSettings
    from MenuBar import restartforsettings
    from MenuBar import reTranslateSettings

    # Theming Things
    from theming import init_themes_main
    from theming import init_themes_add_dialog
    from theming import init_themes_settings_dialog
    from theming import init_themes_about_dialog

    def WindowSettings(self):
        self.setWindowTitle("Dream Download Manager")
        # self.setWindowIcon(QIcon("logo.png"))

        #self.setFixedSize(485, 375)
        #self.setMinimumSize(325, 240)

    def ConfigSettings(self):
        self.settings = QSettings("DDM", "DreamDownloadManager")
        print(self.settings.fileName())
        if self.settings.contains('theme_selection'):
            self.selected_theme = self.settings.value('theme_selection')
        else:
            self.settings.setValue('theme_selection', 'Dark')

        if self.settings.contains('selected_lang'):
            self.sel_lang = self.settings.value('selected_lang')
        else:
            self.settings.setValue('selected_lang', 'en')
Ejemplo n.º 16
0
class ApplicationControlWidget(QWidget):
    """Widget with control buttons for M1M3 operations. Buttons are disabled/enabled and reasonable defaults sets on DetailedState changes."""

    TEXT_START = "&Start"
    """Constants for button titles. Titles are used to select command send to SAL."""
    TEXT_ENABLE = "&Enable"
    TEXT_DISABLE = "&Disable"
    TEXT_STANDBY = "&Standby"
    TEXT_RAISE = "&Raise M1M3"
    TEXT_ABORT_RAISE = "&Abort M1M3 Raise"
    TEXT_LOWER = "&Lower M1M3"
    TEXT_ENTER_ENGINEERING = "&Enter Engineering"
    TEXT_EXIT_ENGINEERING = "&Exit Engineering"
    TEXT_EXIT_CONTROL = "&Exit Control"

    def __init__(self, m1m3):
        super().__init__()

        self.m1m3 = m1m3
        self.lastEnabled = None

        def _addButton(text, onClick, default=False):
            button = QPushButton(text)
            button.clicked.connect(onClick)
            button.setEnabled(False)
            button.setAutoDefault(default)
            return button

        self.startButton = _addButton(self.TEXT_START, self.start, True)
        self.enableButton = _addButton(self.TEXT_ENABLE, self.enable, True)
        self.raiseButton = _addButton(self.TEXT_RAISE, self.raiseControl, True)
        self.engineeringButton = _addButton(self.TEXT_ENTER_ENGINEERING,
                                            self.engineering)
        self.exitButton = _addButton(self.TEXT_STANDBY, self.exit)

        self.supportedNumber = QLCDNumber(6)
        self.supportedNumber.setAutoFillBackground(True)
        self.minPressure = QLCDNumber(6)
        self.minPressure.setAutoFillBackground(True)
        self.maxPressure = QLCDNumber(6)
        self.maxPressure.setAutoFillBackground(True)

        dataLayout = QFormLayout()
        dataLayout.addRow("Supported", self.supportedNumber)
        dataLayout.addRow("Min pressure", self.minPressure)
        dataLayout.addRow("Max pressure", self.maxPressure)

        commandLayout = QVBoxLayout()
        commandLayout.addWidget(self.startButton)
        commandLayout.addWidget(self.enableButton)
        commandLayout.addWidget(self.raiseButton)
        commandLayout.addWidget(self.engineeringButton)
        commandLayout.addWidget(self.exitButton)
        commandLayout.addLayout(dataLayout)
        commandLayout.addStretch()

        self.supportPercentage = QProgressBar()
        self.supportPercentage.setOrientation(Qt.Vertical)
        self.supportPercentage.setRange(0, 100)
        self.supportPercentage.setTextVisible(True)
        self.supportPercentage.setFormat("%p%")

        layout = QHBoxLayout()
        layout.addLayout(commandLayout)
        layout.addWidget(self.supportPercentage)

        self.setLayout(layout)

        # connect SAL signals
        self.m1m3.detailedState.connect(self.detailedState)
        self.m1m3.forceActuatorState.connect(self.forceActuatorState)
        self.m1m3.hardpointMonitorData.connect(self.hardpointMonitorData)

    def disableAllButtons(self):
        if self.lastEnabled is None:
            self.lastEnabled = [
                self.startButton.isEnabled(),
                self.enableButton.isEnabled(),
                self.raiseButton.isEnabled(),
                self.engineeringButton.isEnabled(),
                self.exitButton.isEnabled(),
            ]
        self.startButton.setEnabled(False)
        self.enableButton.setEnabled(False)
        self.raiseButton.setEnabled(False)
        self.engineeringButton.setEnabled(False)
        self.exitButton.setEnabled(False)

    def restoreEnabled(self):
        if self.lastEnabled is None:
            return
        self.startButton.setEnabled(self.lastEnabled[0])
        self.enableButton.setEnabled(self.lastEnabled[1])
        self.raiseButton.setEnabled(self.lastEnabled[2])
        self.engineeringButton.setEnabled(self.lastEnabled[3])
        self.exitButton.setEnabled(self.lastEnabled[4])
        self.lastEnabled = None

    async def command(self, button):
        self.disableAllButtons()
        try:
            if button.text() == self.TEXT_START:
                await self.m1m3.remote.cmd_start.set_start(
                    settingsToApply="Default", timeout=60)
            elif button.text() == self.TEXT_EXIT_CONTROL:
                await self.m1m3.remote.cmd_exitControl.start()
            elif button.text() == self.TEXT_ENABLE:
                await self.m1m3.remote.cmd_enable.start()
            elif button.text() == self.TEXT_DISABLE:
                await self.m1m3.remote.cmd_disable.start()
            elif button.text() == self.TEXT_RAISE:
                await self.m1m3.remote.cmd_raiseM1M3.set_start(
                    raiseM1M3=True, bypassReferencePosition=False)
            elif button.text() == self.TEXT_ABORT_RAISE:
                await self.m1m3.remote.cmd_abortRaiseM1M3.start()
            elif button.text() == self.TEXT_LOWER:
                await self.m1m3.remote.cmd_lowerM1M3.start()
            elif button.text() == self.TEXT_ENTER_ENGINEERING:
                await self.m1m3.remote.cmd_enterEngineering.start()
            elif button.text() == self.TEXT_EXIT_ENGINEERING:
                await self.m1m3.remote.cmd_exitEngineering.start()
            elif button.text() == self.TEXT_STANDBY:
                await self.m1m3.remote.cmd_standby.start()
        except base.AckError as ackE:
            warning(
                self,
                f"Error executing button {button.text()}",
                f"Error executing button <i>{button.text()}</i>:<br/>{ackE.ackcmd.result}",
            )
        except RuntimeError as rte:
            warning(
                self,
                f"Error executing {button.text()}",
                f"Executing button <i>{button.text()}</i>:<br/>{str(rte)}",
            )
        finally:
            self.restoreEnabled()

    @asyncSlot()
    async def start(self):
        await self.command(self.startButton)

    @asyncSlot()
    async def enable(self):
        await self.command(self.enableButton)

    @asyncSlot()
    async def raiseControl(self):
        await self.command(self.raiseButton)

    @asyncSlot()
    async def engineering(self):
        await self.command(self.engineeringButton)

    @asyncSlot()
    async def exit(self):
        await self.command(self.exitButton)

    def _setTextEnable(self, button, text):
        button.setText(text)
        button.setEnabled(True)

    @Slot(map)
    def detailedState(self, data):
        self.lastEnabled = None
        if data.detailedState == DetailedState.DISABLED:
            self.raiseButton.setEnabled(False)
            self.engineeringButton.setEnabled(False)
            self._setTextEnable(self.enableButton, self.TEXT_ENABLE)
            self._setTextEnable(self.exitButton, self.TEXT_STANDBY)
            self.enableButton.setDefault(True)
        elif data.detailedState == DetailedState.FAULT:
            self._setTextEnable(self.startButton, self.TEXT_STANDBY)
            self.startButton.setDefault(True)
        elif data.detailedState == DetailedState.OFFLINE:
            self.startButton.setEnabled(False)
        elif data.detailedState == DetailedState.STANDBY:
            self.enableButton.setEnabled(False)
            self._setTextEnable(self.startButton, self.TEXT_START)
            self._setTextEnable(self.exitButton, self.TEXT_EXIT_CONTROL)
            self.startButton.setDefault(True)
        elif data.detailedState == DetailedState.PARKED:
            self._setTextEnable(self.enableButton, self.TEXT_DISABLE)
            self._setTextEnable(self.raiseButton, self.TEXT_RAISE)
            self._setTextEnable(self.engineeringButton,
                                self.TEXT_ENTER_ENGINEERING)
            self.exitButton.setEnabled(False)
            self.raiseButton.setDefault(True)
        elif data.detailedState == DetailedState.RAISING:
            self._setTextEnable(self.raiseButton, self.TEXT_ABORT_RAISE)
            self.engineeringButton.setEnabled(False)
            self.raiseButton.setDefault(True)
        elif data.detailedState == DetailedState.ACTIVE:
            self._setTextEnable(self.raiseButton, self.TEXT_LOWER)
            self._setTextEnable(self.engineeringButton,
                                self.TEXT_ENTER_ENGINEERING)
            self.engineeringButton.setEnabled(True)
        elif data.detailedState == DetailedState.LOWERING:
            pass
        elif data.detailedState == DetailedState.PARKEDENGINEERING:
            self.enableButton.setEnabled(False)
            self._setTextEnable(self.raiseButton, self.TEXT_RAISE)
            self._setTextEnable(self.engineeringButton,
                                self.TEXT_EXIT_ENGINEERING)
        elif data.detailedState == DetailedState.RAISINGENGINEERING:
            self._setTextEnable(self.raiseButton, self.TEXT_ABORT_RAISE)
            self.engineeringButton.setEnabled(False)
        elif data.detailedState == DetailedState.ACTIVEENGINEERING:
            self._setTextEnable(self.raiseButton, self.TEXT_LOWER)
            self.engineeringButton.setEnabled(True)
            self._setTextEnable(self.engineeringButton,
                                self.TEXT_EXIT_ENGINEERING)
        elif data.detailedState == DetailedState.LOWERINGENGINEERING:
            pass
        elif data.detailedState == DetailedState.LOWERINGFAULT:
            self._setTextEnable(self.exitButton, self.TEXT_STANDBY)
        elif data.detailedState == DetailedState.PROFILEHARDPOINTCORRECTIONS:
            pass
        else:
            print(f"Unhandled detailed state {data.detailedState}")

    @Slot(map)
    def forceActuatorState(self, data):
        self.supportPercentage.setValue(data.supportPercentage)
        pal = self.supportedNumber.palette()
        if data.supportPercentage == 0:
            col = QColor(255, 0, 0)
        elif data.supportPercentage < 90:
            col = QColor(0, 0, 255)
        elif data.supportPercentage < 100:
            col = QColor(255, 255, 0)
        else:
            col = QColor(0, 255, 0)
        pal.setColor(pal.Background, col)
        self.supportedNumber.display(f"{data.supportPercentage:.02f}")
        self.supportedNumber.setPalette(pal)

    @Slot(map)
    def hardpointMonitorData(self, data):
        min_d = min(data.breakawayPressure)
        max_d = max(data.breakawayPressure)

        def _getColor(v):
            if v < 110 or v > 127:
                return QColor(255, 0, 0)
            elif v < 115 or v > 125:
                return QColor(255, 255, 0)
            return QColor(0, 255, 0)

        min_pal = self.minPressure.palette()
        min_pal.setColor(min_pal.Background, _getColor(min_d))
        self.minPressure.display(f"{min_d:.02f}")
        self.minPressure.setPalette(min_pal)

        max_pal = self.minPressure.palette()
        max_pal.setColor(max_pal.Background, _getColor(max_d))
        self.maxPressure.display(f"{max_d:.02f}")
        self.maxPressure.setPalette(max_pal)
Ejemplo n.º 17
0
 def setValue(self, p_int):
     QProgressBar.setValue(self, p_int)
     self.repaint()
Ejemplo n.º 18
0
    def addDownloadItem(self, taskId: str, fileName: str, filePath: str, url: str):
        row = self.tableWidget.rowCount()
        self.tableWidget.setRowCount(row + 1)

        taskIdItem = QTableWidgetItem(taskId)
        fileNameItem = QTableWidgetItem(fileName)
        progressBarItem = QTableWidgetItem()
        downloadSpeedItem = QTableWidgetItem("0 MB/s")
        downloadStatusItem = QTableWidgetItem("Pending")
        downloadUrlItem = QTableWidgetItem(url)
        filePathItem = QTableWidgetItem(filePath)
        cancelItem = QTableWidgetItem()
        retryItem = QTableWidgetItem()
        deleteItem = QTableWidgetItem()

        taskIdItem.setFlags(Qt.ItemIsEnabled)
        fileNameItem.setFlags(Qt.ItemIsEnabled)
        progressBarItem.setFlags(Qt.ItemIsEnabled)
        downloadSpeedItem.setFlags(Qt.ItemIsEnabled)
        downloadStatusItem.setFlags(Qt.ItemIsEnabled)
        downloadUrlItem.setFlags(Qt.ItemIsEnabled)
        filePathItem.setFlags(Qt.ItemIsEnabled)
        cancelItem.setFlags(Qt.ItemIsEnabled)
        retryItem.setFlags(Qt.ItemIsEnabled)
        deleteItem.setFlags(Qt.ItemIsEnabled)

        progressBar = QProgressBar()
        progressBar.setMinimum(0)
        progressBar.setMaximum(100)
        progressBar.setValue(0)
        progressBar.setAlignment(Qt.AlignCenter)
        progressBar.setFormat(str(progressBar.value()) + ' %')

        cancelButton = QPushButton('Cancel')
        cancelButton.clicked.connect(self.cancelTask)

        retryButton = QPushButton('Retry')
        retryButton.clicked.connect(self.retryTask)

        deleteButton = QPushButton('Delete')
        deleteButton.clicked.connect(self.deleteTask)

        self.tableWidget.setItem(row, 0, taskIdItem)
        self.tableWidget.setItem(row, 1, fileNameItem)
        self.tableWidget.setItem(row, 2, progressBarItem)
        self.tableWidget.setCellWidget(row, 2, progressBar)
        self.tableWidget.setItem(row, 3, downloadSpeedItem)
        self.tableWidget.setItem(row, 4, downloadStatusItem)
        self.tableWidget.setItem(row, 5, downloadUrlItem)
        self.tableWidget.setItem(row, 6, filePathItem)
        self.tableWidget.setItem(row, 7, cancelItem)
        self.tableWidget.setCellWidget(row, 7, cancelButton)
        self.tableWidget.setItem(row, 8, retryItem)
        self.tableWidget.setCellWidget(row, 8, retryButton)
        self.tableWidget.setItem(row, 9, deleteItem)
        self.tableWidget.setCellWidget(row, 9, deleteButton)
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("open video")
        self.setGeometry(300, 300, 800, 600)
        self.setIcon()
        # showing a hint, or tooltip
        #        self.setToolTip("this is window")
        #        self.center()
        #        self.centralwidget = QWidget(self)
        #        self.setCentralWidget(self.centralwidget)

        self.add_menu()
        self.create_main_frame()

        self.setImageView()

        self.statusLabel = QLabel("showing progress")
        self.progressbar = QProgressBar()
        self.progressbar.setMinimum(0)
        self.progressbar.setMaximum(100)
        self.createStatusBar()
        self.init()

    def init(self):
        self.file_name = ""
        self.timer = QTimer()
        self.timer.timeout.connect(self.displayFrame)

    def create_main_frame(self):
        self.mainWidget = QWidget()
        self.setCentralWidget(self.mainWidget)

    def open_video(self):
        self.fname = QFileDialog.getOpenFileName()

        print(self.fname[0])

        self.cap = cv2.VideoCapture(self.fname[0])
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 600)

        self.timer.start()

    def add_menu(self):
        menubar = self.menuBar()
        menu = QMenu('File', self)  # title and parent
        file_action = QAction("Open file", self)  # title and parent
        file_action.setStatusTip("Select a file to play")
        file_action.triggered.connect(self.open_video)

        menu.addAction(file_action)
        menubar.addMenu(menu)
        menubar.setNativeMenuBar(False)
        self.statusBar().showMessage("Ready")

    def displayFrame(self):
        ret, frame = self.cap.read()
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        height, width, channel = frame.shape
        bytesPerLine = 3 * width
        qImg = QImage(frame.data, width, height, bytesPerLine,
                      QImage.Format_RGB888)
        self.imageView.setPixmap(QPixmap(qImg))

    def setImageView(self):
        layout = QVBoxLayout()
        self.imageView = QLabel("no video input")
        layout.addWidget(self.imageView)
        self.mainWidget.setLayout(layout)

    def setIcon(self):
        appIcon = QIcon("Screenshot from 2019-10-15 09-33-25.png")
        self.setWindowIcon(appIcon)

    def center(self):
        qRect = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qRect.moveCenter(centerPoint)
        self.move(qRect.topLeft())

    def createStatusBar(self):
        self.myStatus = QStatusBar()
        #        self.myStatus.showMessage("status bar is ready", 3000)
        self.progressbar.setValue(10)
        self.myStatus.addWidget(self.statusLabel, 1)
        self.myStatus.addWidget(self.progressbar, 2)
        self.setStatusBar(self.myStatus)
Ejemplo n.º 20
0
class mainScreen(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.driveLabel = QLabel('Serial Number:')
        self.sizeLabel = QLabel('Size:')
        self.statusLabel = QLabel('Status:')
        self.partitionLabel = QLabel('Partitions:')
        self.indexLabel = QLabel('Index:')
        self.checkLabel = QLabel('Master:')
        self.progress = QProgressBar()
        self.wipeButton = QPushButton('Wipe')
        self.cancelButton = QPushButton('Cancel')
        self.bottomStatus = QLabel('Ready to Wipe')
        self.refactor = QPushButton('Refactor')

        # TODO: Add a group box to make this look better
        # EDIT TODO: Use GUI application to build a really good looking app!
        # TODO: Add selection of wipe method, verification, and certificate output

        self.layout = QGridLayout()

        self.layout.addWidget(self.driveLabel, 0, 0, 1, 2)
        self.layout.addWidget(self.sizeLabel, 0, 3)
        self.layout.addWidget(self.statusLabel, 0, 5, 1, 2)
        self.layout.addWidget(self.partitionLabel, 0, 7)
        self.layout.addWidget(self.indexLabel, 0, 8)
        self.layout.addWidget(self.checkLabel, 0, 9)
        self.layout.addWidget(self.progress, 26, 0, 1, 10)
        self.layout.addWidget(self.wipeButton, 27, 2, 1, 2)
        self.layout.addWidget(self.cancelButton, 27, 4, 1, 2)
        self.layout.addWidget(self.bottomStatus, 28, 0, 1, 10)
        self.layout.addWidget(self.refactor, 27, 0, 1, 2)
        self.drivesSet = 0
        self.driveNames = []
        self.driveStatus = []
        self.driveSize = []
        self.drivePartitions = []
        self.driveIndex = []
        self.masterRadio = []
        self.master = self.getMaster()
        self.progressInt = 10
        for i in range(25):
            toAdd = QLabel('')
            self.driveNames.append(toAdd)
            toAdd2 = QLabel('')
            self.driveSize.append(toAdd2)
            toAdd3 = QLabel('')
            self.driveStatus.append(toAdd3)
            toAdd4 = QLabel('')
            self.drivePartitions.append(toAdd4)
            toAdd5 = QLabel('')
            self.driveIndex.append(toAdd5)

        self.setWindowTitle('Auto Kill Disk')
        #icon =
        #self.setWindowIcon()
        self.wipeButton.clicked.connect(self.startButtonClicked)
        self.refactor.clicked.connect(self.refactorDrives)

        self.worker = refactorThread()
        self.worker.refSig.connect(self.refactorDrives)
        self.worker.start()

    def addDrive(self, name, status, size, partitions, index):
        self.driveNames[self.drivesSet].setText(name)
        self.driveStatus[self.drivesSet].setText(status)
        self.driveSize[self.drivesSet].setText(size + ' GB')
        self.drivePartitions[self.drivesSet].setText(str(partitions))
        self.driveIndex[self.drivesSet].setText(str(index))
        toAdd = QRadioButton()
        self.masterRadio.append(toAdd)
        self.layout.addWidget(self.masterRadio[self.drivesSet],
                              self.drivesSet + 1, 9)
        if int(index) == int(self.master):
            self.masterRadio[self.drivesSet].setChecked(True)
        self.drivesSet += 1

    def addPayloadNames(self):
        for i in range(25):
            self.layout.addWidget(self.driveNames[i], i + 1, 0, 1, 2)
            self.layout.addWidget(self.driveStatus[i], i + 1, 5, 1, 2)
            self.layout.addWidget(self.driveSize[i], i + 1, 3)
            self.layout.addWidget(self.drivePartitions[i], i + 1, 7)
            self.layout.addWidget(self.driveIndex[i], i + 1, 8)

    def resetSpacing(self):
        self.layout.setContentsMargins(10, 10, 0, 10)

    def startButtonClicked(self):
        self.bottomStatus.setText('Are you sure you want to wipe?')
        self.confirmButton = QPushButton('Confirm')
        self.layout.addWidget(self.confirmButton, 27, 6, 1, 2)
        self.setLayout(self.layout)

        self.confirmButton.clicked.connect(self.getIndex)

    def setText(self):
        self.bottomStatus.setText('Ready to Wipe')

    def getIndex(self):
        self.confirmButton.deleteLater()
        self.bottomStatus.setText('Starting Wipe')
        self.indexToWipe = []
        self.serialToWipe = []
        for i in range(len(self.masterRadio)):
            if not self.masterRadio[i].isChecked():
                self.indexToWipe.append(self.index[i])
                self.serialToWipe.append(self.serial[i])
        if len(self.indexToWipe) == len(self.index):
            self.bottomStatus.setText('Error: No master drive selected!')
            self.refactorDrives()
            t = Timer(3, self.setText)
            t.start()
            return None
        elif len(self.indexToWipe) == 0:
            self.refactorDrives()
            self.bottomStatus.setText('No drives available to wipe!')
            t = Timer(3, self.setText)
            t.start()
        else:
            serialString = self.serialToWipe[0]
            for i in range(1, len(self.serialToWipe)):
                serialString += ', ' + self.serialToWipe[i]
            self.bottomStatus.setText('Wiping Drives:' + serialString)
            self.progress.setValue(self.progressInt)
            for i in range(len(self.masterRadio)):
                # TODO: Figure out which index is the master so we don't wipe it
                if self.masterRadio[i].isChecked():
                    self.driveStatus[i].setText('MASTER')
                else:
                    self.driveStatus[i].setText('WIPING')
            wipeDrives(self, self.indexToWipe)

    def refactorDrives(self):
        pythoncom.CoInitialize()
        for i in range(len(self.driveNames)):
            self.driveNames[i].setText('')
            self.driveStatus[i].setText('')
            self.driveSize[i].setText('')
            self.drivePartitions[i].setText('')
            self.driveIndex[i].setText('')
        for i in range(len(self.masterRadio)):
            self.masterRadio[i].deleteLater()
        self.setLayout(self.layout)
        del self.masterRadio
        self.masterRadio = []
        self.drivesSet = 0
        for i in range(25):
            toAdd = QLabel('')
            self.driveNames.append(toAdd)
            toAdd2 = QLabel('')
            self.driveSize.append(toAdd2)
            toAdd3 = QLabel('')
            self.driveStatus.append(toAdd3)
            toAdd4 = QLabel('')
            self.drivePartitions.append(toAdd4)
            toAdd5 = QLabel('')
            self.driveIndex.append(toAdd5)
        self.addPayloadNames()
        self.setLayout(self.layout)
        getDisks(self)
        self.addPayloadNames()
        self.setLayout(self.layout)

    def getMaster(self):
        exists = os.path.isfile('config.txt')
        if not exists:
            self.bottomStatus.setText(
                'Error: Config file not found. Defaulting to master drive with index 0.'
            )
            t = Timer(5, self.setText)
            t.start()
            return 0
        with open('config.txt', 'r') as fh:
            for line in fh:
                toSet = line.strip(' ')
        self.bottomStatus.setText('Loading complete')
        t = Timer(5, self.setText)
        t.start()
        return toSet
Ejemplo n.º 21
0
class DownloadDialog(QDialog):
    """Summary
        A dialog to download file and display progression 

    Attributes:
        source (QUrl): url of file to download
        destination (QDir): destination folder of downloaded file 
    """
    def __init__(self, parent=None):
        super().__init__(parent)

        self.file_label = QLabel()
        self.progress = QProgressBar()
        self.info_label = QLabel()
        self.btn_box = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        self.net = QNetworkAccessManager()

        font = QFont()
        font.setBold(True)
        self.file_label.setFont(font)

        v_layout = QVBoxLayout()
        v_layout.addWidget(self.file_label)
        v_layout.addWidget(self.progress)
        v_layout.addWidget(self.info_label)
        v_layout.addStretch()
        v_layout.addWidget(self.btn_box)

        self.btn_box.accepted.connect(self.close)
        self.btn_box.rejected.connect(self.cancel)
        self.btn_box.button(QDialogButtonBox.Ok).setVisible(False)

        self.setLayout(v_layout)

        self.setFixedSize(450, 150)
        self.setWindowTitle(self.tr("Download file"))

    def set_source(self, url: QUrl):
        """Set file url to download 
        
        Args:
            url (QUrl)
        """
        self.source = url
        self.file_label.setText(self.source.fileName())

    def set_destination(self, directory: QDir):
        """Set folder path where download the file 
        
        Args:
            directory (QDir)
        """
        self.destination = directory

    def start(self):
        """ Start downloading the file specify by set_source 
        """
        filepath = self.destination.absoluteFilePath(self.source.fileName())

        if QFile(filepath).exists():
            QFile.remove(filepath)

        self._file = QFile(filepath)

        # open the file to write in
        if self._file.open(QIODevice.WriteOnly):
            print("open file", filepath)
            # Create a Qt Request
            request = QNetworkRequest()
            request.setUrl(self.source)
            self.time = QTime.currentTime()
            self.reply = self.net.get(request)

            # Connect reply to different slots
            self.reply.downloadProgress.connect(self.on_update_progress)
            self.reply.finished.connect(self.on_finished)
            self.reply.error.connect(self.on_error)

    def cancel(self):
        """Cancel download
        """
        if hasattr(self, "reply"):
            self.reply.abort()
            self._file.remove()
            self.close()

    @Slot(int, int)
    def on_update_progress(self, read, total):
        """This methods is called by self.reply.downloadProgress signal 
        
        Args:
            read (int): Number of bytes readed
            total (int): Total bytes to download
        """
        if read <= 0:
            return

        if self.reply.error() != QNetworkReply.NoError:
            return

        self._file.write(self.reply.readAll())

        # compute speed
        duration = self.time.secsTo(QTime.currentTime()) + 1
        speed = read / duration
        remaining = (total - read) / speed

        h_remaining = QTime(0, 0, 0, 0).addSecs(remaining).toString()
        h_total = self.human_readable_bytes(total)
        h_read = self.human_readable_bytes(read)
        h_speed = self.human_readable_bytes(speed) + "/sec"

        self.info_label.setText(
            f"Time remaining {h_remaining} - {h_read} of {h_total} ({h_speed})"
        )

        # Set progression
        self.progress.setRange(0, total)
        self.progress.setValue(read)

    @Slot()
    def on_finished(self):
        """This methods is called by self.reply.finished signal
        """
        if self.reply.error() == QNetworkReply.NoError:
            self._file.close()
            self.reply.deleteLater()
            self.btn_box.button(QDialogButtonBox.Ok).setVisible(True)

    @Slot(QNetworkReply.NetworkError)
    def on_error(self, err: QNetworkReply.NetworkError):
        """This method is called by self.reply.error signal
        
        Args:
            err (QNetworkReply.NetworkError)
        """
        self.reply.deleteLater()

    def human_readable_bytes(self, num, suffix="B"):
        for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
            if abs(num) < 1024.0:
                return "%3.1f%s%s" % (num, unit, suffix)
            num /= 1024.0
        return "%.1f%s%s" % (num, "Yi", suffix)
class IpSubnetCalculation(QWidget):
    def __init__(self):
        super(IpSubnetCalculation, self).__init__()

        # Use language settings
        self.ml = ManageLng()

        # App attributes
        self.network_ip = None
        self.needed_networks = None
        self.subnet_bits = None
        self.default_networkbits = None
        self.calculation_worker = None

        main_layout = QVBoxLayout()
        main_layout.setSpacing(10)
        main_layout.setAlignment(Qt.AlignTop)
        self.setLayout(main_layout)

        top_bar = QGridLayout()

        # Left, top, right and bottom margins
        top_bar.setContentsMargins(40, 15, 40, 15)
        top_bar.setHorizontalSpacing(40)
        main_layout.addLayout(top_bar)

        self.starting_network_address_label = QLabel(self.ml.get_tr_text("tab_ipsubnet_starting_net"))
        self.number_of_subnets_label = QLabel(self.ml.get_tr_text("tab_ipsubnet_required_subnet_num"))

        self.starting_network_address_input = QLineEdit()
        self.starting_network_address_input.returnPressed.connect(self.calculation_action)
        self.number_of_subnets_input = QLineEdit()
        self.number_of_subnets_input.returnPressed.connect(self.calculation_action)

        top_bar.addWidget(self.starting_network_address_label, 0, 0)
        top_bar.addWidget(self.starting_network_address_input, 0, 1)
        top_bar.addWidget(self.number_of_subnets_label, 1, 0)
        top_bar.addWidget(self.number_of_subnets_input, 1, 1)

        self.calculation_button = QPushButton(self.ml.get_tr_text("tab_ipsubnet_calc_btn"))
        self.calculation_button.clicked.connect(self.calculation_action)
        self.calculation_button.setIcon(QIcon("static/images/get_info.png"))
        main_layout.addWidget(self.calculation_button, alignment=Qt.AlignCenter)

        self.table = QTableWidget()
        self.table.itemDoubleClicked.connect(copy_text_action)
        self.table.setColumnCount(6)

        self.table_column_names = [self.ml.get_tr_text("table_column_network_add"),
                                   self.ml.get_tr_text("table_column_ip_range"),
                                   self.ml.get_tr_text("table_column_broadcast_add"),
                                   self.ml.get_tr_text("table_column_subnet_mask"),
                                   self.ml.get_tr_text("table_column_prefix"),
                                   self.ml.get_tr_text("table_column_addressable_host")]

        self.table.setHorizontalHeaderLabels(self.table_column_names)

        # Automatic resizing of the columns to the content
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)

        # Set table text align of vertical header
        self.table.verticalHeader().setDefaultAlignment(Qt.AlignCenter)

        # Fixed height of table rows
        self.table.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)

        main_layout.addWidget(self.table)

        # Bottom bar
        bottom_bar = QHBoxLayout()

        # Create progressbar
        self.progressbar = QProgressBar()
        self.progressbar.setVisible(False)

        # Create cancel button
        self.cancel_btn = QPushButton(self.ml.get_tr_text("tab_ipsubnet_cancel_btn"))
        self.cancel_btn.setVisible(False)
        self.cancel_btn.clicked.connect(self.terminate_calculation)

        bottom_bar.addWidget(self.progressbar)
        bottom_bar.addWidget(self.cancel_btn)
        main_layout.addLayout(bottom_bar)

    def check_input(self):

        # If the starting network address is empty
        if is_empty(self.starting_network_address_input.text()):
            PopupWindow("warning",
                        self.ml.get_tr_text("tab_ipsubnet_warning01"),
                        self.starting_network_address_input)
            return False
        else:

            # If the starting network address is incorrect
            if not is_correct_network_address(self.starting_network_address_input.text()):
                PopupWindow("warning",
                            self.ml.get_tr_text("tab_ipsubnet_warning02"),
                            self.starting_network_address_input)
                return False

        # If number of subnets is empty
        if is_empty(self.number_of_subnets_input.text()):
            PopupWindow("warning",
                        self.ml.get_tr_text("tab_ipsubnet_warning03"),
                        self.number_of_subnets_input)
            return False
        else:

            # If number of subnets is incorrect
            if not is_correct_number_of_subnets(self.number_of_subnets_input.text()):
                PopupWindow("warning",
                            self.ml.get_tr_text("tab_ipsubnet_warning04"),
                            self.number_of_subnets_input)
                return False

        self.storing_input_data()

        # If max addressable host least two and have least one needed network
        if self.get_max_addressable_hosts() >= 2 and int(self.needed_networks) >= 1:
            return True
        else:

            # Unreal subnet number
            PopupWindow("warning",
                        self.ml.get_tr_text("tab_ipsubnet_warning05"),
                        self.number_of_subnets_input)
            return False

    def storing_input_data(self):
        self.network_ip = self.starting_network_address_input.text()
        self.needed_networks = self.number_of_subnets_input.text()
        self.subnet_bits = int(log2(int(power_bit_length(int(self.needed_networks)))))

    def get_max_addressable_hosts(self):
        self.default_networkbits = 32 - get_32bit_format(self.get_starting_network_default_mask()).count("0")
        return pow(2, ((self.default_networkbits + self.subnet_bits) * "1").ljust(32, "0").count("0")) - 2

    def get_starting_network_default_mask(self):
        first_octet = int(self.network_ip.split(".")[0])

        if 1 <= first_octet < 128:
            return "255.0.0.0"
        elif 128 <= first_octet < 192:
            return "255.255.0.0"
        elif 192 <= first_octet < 224:
            return "255.255.255.0"

    def calculation_action(self):
        if self.check_input():
            self.table.setRowCount(0)
            self.progressbar.setValue(0)
            self.progressbar.setMaximum(int(self.number_of_subnets_input.text()))
            self.calculation_worker = CalculationWorker(self)
            self.calculation_worker.setTerminationEnabled(True)
            self.calculation_worker.subnet_calculated.connect(self.subnet_calculated)
            self.calculation_worker.calculation_finished.connect(self.calculation_finished)
            self.progressbar.setVisible(True)
            self.cancel_btn.setVisible(True)
            self.calculation_worker.start()

    def subnet_calculated(self, row, subnet):
        self.table.insertRow(row)
        column = 0
        for subnet_item in subnet.items():
            self.table.setItem(row, column, TableItem(str(subnet_item[1])))
            column += 1
        self.progressbar.setValue(row + 1)

    def calculation_finished(self):
        self.progressbar.setVisible(False)
        self.cancel_btn.setVisible(False)
        self.progressbar.setValue(0)

    def terminate_calculation(self):
        if self.calculation_worker.isRunning():
            self.calculation_worker.terminate()
            self.calculation_worker.wait()
            self.progressbar.setVisible(False)
            self.cancel_btn.setVisible(False)
            self.progressbar.setValue(0)

    def re_translate_ui(self, lang):
        self.ml = ManageLng(lang)

        self.starting_network_address_label.setText(self.ml.get_tr_text("tab_ipsubnet_starting_net"))
        self.number_of_subnets_label.setText(self.ml.get_tr_text("tab_ipsubnet_required_subnet_num"))
        self.calculation_button.setText(self.ml.get_tr_text("tab_ipsubnet_calc_btn"))

        self.table_column_names = [self.ml.get_tr_text("table_column_network_add"),
                                   self.ml.get_tr_text("table_column_ip_range"),
                                   self.ml.get_tr_text("table_column_broadcast_add"),
                                   self.ml.get_tr_text("table_column_subnet_mask"),
                                   self.ml.get_tr_text("table_column_prefix"),
                                   self.ml.get_tr_text("table_column_addressable_host")]

        self.table.setHorizontalHeaderLabels(self.table_column_names)
        self.cancel_btn.setText(self.ml.get_tr_text("tab_ipsubnet_cancel_btn"))
Ejemplo n.º 23
0
class Ventana(QtWidgets.QWidget):
    '''Constructor de la clase'''
    def __init__(self, vectorizer, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.vectorizer = vectorizer  #Variable para el entrenamiento de algoritmos
        #resultados de los mejores entrenamientos
        self.resultadoEntrenamiento = {}
        self.layoutReporte = QVBoxLayout()
        self.svcTitulo = QLabel(self)
        self.layoutReporte.addWidget(self.svcTitulo)
        self.svcF1Label = QLabel(self)
        self.layoutReporte.addWidget(self.svcF1Label)
        self.svcRecallLabel = QLabel(self)
        self.layoutReporte.addWidget(self.svcRecallLabel)
        self.svcPrecisionLabel = QLabel(self)
        self.layoutReporte.addWidget(self.svcPrecisionLabel)
        self.svcAccuracyLabel = QLabel(self)
        self.layoutReporte.addWidget(self.svcAccuracyLabel)
        self.svcMatrix = QLabel(self)
        self.layoutReporte.addWidget(self.svcMatrix)
        self.mlpTitulo = QLabel(self)
        self.layoutReporte.addWidget(self.mlpTitulo)
        self.mlpF1Label = QLabel(self)
        self.layoutReporte.addWidget(self.mlpF1Label)
        self.mlpRecallLabel = QLabel(self)
        self.layoutReporte.addWidget(self.mlpRecallLabel)
        self.mlpPrecisionLabel = QLabel(self)
        self.layoutReporte.addWidget(self.mlpPrecisionLabel)
        self.mlpAccuracyLabel = QLabel(self)
        self.layoutReporte.addWidget(self.mlpAccuracyLabel)
        self.mlpMatrix = QLabel(self)
        self.layoutReporte.addWidget(self.mlpMatrix)
        self.knnTitulo = QLabel(self)
        self.layoutReporte.addWidget(self.knnTitulo)
        self.knnF1Label = QLabel(self)
        self.layoutReporte.addWidget(self.knnF1Label)
        self.knnRecallLabel = QLabel(self)
        self.layoutReporte.addWidget(self.knnRecallLabel)
        self.knnPrecisionLabel = QLabel(self)
        self.layoutReporte.addWidget(self.knnPrecisionLabel)
        self.knnAccuracyLabel = QLabel(self)
        self.layoutReporte.addWidget(self.knnAccuracyLabel)
        self.knnMatrix = QLabel(self)
        self.layoutReporte.addWidget(self.knnMatrix)
        self.nbTitulo = QLabel(self)
        self.layoutReporte.addWidget(self.nbTitulo)
        self.nbF1Label = QLabel(self)
        self.layoutReporte.addWidget(self.nbF1Label)
        self.nbRecallLabel = QLabel(self)
        self.layoutReporte.addWidget(self.nbRecallLabel)
        self.nbPrecisionLabel = QLabel(self)
        self.layoutReporte.addWidget(self.nbPrecisionLabel)
        self.nbAccuracyLabel = QLabel(self)
        self.layoutReporte.addWidget(self.nbAccuracyLabel)
        self.nbMatrix = QLabel(self)
        self.layoutReporte.addWidget(self.nbMatrix)
        self.layoutClass = QVBoxLayout()
        self.svcClass = QLabel(self)
        self.layoutClass.addWidget(self.svcClass)
        self.mlpClass = QLabel(self)
        self.layoutClass.addWidget(self.mlpClass)
        self.knnClass = QLabel(self)
        self.layoutClass.addWidget(self.knnClass)
        self.nbClass = QLabel(self)
        self.layoutClass.addWidget(self.nbClass)
        self.layoutEntrenamiento = QHBoxLayout()
        #Botones del menú principal
        self.buttonBloqueFile = QPushButton("&Analizar Bloque desde archivo",
                                            self)
        self.buttonBloqueTwitter = QPushButton(
            "&Analizar Bloque desde Twitter.com", self)
        self.buttonUnTweet = QPushButton("&Analizar un Tweet", self)
        self.buttonEntrenar = QPushButton("&Entrenar algoritmos", self)
        #Añadir los botones al layout del menú
        self.layoutMenu = QHBoxLayout()
        self.layoutMenu.addWidget(self.buttonBloqueFile)
        self.layoutMenu.addWidget(self.buttonBloqueTwitter)
        self.layoutMenu.addWidget(self.buttonUnTweet)
        self.layoutMenu.addWidget(self.buttonEntrenar)
        #Layout donde irían los resultados
        self.layoutWidget = QVBoxLayout()
        self.infoLayout = QVBoxLayout(
        )  #Layout que muestra todos los widgets de mostrar un sólo tweet
        #Variables para mostrar un sólo tweet
        self.tituloLabel = QLabel(self)  #Etiqueta que muestra el título
        self.infoLayout.addWidget(self.tituloLabel)
        self.tweetLabel = QLabel(
            self)  #Etiqueta que muestra el texto del tweet
        self.infoLayout.addWidget(self.tweetLabel)
        self.nerLabel = QLabel(self)  #Etiqueta que muestra el título de NER
        self.infoLayout.addWidget(self.nerLabel)
        self.nonerLabel = QLabel(
            self)  #Etiqueta que muestra el aviso de que no hay NER
        self.infoLayout.addWidget(self.nonerLabel)
        self.tabla = QTableWidget()  #Tabla que muestra los resultados del NER
        self.infoLayout.addWidget(self.tabla)
        self.claLabel = QLabel(
            self
        )  #Etiqueta que muestra el título que precede a la tabla de sentimientos
        self.infoLayout.addWidget(self.claLabel)
        self.tablaSent = QTableWidget(
        )  #Tabla que muestra los sentimientos de cada algoritmo
        self.infoLayout.addWidget(self.tablaSent)
        #Variables para mostrar en entrenamiento
        self.entrenamientoLabel = QLabel(self)
        #Variables para la barra de progreso
        self.progressBarUnTweet = QProgressBar(self)
        self.progressLayout = QVBoxLayout()
        self.progresLabel = QLabel(self)
        self.progressLayout.addWidget(self.progresLabel)
        self.progressLayout.addWidget(self.progressBarUnTweet)
        #Elementos para NER
        self.nerLayout = QVBoxLayout()
        self.layoutWidget.addLayout(self.nerLayout)
        self.botones = []
        #Variables para la selección en cargar datos de twitter
        self.consultaText = ""
        self.consultaTweets = 0
        self.nerCantidadValor = 0
        #diálogo de archivo
        self.dialogo1 = QFileDialog(self)
        #Creación del layout principal que anida el resto de layouts
        self.layoutPrincipal = QVBoxLayout()
        self.layoutPrincipal.addLayout(self.layoutMenu)
        self.layoutPrincipal.addLayout(self.progressLayout)
        self.layoutPrincipal.addStretch()
        self.layoutPrincipal.addLayout(self.layoutWidget)
        self.setLayout(self.layoutPrincipal)
        #Diálogo para configurar parámetros de bloque de Twitter
        self.dialogConsulta = QInputDialog(self)
        self.dialogTweets = QInputDialog(self)
        self.nerCantidad = QInputDialog(self)
        # Conectar a analizarUnTweet:
        self.buttonUnTweet.clicked.connect(self.analizarUnTweet)
        # Conectar a entrenar_algoritmos
        self.buttonEntrenar.clicked.connect(self.entrenar_algoritmos)
        # Conectar a cargar datos de Twitter
        self.buttonBloqueTwitter.clicked.connect(self.cuadroDialogo)
        # Conectar a cargar datos de archivo
        self.buttonBloqueFile.clicked.connect(self.analizarDeArchivo)

    '''Reinicia el estado de la barra de estado'''

    def reiniciarEstado(self, maximo):
        self.progressBarUnTweet.reset()
        self.progressBarUnTweet.setMaximum(maximo)
        self.progressBarUnTweet.setMinimum(0)

    '''Actualiza el estado de la barra de estado y de la etiqueta de estado'''

    def actualizarEstado(self, porcentaje, etiqueta):
        self.progressBarUnTweet.setValue(porcentaje)
        self.progresLabel.setText(etiqueta)

    '''Función que oculta todos los widgets que hay en el layout que se le pasa por parámetro'''

    def limpiarLayout(self, layout):
        for i in reversed(range(layout.count())):
            layout.itemAt(i).widget().hide()

    '''Función que muestra todos los widgets que hay en el layout que se le pasa por parámetro'''

    def mostrarLayout(self, layout):
        for i in range(layout.count()):
            layout.itemAt(i).widget().show()

    '''Función que muestra los cuadros de diálogo para analizar un bloque de tweets desde twitter.com'''

    def cuadroDialogo(self):
        self.consultaText = self.dialogConsulta.getText(
            self, "Consulta de Twitter", "¿Sobre qué quieres buscar?")
        self.consultaTweets = self.dialogTweets.getInt(
            self, "Cuántos twits quieres usar",
            "La cantidad se multiplica por 100")
        self.nerCantidadValor = self.nerCantidad.getInt(
            self, "Cuántos twits quieres usar en NER",
            "Tweets que se usarán para NER")
        self.cargar_datos_de_twitter()

    '''Función que muestra un gráfico con los datos pasados por parámetros'''

    def mostrarUnGraph(self, entidad, dataframe, estado):
        if estado == 2:
            dataframe = dataframe[dataframe['text'].str.contains(entidad)]
        dataframe = self.tokenizar(dataframe)
        test_data = dataframe['final'][
            -dataframe.size:]  #saca sólo los últimos 100
        test_data = list(test_data.apply(' '.join))
        test_vectors = self.vectorizer.transform(test_data)
        self.mostrar_graph(self.predecir_Naive_Bayes(test_vectors, entidad),
                           self.predecir_SVC(test_vectors, entidad),
                           self.predecir_KNN(test_vectors, entidad),
                           self.predecir_MLP(test_vectors, entidad))

    '''Función que carga todos los botones correspondientes a las entidades reconocidas'''

    def buttonsNER(self, resultadoNER, df2):
        self.limpiarLayout(self.nerLayout)
        self.botones = []
        self.botones.append(QPushButton('Todas las entidades', self))
        self.nerLayout.addWidget(self.botones[-1])
        self.botones[-1].clicked.connect(
            lambda x='Todas las entidades': self.mostrarUnGraph(x, df2, 1))
        for i in resultadoNER:
            for j in i:
                self.botones.append(QPushButton(
                    j[0], self))  #Creo el botón y lo añado a la lista
                self.nerLayout.addWidget(
                    self.botones[-1])  #Añado el botón al layout
                self.botones[-1].clicked.connect(lambda x=j[
                    0]: self.mostrarUnGraph(x, df2, 2))  #Conecto el botón

    '''Función para configurar todos los datos de la API de Twitter'''

    def configurarAPITwitter(self, buscar, restoConsulta):
        consumer_key = 'ynSB0dFvqPl3xRU7AmYk39rGT'
        consumer_secret = '6alIXTKSxf0RE57QK3fDQ8dxdvlsVr1IRsHDZmoSlMx96YKBFD'
        access_token = '966591013182722049-BVXW14Hf5s6O2oIwS3vtJ3S3dOsKLbY'
        access_token_secret = '829DTKPjmwsSytmp1ky9fMCJkjV0LZ04TbL9oqHGV6cDm'
        q = self.consultaText[0] + restoConsulta  #parámetros de la consulta
        url = 'https://api.Twitter.com/1.1/search/tweets.json'
        pms = {'q': q, 'count': 100, 'lang': 'en', 'result_type': 'recent'}
        auth = OAuth1(consumer_key, consumer_secret, access_token,
                      access_token_secret)
        return {'auth': auth, 'pms': pms, 'url': url}

    '''Función que configura la base de datos y realiza el proceso de paginación'''

    def paginacionMongo(self, url, pms, auth, nombre, colection, cliente,
                        paginas):
        #inicialización de la base de datos para cargar los datos
        database_name = nombre
        collection_name = colection
        client = MongoClient(cliente)
        db = client[database_name]
        collection = db[collection_name]
        #Paginación (carga de 100 en 100 datos)
        pages_counter = 0
        number_of_pages = paginas
        while pages_counter < number_of_pages:
            pages_counter += 1
            res = requests.get(url, params=pms, auth=auth)
            tweets = res.json()
            ids = [i['id'] for i in tweets['statuses']]
            pms['max_id'] = min(ids) - 1
            collection.insert_many(tweets['statuses'])
        return collection

    '''Función para cargar datos de twitter directamente, lo almacena en una base de datos y lo devuelve en un dataframe. Se usa sólo para ver los resultados. No para entrenar.'''

    def cargar_datos_de_twitter(self):
        self.limpiarLayout(self.infoLayout)
        datosAPI = self.configurarAPITwitter(
            self.consultaText[0], ' -filter:retweets AND -filter:replies')
        collection = self.paginacionMongo(datosAPI['url'], datosAPI['pms'],
                                          datosAPI['auth'], "baseDeDatos",
                                          "coleccion",
                                          'mongodb://localhost:27017/',
                                          self.consultaTweets[0])
        #Pasar de la base de datos a un dataframe
        documents = []
        for doc in collection.find().skip(collection.count() -
                                          self.consultaTweets[0] * 100):
            documents.append(doc)
        df = pd.DataFrame(documents)
        #Limpieza de datos
        df = self.limpieza_de_datos_de_twitter(df)
        df2 = pd.DataFrame(data=df['text'][-self.consultaTweets[0] * 100:])
        dfNER = pd.DataFrame(data=df['text'])
        dfNER = self.tokenizar(dfNER)
        anNER = dfNER['final'][
            -self.nerCantidadValor[0]:]  #saca sólo los últimos 5
        resultadoNER = self.usar_NER(anNER, 3)
        self.buttonsNER(resultadoNER, df2)

    '''Función que analiza twits sacados de un archivo a elegir por el usuario'''

    def analizarDeArchivo(self):
        filename = self.dialogo1.getOpenFileName(
            self, "Selecciona el fichero a analizar", "/")
        filename = filename[0].split("/")
        filename = filename[-1]
        self.nerCantidadValor = self.nerCantidad.getInt(
            self, "Cuántos twits quieres usar en NER",
            "Tweets que se usarán para NER")
        self.reiniciarEstado(100)
        #filename = input("\tEscribe el nombre del fichero donde se encuentra el bloque de tweets: ") or 'bloque.csv'
        dataset = pd.read_csv(filename)
        df3 = pd.DataFrame(data=dataset['text'])
        dfNER = pd.DataFrame(data=dataset['text'])
        self.actualizarEstado(20, "Tokenizando")
        dfNER = self.tokenizar(dfNER)
        anNER = dfNER['final'][-self.nerCantidadValor[0]:]
        self.actualizarEstado(30, "Analizando NER")
        resultadoNER = self.usar_NER(anNER, 3)
        self.reiniciarEstado(100)
        self.actualizarEstado(90, "Distribuyendo botones NER")
        self.buttonsNER(resultadoNER, df3)
        self.actualizarEstado(100, "FINALIZADO")

    '''Función que analiza un tweet individual sacado de twitter.com'''

    def analizarUnTweet(self):
        #Barra de progreso
        self.consultaText = self.dialogConsulta.getText(
            self, "Consulta de Twitter", "¿Sobre qué quieres buscar?")
        self.reiniciarEstado(10)
        #self.layoutProgressBar.addWidget(self.progressBarUnTweet)
        datosAPI = self.configurarAPITwitter(
            self.consultaText[0], ' -filter:retweets AND -filter:replies')
        self.progressBarUnTweet.setValue(2)
        self.progresLabel.setText("Iniciando base de datos")
        collection = self.paginacionMongo(datosAPI['url'], datosAPI['pms'],
                                          datosAPI['auth'], "baseDeDatos",
                                          "coleccion",
                                          'mongodb://localhost:27017/', 1)
        self.progressBarUnTweet.setValue(3)
        self.progresLabel.setText("Guardando tweets en base de datos")
        #Pasar de la base de datos a un dataframe
        documents = []
        for doc in collection.find().skip(collection.count() - 10):
            documents.append(doc)
        df = pd.DataFrame(documents)
        mostrar = pd.DataFrame(documents)
        self.progressBarUnTweet.setValue(4)
        #Limpieza de datos
        df = self.limpieza_de_datos_de_twitter(df)
        df2 = pd.DataFrame(data=df['text'][-1:])
        dfNER = pd.DataFrame(data=df['text'][-1:])
        tweet = mostrar['text'][-1:]
        dfNER = self.tokenizar(dfNER)
        anNER = dfNER['final'][-1:]
        resultadoNER = self.usar_NER(anNER, 10)
        self.progressBarUnTweet.setValue(5)
        self.progresLabel.setText("Limpiando datos")
        df2 = self.tokenizar(df2)
        test_data = df2['final']
        test_data = list(test_data.apply(' '.join))
        test_vectors = self.vectorizer.transform(test_data)
        self.progressBarUnTweet.setValue(6)
        self.progresLabel.setText("Transformando datos datos")
        nb = self.predecir_Naive_Bayes(test_vectors, 'nada')
        self.progressBarUnTweet.setValue(7)
        self.progresLabel.setText("Naive Bayes")
        svc = self.predecir_SVC(test_vectors, 'nada')
        self.progressBarUnTweet.setValue(8)
        self.progresLabel.setText("SVC")
        knn = self.predecir_KNN(test_vectors, 'nada')
        self.progressBarUnTweet.setValue(9)
        self.progresLabel.setText("KNN")
        mlp = self.predecir_MLP(test_vectors, 'nada')
        self.progressBarUnTweet.setValue(10)
        self.progresLabel.setText("FINALIZADO")
        self.tituloLabel.setText(
            "<h1>ANÁLISIS DE SENTIMIENTOS EN UN TWEET INDIVIDUAL</h1>")
        self.tweetLabel.setText("<b>TWEET:</b> " + tweet.to_string())
        self.nerLabel.setText("<h2>Entidades</h2>")
        if resultadoNER == 0:
            self.nonerLabel.setText(
                "<b><font size=" + "3" + " color=" + "red" +
                ">NO SE RECONOCIERON LAS ENTIDADES</font></b>")
            self.tabla.clear()
        else:
            self.nonerLabel.setText(" ")
            self.tabla.setVerticalHeaderLabels(["prueba", "prueba2"])
            self.tabla.horizontalHeader().hide()
            self.tabla.verticalHeader().hide()
            self.tabla.setColumnCount(1)
            fila = 0
            filasTotales = 0
            for i in resultadoNER:
                filasTotales = len(i) + filasTotales
                self.tabla.setRowCount(filasTotales)
                for j in i:
                    columna1 = QTableWidgetItem(j[0])
                    self.tabla.setItem(fila, 0, columna1)
                    fila = fila + 1
        self.claLabel.setText("<h2>Clasificación de sentimientos</h2>")
        self.tablaSent.setColumnCount(2)
        self.tablaSent.setRowCount(4)
        self.tablaSent.horizontalHeader().hide()
        self.tablaSent.verticalHeader().hide()
        self.tablaSent.setVerticalHeaderLabels(['Clasificador', 'Resultado'])
        self.tablaSent.setItem(0, 0, QTableWidgetItem("Naive Bayes"))
        if nb[1][0] == 1:
            self.tablaSent.setItem(0, 1, QTableWidgetItem("Positivo"))
        elif nb[1][1] == 1:
            self.tablaSent.setItem(0, 1, QTableWidgetItem("Neutro"))
        elif nb[1][2] == 1:
            self.tablaSent.setItem(0, 1, QTableWidgetItem("Negativo"))
        self.tablaSent.setItem(1, 0, QTableWidgetItem("Clasificador SVC"))
        if svc[1][0] == 1:
            self.tablaSent.setItem(1, 1, QTableWidgetItem("Positivo"))
        elif svc[1][1] == 1:
            self.tablaSent.setItem(1, 1, QTableWidgetItem("Neutro"))
        elif svc[1][2] == 1:
            self.tablaSent.setItem(1, 1, QTableWidgetItem("Negativo"))
        self.tablaSent.setItem(2, 0,
                               QTableWidgetItem("Clasificador K-Neighbors"))
        if knn[1][0] == 1:
            self.tablaSent.setItem(2, 1, QTableWidgetItem("Positivo"))
        elif knn[1][1] == 1:
            self.tablaSent.setItem(2, 1, QTableWidgetItem("Neutro"))
        elif knn[1][2] == 1:
            self.tablaSent.setItem(2, 1, QTableWidgetItem("Negativo"))
        self.tablaSent.setItem(3, 0, QTableWidgetItem("Clasificador MLP"))
        if mlp[1][0] == 1:
            self.tablaSent.setItem(3, 1, QTableWidgetItem("Positivo"))
        elif mlp[1][1] == 1:
            self.tablaSent.setItem(3, 1, QTableWidgetItem("Neutro"))
        elif mlp[1][2] == 1:
            self.tablaSent.setItem(3, 1, QTableWidgetItem("Negativo"))
        self.layoutWidget.addLayout(self.infoLayout)
        self.mostrarLayout(self.infoLayout)

    '''Función que tokeniza los datos de un tweet, eliminando las stopwords y los caracteres especiales'''

    def tokenizar(self, df):
        #TOKENIZATION inicial para NER
        df.loc[:, 'tokens'] = df['text'].apply(TweetTokenizer().tokenize)
        #STOPWORDS
        stopwords_vocabulary = stopwords.words('english')  #estará en español?
        df.loc[:, 'stopwords'] = df['tokens'].apply(
            lambda x: [i for i in x if i.lower() not in stopwords_vocabulary])
        #SPECIAL CHARACTERS AND STOPWORDS REMOVAL
        punctuations = list(string.punctuation)
        df.loc[:, 'punctuation'] = df['stopwords'].apply(
            lambda x: [i for i in x if i not in punctuations])
        df.loc[:, 'digits'] = df['punctuation'].apply(
            lambda x: [i for i in x if i[0] not in list(string.digits)])
        df.loc[:, 'final'] = df['digits'].apply(
            lambda x: [i for i in x if len(i) > 1])
        return df

    '''Función que recibe un dataframe con tweets de twitter y los deja preparados para ser tokenizados'''

    def limpieza_de_datos_de_twitter(self, df):
        df['tweet_source'] = df['source'].apply(
            lambda x: BeautifulSoup(x).get_text())
        devices = list(
            set(df[df['tweet_source'].str.startswith('Twitter')]
                ['tweet_source']))
        df = df[df['tweet_source'].isin(devices)]
        return df

    '''Funciones de predicción de los diferentes algoritmos para los diferentes modelos'''

    def predecir_Naive_Bayes(self, test_vectors, it):
        mod = MultinomialNB()
        file = open('NaiveBayes', 'rb')
        mod = load(file)
        result = mod.predict(test_vectors)
        pos = len(
            result[result == 4])  #guardamos la cantidad de tweets positivos
        neg = len(
            result[result == 0])  #guardamos la cantidad de tweets negativos
        neu = len(
            result[result == 2])  #guardamos la cantidad de tweets neutros
        y = [
            pos, neu, neg
        ]  # vector de la cantidad de tweets positivos, negativos y neutros
        return (it, y)

    def predecir_SVC(self, test_vectors, it):
        mod = SVC()
        file = open('Svc', 'rb')
        mod = load(file)
        result = mod.predict(test_vectors)
        pos = len(
            result[result == 4])  #guardamos la cantidad de tweets positivos
        neg = len(
            result[result == 0])  #guardamos la cantidad de tweets negativos
        neu = len(
            result[result == 2])  #guardamos la cantidad de tweets neutros
        y = [
            pos, neu, neg
        ]  # vector de la cantidad de tweets positivos, negativos y neutros
        return (it, y)

    def predecir_KNN(self, test_vectors, it):
        mod = KNeighborsClassifier()
        file = open('Knn', 'rb')
        mod = load(file)
        result = mod.predict(test_vectors)
        pos = len(
            result[result == 4])  #guardamos la cantidad de tweets positivos
        neg = len(
            result[result == 0])  #guardamos la cantidad de tweets negativos
        neu = len(
            result[result == 2])  #guardamos la cantidad de tweets neutros
        y = [
            pos, neu, neg
        ]  # vector de la cantidad de tweets positivos, negativos y neutros
        return (it, y)

    def predecir_MLP(self, test_vectors, it):
        mod = MLPClassifier()
        file = open('Mlp', 'rb')
        mod = load(file)
        result = mod.predict(test_vectors)
        pos = len(
            result[result == 4])  #guardamos la cantidad de tweets positivos
        neg = len(
            result[result == 0])  #guardamos la cantidad de tweets negativos
        neu = len(
            result[result == 2])  #guardamos la cantidad de tweets neutros
        y = [
            pos, neu, neg
        ]  # vector de la cantidad de tweets positivos, negativos y neutros
        return (it, y)

    '''Función que muestra los gráficos utilizando los plots de python'''

    def mostrar_graph(self, NB, SVC, KNN, MLP):
        plt.figure(figsize=(9, 7))
        #Naive Bayes
        plt.subplot(221)
        plt.title("NB para la entidad " + NB[0])
        plt.ylabel('tweets')
        plt.xticks(range(len(NB[1])), ['positive', 'neutral', 'negative'])
        plt.bar(range(len(NB[1])),
                height=NB[1],
                width=0.75,
                align='center',
                alpha=0.8)
        #SVC
        plt.subplot(222)
        plt.title("SVC para la entidad " + SVC[0])
        plt.ylabel('tweets')
        plt.xticks(range(len(SVC[1])), ['positive', 'neutral', 'negative'])
        plt.bar(range(len(SVC[1])),
                height=SVC[1],
                width=0.75,
                align='center',
                alpha=0.8)
        #KNN
        plt.subplot(223)
        plt.title("KNN para la entidad " + KNN[0])
        plt.ylabel('tweets')
        plt.xticks(range(len(KNN[1])), ['positive', 'neutral', 'negative'])
        plt.bar(range(len(KNN[1])),
                height=KNN[1],
                width=0.75,
                align='center',
                alpha=0.8)
        #MLP
        plt.subplot(224)
        plt.title("MLP para la entidad " + MLP[0])
        plt.ylabel('tweets')
        plt.xticks(range(len(MLP[1])), ['positive', 'neutral', 'negative'])
        plt.bar(range(len(MLP[1])),
                height=MLP[1],
                width=0.75,
                align='center',
                alpha=0.8)
        plt.show()

    '''Función que utiliza NER para detectar entidades.'''

    def usar_NER(self, tweetys, n):
        self.reiniciarEstado(len(tweetys) * 10)
        self.actualizarEstado(1, "ANALIZANDO ENTIDADES: ")
        st = StanfordNERTagger(
            r'C:\Users\Servicio Técnico\Documents\stanford-ner-2018-02-27\classifiers\english.all.3class.distsim.crf.ser.gz'
        )
        #st = StanfordNERTagger('/Users/jonas/stanford-ner-2018-02-27/classifiers/english.all.3class.distsim.crf.ser.gz')
        #Recuerda de que cambia para el mac que es donde vas a realizar la presentación
        entities = []
        tindice = 0
        for r in tweetys:
            PySide2.QtWidgets.QApplication.processEvents()
            lst_tags = st.tag(
                r)  #no tengo que hacer el split porque ya está hecho?
            for tup in lst_tags:
                PySide2.QtWidgets.QApplication.processEvents()
                self.actualizarEstado(tindice,
                                      "ANALIZANDO ENTIDADES EN: " + str(r))
                tindice = tindice + 1
                if (tup[1] != 'O'):
                    entities.append(tup)
        df_entities = pd.DataFrame(entities)
        self.actualizarEstado(len(tweetys) * 10, "FINALIZADO")
        if df_entities.size > 0:
            df_entities.columns = ["word", "ner"]
            #Organizaciones
            organizations = df_entities[df_entities['ner'].str.contains(
                "ORGANIZATION")]
            cnt = Counter(organizations['word'])
            organizaciones = cnt.most_common(n)
            #Personas
            person = df_entities[df_entities['ner'].str.contains("PERSON")]
            cnt_person = Counter(person['word'])
            personas = cnt_person.most_common(n)
            #Localizaciones
            locations = df_entities[df_entities['ner'].str.contains(
                "LOCATION")]
            cnt_location = Counter(locations['word'])
            lugares = cnt_location.most_common(n)
            return (organizaciones, personas, lugares)
        else:
            return 0

    '''Función que muestra el reporte del entrenamiento'''

    def mostrarReporte(self):
        self.limpiarLayout(self.layoutClass)
        self.limpiarLayout(self.layoutReporte)
        self.limpiarLayout(self.layoutEntrenamiento)

        self.svcTitulo.setText("<h2>RESULTADOS SVC</h2>")
        self.nbTitulo.setText("<h2>RESULTADOS NAIBE BAYES</h2>")
        self.knnTitulo.setText("<h2>RESULTADOS K-NEIGHBORS NEAREST</h2>")
        self.mlpTitulo.setText("<h2>RESULTADOS MLP</h2>")

        self.svcMatrix.setText(
            str(self.resultadoEntrenamiento['svc']['matrix']))
        self.nbMatrix.setText(str(self.resultadoEntrenamiento['nb']['matrix']))
        self.knnMatrix.setText(
            str(self.resultadoEntrenamiento['knn']['matrix']))
        self.mlpMatrix.setText(
            str(self.resultadoEntrenamiento['mlp']['matrix']))

        self.svcF1Label.setText("Puntuación F1 SVC: " +
                                str(self.resultadoEntrenamiento['svc']['f1']))
        self.svcRecallLabel.setText(
            "Recall SVC: " + str(self.resultadoEntrenamiento['svc']['recall']))
        self.svcPrecisionLabel.setText(
            "Precisión SVC: " +
            str(self.resultadoEntrenamiento['svc']['precisión']))
        self.svcAccuracyLabel.setText(
            "Puntuación Total SVC: " +
            str(self.resultadoEntrenamiento['svc']['puntuación']))
        self.mlpF1Label.setText("Puntuación F1 MLP: " +
                                str(self.resultadoEntrenamiento['mlp']['f1']))
        self.mlpRecallLabel.setText(
            "Recall MLP: " + str(self.resultadoEntrenamiento['mlp']['recall']))
        self.mlpPrecisionLabel.setText(
            "Precisión MLP: " +
            str(self.resultadoEntrenamiento['mlp']['precisión']))
        self.mlpAccuracyLabel.setText(
            "Puntuación Total MLP: " +
            str(self.resultadoEntrenamiento['mlp']['puntuación']))
        self.knnF1Label.setText("Puntuación F1 KNN: " +
                                str(self.resultadoEntrenamiento['knn']['f1']))
        self.knnRecallLabel.setText(
            "Recall KNN: " + str(self.resultadoEntrenamiento['knn']['recall']))
        self.knnPrecisionLabel.setText(
            "Precisión KNN: " +
            str(self.resultadoEntrenamiento['knn']['precisión']))
        self.knnAccuracyLabel.setText(
            "Puntuación Total KNN: " +
            str(self.resultadoEntrenamiento['knn']['puntuación']))
        self.nbF1Label.setText("Puntuación F1 NB: " +
                               str(self.resultadoEntrenamiento['nb']['f1']))
        self.nbRecallLabel.setText(
            "Recall NB: " + str(self.resultadoEntrenamiento['nb']['recall']))
        self.nbPrecisionLabel.setText(
            "Precisión NB: " +
            str(self.resultadoEntrenamiento['nb']['precisión']))
        self.nbAccuracyLabel.setText(
            "Puntuación Total NB: " +
            str(self.resultadoEntrenamiento['nb']['puntuación']))

        self.svcClass.setText(
            str(self.resultadoEntrenamiento['svc']['clasificación']))
        self.mlpClass.setText(
            str(self.resultadoEntrenamiento['mlp']['clasificación']))
        self.nbClass.setText(
            str(self.resultadoEntrenamiento['nb']['clasificación']))
        self.knnClass.setText(
            str(self.resultadoEntrenamiento['knn']['clasificación']))

        #self.setLayout(self.layoutReporte)
        self.layoutWidget.addLayout(self.layoutEntrenamiento)
        self.layoutEntrenamiento.addLayout(self.layoutReporte)
        self.layoutEntrenamiento.addLayout(self.layoutClass)
        self.mostrarLayout(self.layoutReporte)
        self.mostrarLayout(self.layoutClass)
        print("Se muestra el reporte")

    '''Función que entrena todos los algoritmos utilizando datos de ficheros de entrenamiento y de test. En la misma función se limpian los datos tokenizados. Al final detecta cuál es la mejor configuración para el algoritmo y los entrena con dicha configuración'''

    def entrenar_algoritmos(self):
        #self.infoLayout.hide()
        self.reiniciarEstado(438)
        filename2 = self.dialogo1.getOpenFileName(
            self, "Selecciona el fichero de entrenamiento", "/")
        filename2 = filename2[0].split("/")
        filename2 = filename2[-1]
        filename = self.dialogo1.getOpenFileName(
            self, "Selecciona el fichero de pruebas", "/")
        filename = filename[0].split("/")
        filename = filename[-1]
        dataset = pd.read_csv(filename)
        tweetys = dataset['text']  #Para mostrar el tweet?
        prueba = pd.read_csv(filename)  #para la última parte del NER combinado
        dataset2 = pd.read_csv(filename2)
        #CLEANING DATASET
        #TOKENIZATION
        dataset['tokens'] = dataset['text'].apply(TweetTokenizer().tokenize)
        #STOPWORDS
        stopwords_vocabulary = stopwords.words('english')
        dataset['stopwords'] = dataset['tokens'].apply(
            lambda x: [i for i in x if i.lower() not in stopwords_vocabulary])
        #SPECIAL CHARACTERS AND STOPWORDS REMOVAL
        punctuations = list(string.punctuation)
        dataset['punctuation'] = dataset['stopwords'].apply(
            lambda x: [i for i in x if i not in punctuations])
        dataset['digits'] = dataset['punctuation'].apply(
            lambda x: [i for i in x if i[0] not in list(string.digits)])
        dataset['final'] = dataset['digits'].apply(
            lambda x: [i for i in x if len(i) > 1])
        self.progressBarUnTweet.setValue(1)
        self.progresLabel.setText("Limpiando datos fichero entrenamiento")
        #CLEANING DATASET2
        #TOKENIZATION
        dataset2['tokens'] = dataset2['text'].apply(TweetTokenizer().tokenize)
        #STOPWORDS
        stopwords_vocabulary = stopwords.words('english')  #estará en español?
        dataset2['stopwords'] = dataset2['tokens'].apply(
            lambda x: [i for i in x if i.lower() not in stopwords_vocabulary])
        #SPECIAL CHARACTERS AND STOPWORDS REMOVAL
        punctuations = list(string.punctuation)
        dataset2['punctuation'] = dataset2['stopwords'].apply(
            lambda x: [i for i in x if i not in punctuations])
        dataset2['digits'] = dataset2['punctuation'].apply(
            lambda x: [i for i in x if i[0] not in list(string.digits)])
        dataset2['final'] = dataset2['digits'].apply(
            lambda x: [i for i in x if len(i) > 1])
        self.progressBarUnTweet.setValue(2)
        self.progresLabel.setText("Limpiando datos fichero de pruebas")
        #Here is the place where we set the number of tweets that we use to models. Always whit 80:20 percent.
        train_data = dataset2['final'][0:500]
        train_labels = dataset2['label'][0:500]
        test_data = dataset['final'][0:125]
        test_labels = dataset['label'][0:125]
        train_data = list(train_data.apply(' '.join))
        test_data = list(test_data.apply(' '.join))
        self.progressBarUnTweet.setValue(3)
        self.progresLabel.setText("Actualizando datos de entrenamiento")
        #Preparing data for models
        train_vectors = self.vectorizer.fit_transform(train_data)
        test_vectors = self.vectorizer.transform(test_data)
        fvecto = open('fvecto', 'wb')
        dump(self.vectorizer, fvecto)
        #Analisys vectors:
        modelos = ['NaiveBayes', 'Svc', 'Knn', 'Mlp']
        puntuaciones = [0, 0, 0, 0]
        params_svc = [['linear', 'poly', 'tbf', 'sigmod', 'precomputed'],
                      [3, 5, 10], [0.1, 0.5, 0.9], [True, False],
                      [True, False]]
        best_svc = []
        params_knn = [[1, 5, 10], ['uniform', 'distance'],
                      ['ball_tree', 'kd_tree', 'brute', 'auto'], [5, 30, 100],
                      [1, 2]]
        best_knn = []
        params_mlp = [[50, 100, 150], ['identity', 'logistic', 'tanh', 'relu'],
                      [0.00005, 0.0001, 0.001],
                      ['constant', 'invscaling', 'adaptative']]
        best_mlp = []
        self.progressBarUnTweet.setValue(4)
        self.progresLabel.setText("Preparando parámetros de algoritmos")
        #TRAINING ALGORITHMs
        progreso = 5
        for alg in modelos:
            PySide2.QtWidgets.QApplication.processEvents()
            if alg == 'Svc':
                for a in params_svc[0]:
                    PySide2.QtWidgets.QApplication.processEvents()
                    for b in params_svc[1]:
                        PySide2.QtWidgets.QApplication.processEvents()
                        for c in params_svc[2]:
                            PySide2.QtWidgets.QApplication.processEvents()
                            for d in params_svc[3]:
                                PySide2.QtWidgets.QApplication.processEvents()
                                for e in params_svc[4]:
                                    PySide2.QtWidgets.QApplication.processEvents(
                                    )
                                    mod = SVC(kernel=a,
                                              degree=b,
                                              coef0=c,
                                              probability=d,
                                              shrinking=e)
                                    punt = self.entrenar(
                                        1, alg, train_vectors, train_labels,
                                        test_vectors, test_labels, mod)
                                    self.progressBarUnTweet.setValue(progreso)
                                    progreso = progreso + 1
                                    self.progresLabel.setText(
                                        "Entrenando SVC con kernel " + a)
                                    if punt > puntuaciones[0]:
                                        puntuaciones[0] = punt
                                        best_svc = [a, b, c, d, e]
            elif alg == 'NaiveBayes':
                mod = MultinomialNB()
                puntuaciones[1] = self.entrenar(1, alg, train_vectors,
                                                train_labels, test_vectors,
                                                test_labels, mod)
            elif alg == 'Knn':
                for a in params_knn[0]:
                    PySide2.QtWidgets.QApplication.processEvents()
                    for b in params_knn[1]:
                        PySide2.QtWidgets.QApplication.processEvents()
                        for c in params_knn[2]:
                            PySide2.QtWidgets.QApplication.processEvents()
                            for d in params_knn[3]:
                                PySide2.QtWidgets.QApplication.processEvents()
                                for e in params_knn[4]:
                                    PySide2.QtWidgets.QApplication.processEvents(
                                    )
                                    self.progressBarUnTweet.setValue(progreso)
                                    self.progresLabel.setText(
                                        "Entrenando KNN con kernel " + b + c)
                                    progreso = progreso + 1
                                    mod = KNeighborsClassifier(n_neighbors=a,
                                                               weights=b,
                                                               algorithm=c,
                                                               leaf_size=d,
                                                               p=e)
                                    punt = self.entrenar(
                                        1, alg, train_vectors, train_labels,
                                        test_vectors, test_labels, mod)
                                    if punt > puntuaciones[2]:
                                        puntuaciones[2] = punt
                                        best_knn = [a, b, c, d, e]
            elif alg == 'Mlp':
                for a in params_mlp[0]:
                    PySide2.QtWidgets.QApplication.processEvents()
                    for b in params_mlp[1]:
                        PySide2.QtWidgets.QApplication.processEvents()
                        for c in params_mlp[2]:
                            PySide2.QtWidgets.QApplication.processEvents()
                            for d in params_mlp[3]:
                                PySide2.QtWidgets.QApplication.processEvents()
                                self.progressBarUnTweet.setValue(progreso)
                                self.progresLabel.setText(
                                    "Entrenando MLP con kernel " + b + d)
                                progreso = progreso + 1
                                mod = MLPClassifier(hidden_layer_sizes=a,
                                                    activation=b,
                                                    alpha=c,
                                                    learning_rate=d)
                                punt = self.entrenar(1, alg, train_vectors,
                                                     train_labels,
                                                     test_vectors, test_labels,
                                                     mod)
                                if punt > puntuaciones[3]:
                                    puntuaciones[3] = punt
                                    best_mlp = [a, b, c, d]
        #Encontrar el mejor modelo de todos
        tmp = 0
        guia = 0
        for h in puntuaciones:
            if h > tmp:
                best_model = guia
                tmp = h
            guia = guia + 1
        self.progressBarUnTweet.setValue(progreso)
        progreso = progreso + 1
        self.resultadoEntrenamiento['svc'] = self.entrenar(
            2, 'Svc', train_vectors, train_labels, test_vectors, test_labels,
            SVC(kernel=best_svc[0],
                degree=best_svc[1],
                coef0=best_svc[2],
                probability=best_svc[3],
                shrinking=best_svc[4]))
        self.resultadoEntrenamiento['nb'] = self.entrenar(2,
                                                          'NaiveBayes',
                                                          train_vectors,
                                                          train_labels,
                                                          test_vectors,
                                                          test_labels,
                                                          mod=MultinomialNB())
        self.resultadoEntrenamiento['knn'] = self.entrenar(
            2, 'Knn', train_vectors, train_labels, test_vectors, test_labels,
            KNeighborsClassifier(n_neighbors=best_knn[0],
                                 weights=best_knn[1],
                                 algorithm=best_knn[2],
                                 leaf_size=best_knn[3],
                                 p=best_knn[4]))
        self.resultadoEntrenamiento['mlp'] = self.entrenar(
            2, 'Mlp', train_vectors, train_labels, test_vectors, test_labels,
            MLPClassifier(hidden_layer_sizes=best_mlp[0],
                          activation=best_mlp[1],
                          alpha=best_mlp[2],
                          learning_rate=best_mlp[3]))
        self.progressBarUnTweet.setValue(progreso)
        self.progresLabel.setText("FINALIZADO")
        self.entrenamientoLabel.setText(
            "<h1>ENTRENAMIENTO REALIZADO CON ÉXITO</h1>")
        self.layoutWidget.addWidget(self.entrenamientoLabel)
        self.mostrarReporte()

    '''Función auxiliar para usar_NER que guarda los archivos de entrenamiento para que se guarden en futuras sesiones'''

    def entrenar(self, opc, alg, train_vectors, train_labels, test_vectors,
                 test_labels, mod):
        nfile = alg
        if path.exists(nfile):
            file = open(nfile, 'rb')  #abre el archivo en modo lectura
            mod = load(file)  #carga el archivo en la variable
            mod.fit(train_vectors,
                    train_labels).score(test_vectors, test_labels)  #lo entrena
            file.close()  #cierra el archivo
            file = open(nfile, 'wb')  #abre el archivo en modo escritura
            dump(mod, file)  #actualiza el entrenamiento
        else:
            file = open(nfile, 'wb')  #abre el archivo en modo escritura
            mod.fit(train_vectors,
                    train_labels).score(test_vectors, test_labels)  #lo entrena
            dump(mod, file)  #guarda el entrenamiento
        predicted = cross_val_predict(mod, test_vectors, test_labels, cv=10)
        if opc == 1:
            return accuracy_score(test_labels, predicted)
        elif opc == 2:
            return {
                'clasificación':
                classification_report(test_labels, mod.predict(test_vectors)),
                'matrix':
                confusion_matrix(test_labels, mod.predict(test_vectors)),
                'puntuación':
                accuracy_score(test_labels, predicted),
                'f1':
                f1_score(test_labels,
                         mod.predict(test_vectors),
                         average='macro'),
                'recall':
                recall_score(test_labels,
                             mod.predict(test_vectors),
                             average='macro'),
                'precisión':
                precision_score(test_labels,
                                mod.predict(test_vectors),
                                average='macro')
            }
Ejemplo n.º 24
0
class Ui_MainWindow(object):
    def __init__(self):
        self.file_name = ""
        self.threadpool = QThreadPool()
        self.num_of_co = 1000
        self.alpha = 0.1
        self.watermarker = None

    def setupUi(self, MainWindow):
        if not MainWindow.objectName():
            MainWindow.setObjectName(u"MainWindow")
        MainWindow.resize(1024, 768)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(u"centralwidget")
        self.verticalLayoutWidget_2 = QWidget(self.centralwidget)
        self.verticalLayoutWidget_2.setObjectName(u"verticalLayoutWidget_2")
        self.verticalLayoutWidget_2.setGeometry(QRect(0, 0, 1021, 511))
        self.pictureLayout = QVBoxLayout(self.verticalLayoutWidget_2)
        self.pictureLayout.setObjectName(u"pictureLayout")
        self.pictureLayout.setContentsMargins(0, 0, 0, 0)
        self.picture_label = QLabel(self.verticalLayoutWidget_2)
        self.picture_label.setObjectName(u"picture_label")

        self.pictureLayout.addWidget(self.picture_label)

        self.picture_button = QPushButton(self.verticalLayoutWidget_2)
        self.picture_button.setObjectName(u"picture_button")

        self.pictureLayout.addWidget(self.picture_button)

        self.horizontalLayoutWidget = QWidget(self.centralwidget)
        self.horizontalLayoutWidget.setObjectName(u"horizontalLayoutWidget")
        self.horizontalLayoutWidget.setGeometry(QRect(10, 520, 1011, 120))
        self.horizontalLayout_2 = QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName(u"verticalLayout_3")
        self.label_2 = QLabel(self.horizontalLayoutWidget)
        self.label_2.setObjectName(u"label_2")

        self.verticalLayout_3.addWidget(self.label_2)

        self.DCT_encode = QPushButton(self.horizontalLayoutWidget)
        self.DCT_encode.setObjectName(u"DCT_encode")

        self.verticalLayout_3.addWidget(self.DCT_encode)

        self.DCT_decode = QPushButton(self.horizontalLayoutWidget)
        self.DCT_decode.setObjectName(u"DCT_decode")

        self.verticalLayout_3.addWidget(self.DCT_decode)

        self.label_4 = QLabel(self.horizontalLayoutWidget)
        self.label_4.setObjectName(u"label_4")

        self.verticalLayout_3.addWidget(self.label_4)

        self.DCT_masg = QLineEdit(self.horizontalLayoutWidget)
        self.DCT_masg.setObjectName(u"DCT_masg")

        self.verticalLayout_3.addWidget(self.DCT_masg)

        self.horizontalLayout_2.addLayout(self.verticalLayout_3)

        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.label_3 = QLabel(self.horizontalLayoutWidget)
        self.label_3.setObjectName(u"label_3")

        self.verticalLayout.addWidget(self.label_3)

        self.LSB_encode = QPushButton(self.horizontalLayoutWidget)
        self.LSB_encode.setObjectName(u"LSB_encode")

        self.verticalLayout.addWidget(self.LSB_encode)

        self.LSB_decode = QPushButton(self.horizontalLayoutWidget)
        self.LSB_decode.setObjectName(u"LSB_decode")

        self.verticalLayout.addWidget(self.LSB_decode)

        self.lsb_encode_msg = QLabel(self.horizontalLayoutWidget)
        self.lsb_encode_msg.setObjectName(u"lsb_encode_msg")

        self.verticalLayout.addWidget(self.lsb_encode_msg)

        self.LSB_msg = QLineEdit(self.horizontalLayoutWidget)
        self.LSB_msg.setObjectName(u"LSB_msg")

        self.verticalLayout.addWidget(self.LSB_msg)

        self.horizontalLayout_2.addLayout(self.verticalLayout)

        self.verticalLayoutWidget_3 = QWidget(self.centralwidget)
        self.verticalLayoutWidget_3.setObjectName(u"verticalLayoutWidget_3")
        self.verticalLayoutWidget_3.setGeometry(QRect(20, 650, 981, 51))
        self.verticalLayout_2 = QVBoxLayout(self.verticalLayoutWidget_3)
        self.verticalLayout_2.setObjectName(u"verticalLayout_2")
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.label_6 = QLabel(self.verticalLayoutWidget_3)
        self.label_6.setObjectName(u"label_6")

        self.verticalLayout_2.addWidget(self.label_6)

        self.progressBar = QProgressBar(self.verticalLayoutWidget_3)
        self.progressBar.setObjectName(u"progressBar")
        self.progressBar.setValue(0)

        self.verticalLayout_2.addWidget(self.progressBar)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setObjectName(u"menubar")
        self.menubar.setGeometry(QRect(0, 0, 1024, 21))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName(u"statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        # bind functions
        self.picture_button.clicked.connect(self.open_file)
        self.LSB_encode.clicked.connect(self.call_lsb_encode)
        self.LSB_decode.clicked.connect(self.call_lsb_decode)
        self.DCT_encode.clicked.connect(self.call_dct_encode)
        self.DCT_decode.clicked.connect(self.call_dct_decode)
        # end bind functions()
        self.hide_progress_bar()
        self.disable_Methods(True)

        QMetaObject.connectSlotsByName(MainWindow)

    # setupUi

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(
            QCoreApplication.translate("MainWindow", u"Watermarking tool",
                                       None))
        # self.picture_label.setText(QCoreApplication.translate("MainWindow", u"TextLabel", None))
        self.picture_button.setText(
            QCoreApplication.translate("MainWindow", u"Select picture", None))
        self.label_2.setText(
            QCoreApplication.translate("MainWindow", u"DCT", None))
        self.DCT_encode.setText(
            QCoreApplication.translate("MainWindow", u"encode", None))
        self.DCT_decode.setText(
            QCoreApplication.translate("MainWindow", u"decode", None))
        self.label_4.setText(
            QCoreApplication.translate("MainWindow", u"coeficient:", None))
        self.DCT_masg.setText(
            QCoreApplication.translate("MainWindow", u"1000, 0.1", None))
        self.label_3.setText(
            QCoreApplication.translate("MainWindow", u"LSB", None))
        self.LSB_encode.setText(
            QCoreApplication.translate("MainWindow", u"encode", None))
        self.LSB_decode.setText(
            QCoreApplication.translate("MainWindow", u"decode", None))
        self.lsb_encode_msg.setText(
            QCoreApplication.translate("MainWindow", u"LSB msg:", None))
        self.LSB_msg.setText(
            QCoreApplication.translate("MainWindow", u"secret", None))
        self.label_6.setText(
            QCoreApplication.translate("MainWindow", u"Work in progress:",
                                       None))

    # retranslateUi

    # def bindFunctions(self):

    def load_picture(self):
        pixmap = QPixmap(self.file_name[0])
        if pixmap.width() > pixmap.height():
            self.picture_label.setPixmap(
                pixmap.scaledToWidth(self.picture_label.width()))
        else:
            self.picture_label.setPixmap(
                pixmap.scaledToHeight(self.picture_label.height()))

    def open_file(self):
        self.hide_progress_bar()
        self.file_name = QFileDialog.getOpenFileName(
            None, "Open Image", "", "Image Files (*.png *.jpg *.bmp)")
        self.load_picture()
        self.disable_Methods(False)

    def method_LSB_encode(self, progress_callback):
        self.disable_Methods(True)
        progress_callback.emit(10)
        msg = self.LSB_msg.text()
        image = cv2.imread(self.file_name[0])
        watermarker = LSBWatermarker(image=image,
                                     mode='encode-message',
                                     message=msg,
                                     filename='result.png')
        progress_callback.emit(50)
        self.file_name = ["result.png", ""]
        watermarker.run()
        progress_callback.emit(90)
        self.load_picture()
        self.disable_Methods(False)
        progress_callback.emit(100)

    def method_LSB_decode(self, progress_callback):
        self.disable_Methods(True)
        self.LSB_msg.setText("")
        progress_callback.emit(10)
        image = cv2.imread(self.file_name[0])
        watermarker = LSBWatermarker(image=image, mode='decode-message')
        progress_callback.emit(50)
        watermarker.run()
        self.disable_Methods(False)
        progress_callback.emit(90)
        # self.show_decoded_msg(watermarker.decoded_msg)
        if watermarker.decoded_msg == "Provided file has no message encoded!":
            self.LSB_msg.setText(watermarker.decoded_msg)
        else:
            self.LSB_msg.setText("Decoded: " + watermarker.decoded_msg)
        progress_callback.emit(100)

    def method_DCT_encode(self, progress_callback):
        self.disable_Methods(True)
        progress_callback.emit(10)
        msg = self.DCT_masg.text().split(",")
        try:
            self.num_of_co = int(msg[0])
            self.alpha = float(msg[1])
            self.watermarker = WatermarkDCT(self.file_name[0],
                                            num_of_co=self.num_of_co,
                                            alpha=self.alpha)
            progress_callback.emit(50)
            self.watermarker.encode_watermark()
            self.file_name = ["result_DCT.png", ""]
            self.DCT_masg.setText("Picture is watermarked?:" +
                                  str(self.watermarker.detect_watermark()))

        except Exception as e:
            print(e)
            self.DCT_masg.setText("Error: wrong parameters: example 1000, 0.1")
        finally:
            progress_callback.emit(90)

            self.load_picture()
            self.disable_Methods(False)
            progress_callback.emit(100)

    def method_DCT_decode(self, progress_callback):
        self.disable_Methods(True)
        progress_callback.emit(10)
        try:
            if self.watermarker is None:
                self.watermarker = WatermarkDCT(self.file_name[0],
                                                num_of_co=self.num_of_co,
                                                alpha=self.alpha)
            progress_callback.emit(50)
            self.DCT_masg.setText(
                "Picture is watermarked?:" +
                str(self.watermarker.detect_watermark(self.file_name[0])))
        except Exception as e:
            print(e)
            self.DCT_masg.setText("Error: Unable to check the picture.")
        finally:
            progress_callback.emit(90)

            self.load_picture()
            self.disable_Methods(False)
            progress_callback.emit(100)

    def show_decoded_msg(self, msg):
        msgBox = QMessageBox()
        msgBox.setWindowTitle("Decoded message:")
        msgBox.setText(msg)
        msgBox.exec_()

    def thread_complete(self):
        print("THREAD COMPLETE!")

    def progress_fn(self, n):
        self.progressBar.setValue(n)

    def print_output(self, s):
        print(s)

    def call_lsb_encode(self):
        self.show_progress_bar()
        self.call_function(self.method_LSB_encode)

    def call_lsb_decode(self):
        self.show_progress_bar()
        self.call_function(self.method_LSB_decode)

    def call_dct_encode(self):
        self.show_progress_bar()
        self.call_function(self.method_DCT_encode)

    def call_dct_decode(self):
        self.show_progress_bar()
        self.call_function(self.method_DCT_decode)

    def call_function(self, fn):
        worker = Worker(
            fn)  # Any other args, kwargs are passed to the run function
        worker.signals.result.connect(self.print_output)
        worker.signals.finished.connect(self.thread_complete)
        worker.signals.progress.connect(self.progress_fn)

        # Execute
        self.threadpool.start(worker)

    def hide_progress_bar(self):
        self.progressBar.setValue(0)
        self.progressBar.setVisible(False)
        self.label_6.setVisible(False)

    def show_progress_bar(self):
        self.progressBar.setValue(0)
        self.progressBar.setVisible(True)
        self.label_6.setVisible(True)

    def disable_Methods(self, disable):
        self.LSB_encode.setDisabled(disable)
        self.LSB_decode.setDisabled(disable)
        self.DCT_decode.setDisabled(disable)
        self.DCT_encode.setDisabled(disable)
Ejemplo n.º 25
0
 def __init__(self, vectorizer, parent=None):
     QtWidgets.QWidget.__init__(self, parent)
     self.vectorizer = vectorizer  #Variable para el entrenamiento de algoritmos
     #resultados de los mejores entrenamientos
     self.resultadoEntrenamiento = {}
     self.layoutReporte = QVBoxLayout()
     self.svcTitulo = QLabel(self)
     self.layoutReporte.addWidget(self.svcTitulo)
     self.svcF1Label = QLabel(self)
     self.layoutReporte.addWidget(self.svcF1Label)
     self.svcRecallLabel = QLabel(self)
     self.layoutReporte.addWidget(self.svcRecallLabel)
     self.svcPrecisionLabel = QLabel(self)
     self.layoutReporte.addWidget(self.svcPrecisionLabel)
     self.svcAccuracyLabel = QLabel(self)
     self.layoutReporte.addWidget(self.svcAccuracyLabel)
     self.svcMatrix = QLabel(self)
     self.layoutReporte.addWidget(self.svcMatrix)
     self.mlpTitulo = QLabel(self)
     self.layoutReporte.addWidget(self.mlpTitulo)
     self.mlpF1Label = QLabel(self)
     self.layoutReporte.addWidget(self.mlpF1Label)
     self.mlpRecallLabel = QLabel(self)
     self.layoutReporte.addWidget(self.mlpRecallLabel)
     self.mlpPrecisionLabel = QLabel(self)
     self.layoutReporte.addWidget(self.mlpPrecisionLabel)
     self.mlpAccuracyLabel = QLabel(self)
     self.layoutReporte.addWidget(self.mlpAccuracyLabel)
     self.mlpMatrix = QLabel(self)
     self.layoutReporte.addWidget(self.mlpMatrix)
     self.knnTitulo = QLabel(self)
     self.layoutReporte.addWidget(self.knnTitulo)
     self.knnF1Label = QLabel(self)
     self.layoutReporte.addWidget(self.knnF1Label)
     self.knnRecallLabel = QLabel(self)
     self.layoutReporte.addWidget(self.knnRecallLabel)
     self.knnPrecisionLabel = QLabel(self)
     self.layoutReporte.addWidget(self.knnPrecisionLabel)
     self.knnAccuracyLabel = QLabel(self)
     self.layoutReporte.addWidget(self.knnAccuracyLabel)
     self.knnMatrix = QLabel(self)
     self.layoutReporte.addWidget(self.knnMatrix)
     self.nbTitulo = QLabel(self)
     self.layoutReporte.addWidget(self.nbTitulo)
     self.nbF1Label = QLabel(self)
     self.layoutReporte.addWidget(self.nbF1Label)
     self.nbRecallLabel = QLabel(self)
     self.layoutReporte.addWidget(self.nbRecallLabel)
     self.nbPrecisionLabel = QLabel(self)
     self.layoutReporte.addWidget(self.nbPrecisionLabel)
     self.nbAccuracyLabel = QLabel(self)
     self.layoutReporte.addWidget(self.nbAccuracyLabel)
     self.nbMatrix = QLabel(self)
     self.layoutReporte.addWidget(self.nbMatrix)
     self.layoutClass = QVBoxLayout()
     self.svcClass = QLabel(self)
     self.layoutClass.addWidget(self.svcClass)
     self.mlpClass = QLabel(self)
     self.layoutClass.addWidget(self.mlpClass)
     self.knnClass = QLabel(self)
     self.layoutClass.addWidget(self.knnClass)
     self.nbClass = QLabel(self)
     self.layoutClass.addWidget(self.nbClass)
     self.layoutEntrenamiento = QHBoxLayout()
     #Botones del menú principal
     self.buttonBloqueFile = QPushButton("&Analizar Bloque desde archivo",
                                         self)
     self.buttonBloqueTwitter = QPushButton(
         "&Analizar Bloque desde Twitter.com", self)
     self.buttonUnTweet = QPushButton("&Analizar un Tweet", self)
     self.buttonEntrenar = QPushButton("&Entrenar algoritmos", self)
     #Añadir los botones al layout del menú
     self.layoutMenu = QHBoxLayout()
     self.layoutMenu.addWidget(self.buttonBloqueFile)
     self.layoutMenu.addWidget(self.buttonBloqueTwitter)
     self.layoutMenu.addWidget(self.buttonUnTweet)
     self.layoutMenu.addWidget(self.buttonEntrenar)
     #Layout donde irían los resultados
     self.layoutWidget = QVBoxLayout()
     self.infoLayout = QVBoxLayout(
     )  #Layout que muestra todos los widgets de mostrar un sólo tweet
     #Variables para mostrar un sólo tweet
     self.tituloLabel = QLabel(self)  #Etiqueta que muestra el título
     self.infoLayout.addWidget(self.tituloLabel)
     self.tweetLabel = QLabel(
         self)  #Etiqueta que muestra el texto del tweet
     self.infoLayout.addWidget(self.tweetLabel)
     self.nerLabel = QLabel(self)  #Etiqueta que muestra el título de NER
     self.infoLayout.addWidget(self.nerLabel)
     self.nonerLabel = QLabel(
         self)  #Etiqueta que muestra el aviso de que no hay NER
     self.infoLayout.addWidget(self.nonerLabel)
     self.tabla = QTableWidget()  #Tabla que muestra los resultados del NER
     self.infoLayout.addWidget(self.tabla)
     self.claLabel = QLabel(
         self
     )  #Etiqueta que muestra el título que precede a la tabla de sentimientos
     self.infoLayout.addWidget(self.claLabel)
     self.tablaSent = QTableWidget(
     )  #Tabla que muestra los sentimientos de cada algoritmo
     self.infoLayout.addWidget(self.tablaSent)
     #Variables para mostrar en entrenamiento
     self.entrenamientoLabel = QLabel(self)
     #Variables para la barra de progreso
     self.progressBarUnTweet = QProgressBar(self)
     self.progressLayout = QVBoxLayout()
     self.progresLabel = QLabel(self)
     self.progressLayout.addWidget(self.progresLabel)
     self.progressLayout.addWidget(self.progressBarUnTweet)
     #Elementos para NER
     self.nerLayout = QVBoxLayout()
     self.layoutWidget.addLayout(self.nerLayout)
     self.botones = []
     #Variables para la selección en cargar datos de twitter
     self.consultaText = ""
     self.consultaTweets = 0
     self.nerCantidadValor = 0
     #diálogo de archivo
     self.dialogo1 = QFileDialog(self)
     #Creación del layout principal que anida el resto de layouts
     self.layoutPrincipal = QVBoxLayout()
     self.layoutPrincipal.addLayout(self.layoutMenu)
     self.layoutPrincipal.addLayout(self.progressLayout)
     self.layoutPrincipal.addStretch()
     self.layoutPrincipal.addLayout(self.layoutWidget)
     self.setLayout(self.layoutPrincipal)
     #Diálogo para configurar parámetros de bloque de Twitter
     self.dialogConsulta = QInputDialog(self)
     self.dialogTweets = QInputDialog(self)
     self.nerCantidad = QInputDialog(self)
     # Conectar a analizarUnTweet:
     self.buttonUnTweet.clicked.connect(self.analizarUnTweet)
     # Conectar a entrenar_algoritmos
     self.buttonEntrenar.clicked.connect(self.entrenar_algoritmos)
     # Conectar a cargar datos de Twitter
     self.buttonBloqueTwitter.clicked.connect(self.cuadroDialogo)
     # Conectar a cargar datos de archivo
     self.buttonBloqueFile.clicked.connect(self.analizarDeArchivo)
Ejemplo n.º 26
0
class FooterBarWidget(QToolBar):
    """Bottom tool bar"""

    actionPlay = Signal()
    actionStop = Signal()
    actionLiveModeToggle = Signal(bool)

    def __init__(self, parent: QObject, manager: Manager):
        super().__init__(parent)

        self._manager = manager

        # Used to control the progress bar and spacer visibility
        # https://stackoverflow.com/a/1695779
        self._action_progress = None
        self._action_spacer = None

        # Build widgets
        self.button_play = QPushButton("Play", self)
        self.button_stop = QPushButton("Stop", self)
        self.button_export = QPushButton("Export", self)
        self.label_progress = QLabel(self)
        self.checkbox_live = QCheckBox("Live", self)
        self.checkbox_live.setChecked(self._manager.auto_solve)
        self.progressbar = QProgressBar(self)
        self.progressbar.setMaximum(0)
        self.progressbar.setValue(-1)
        self.progressbar.setHidden(True)
        self.spacer = QWidget()
        self.spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # Build layout
        self.addWidget(self.button_play)
        self.addWidget(self.button_stop)
        self.addWidget(self.label_progress)
        self._action_progress = self.addWidget(self.progressbar)
        self._action_spacer = self.addWidget(self.spacer)
        self.addWidget(self.button_export)
        self.addWidget(self.checkbox_live)

        # # Connect events
        self.button_play.pressed.connect(self.actionPlay.emit)  # type: ignore
        self.button_stop.pressed.connect(self.actionStop.emit)  # type: ignore
        self.button_export.pressed.connect(self.on_export_pressed)  # type: ignore
        self.checkbox_live.stateChanged.connect(self.actionLiveModeToggle.emit)  # type: ignore
        self._manager.onSolvingStarted.connect(self.on_solve_start)  # type: ignore
        self._manager.onSolvingEnded.connect(self.on_solve_end)  # type: ignore
        self._manager.onSolutionFound.connect(self.on_solution_found)  # type: ignore

    def set_dirty(self, state: bool):
        """Called when a change that invalidate the current solution was made."""
        self.button_play.setStyleSheet(_CSS_DIRTY if state else _CSS_CLEAN)

    def on_export_pressed(self):
        """Export the current assignments to a .csv file."""
        path = show_save_dialog(self, "Export Assignations", "CSV (*.csv)")
        if not path:
            return
        self._manager.export_assignments(path)

    def on_solve_start(self):
        """Called when the solve start."""
        self._action_progress.setVisible(True)
        self._action_spacer.setVisible(False)

        self.button_play.setEnabled(False)
        self.button_stop.setEnabled(True)
        self.on_solution_found()

    def on_solution_found(self):
        """Called when the solver found a solution."""
        self.label_progress.setText(
            f"Number of iterations: {self._manager.solution_count}. "
            f"Total score: {self._manager.current_score}"
        )

    def on_solve_end(self):
        """Called when the solve end."""
        self._action_progress.setVisible(False)
        self._action_spacer.setVisible(True)

        self.button_play.setEnabled(True)
        self.button_stop.setEnabled(False)
Ejemplo n.º 27
0
class VideoDecoder(QDialog):
    def __init__(self):
        self.videoPath = ''
        self.videoWidth = 1920
        self.videoHeight = 1080
        self.subtitles = {x: {} for x in range(5)}
        self.setEncode = encodeOption()

        super().__init__()
        self.setWindowTitle('字幕输出及合成')
        self.resize(1750, 800)
        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.preview = QLabel('效果预览')
        self.preview.setMaximumHeight(750)
        self.preview.setMaximumWidth(1300)
        self.layout.addWidget(self.preview, 0, 0, 6, 10)
        self.preview.setScaledContents(True)
        self.preview.setAlignment(Qt.AlignCenter)
        self.preview.setStyleSheet("QLabel{background:white;}")

        self.previewSlider = Slider()
        self.previewSlider.setOrientation(Qt.Horizontal)
        self.previewSlider.setMinimum(0)
        self.previewSlider.setMaximum(1000)
        self.previewSlider.pointClicked.connect(self.setPreviewSlider)
        self.layout.addWidget(self.previewSlider, 6, 0, 1, 10)

        self.option = QTabWidget()
        self.option.setMaximumWidth(450)
        self.layout.addWidget(self.option, 0, 10, 3, 1)
        self.subDict = {x: fontWidget() for x in range(5)}
        for subNumber, tabPage in self.subDict.items():
            self.option.addTab(tabPage, '字幕 %s' % (subNumber + 1))
        self.advanced = advanced(self.videoWidth, self.videoHeight)
        self.option.addTab(self.advanced, 'ASS字幕信息')

        self.startGrid = QWidget()
        self.layout.addWidget(self.startGrid, 3, 10, 3, 1)
        self.startLayout = QGridLayout()
        self.startGrid.setLayout(self.startLayout)
        self.sub1Check = QPushButton('字幕 1')
        self.sub1Check.setStyleSheet('background-color:#3daee9')
        self.sub2Check = QPushButton('字幕 2')
        self.sub3Check = QPushButton('字幕 3')
        self.sub4Check = QPushButton('字幕 4')
        self.sub5Check = QPushButton('字幕 5')
        self.sub1CheckStatus = True
        self.sub2CheckStatus = False
        self.sub3CheckStatus = False
        self.sub4CheckStatus = False
        self.sub5CheckStatus = False
        self.sub1Check.clicked.connect(self.sub1CheckButtonClick)
        self.sub2Check.clicked.connect(self.sub2CheckButtonClick)
        self.sub3Check.clicked.connect(self.sub3CheckButtonClick)
        self.sub4Check.clicked.connect(self.sub4CheckButtonClick)
        self.sub5Check.clicked.connect(self.sub5CheckButtonClick)
        self.startLayout.addWidget(self.sub1Check, 0, 0, 1, 1)
        self.startLayout.addWidget(self.sub2Check, 0, 1, 1, 1)
        self.startLayout.addWidget(self.sub3Check, 0, 2, 1, 1)
        self.startLayout.addWidget(self.sub4Check, 0, 3, 1, 1)
        self.startLayout.addWidget(self.sub5Check, 0, 4, 1, 1)
        self.layerCheck = QPushButton('禁止字幕重叠')
        self.layerCheck.setStyleSheet('background-color:#3daee9')
        self.layerCheckStatus = True
        self.layerCheck.clicked.connect(self.layerButtonClick)
        self.startLayout.addWidget(self.layerCheck, 1, 0, 1, 2)
        self.encodeSetup = QPushButton('编码设置')
        self.encodeSetup.clicked.connect(self.setEncodeArgs)
        self.startLayout.addWidget(self.encodeSetup, 1, 3, 1, 2)
        self.outputEdit = QLineEdit()
        self.startLayout.addWidget(self.outputEdit, 2, 0, 1, 4)
        self.outputButton = QPushButton('保存路径')
        self.startLayout.addWidget(self.outputButton, 2, 4, 1, 1)
        self.outputButton.clicked.connect(self.setSavePath)
        self.exportSubButton = QPushButton('导出字幕')
        self.exportSubButton.clicked.connect(self.exportSub)
        self.exportSubButton.setFixedHeight(50)
        self.startLayout.addWidget(self.exportSubButton, 3, 0, 1, 2)
        self.startButton = QPushButton('开始合成')
        self.startButton.clicked.connect(self.exportVideo)
        self.startButton.setFixedHeight(50)
        self.startLayout.addWidget(self.startButton, 3, 3, 1, 2)

        self.processBar = QProgressBar()
        self.processBar.setStyleSheet(
            "QProgressBar{border:1px;text-align:center;background:white}")
        self.processBar.setMaximumWidth(450)
        self.layout.addWidget(self.processBar, 6, 10, 1, 1)

        self.totalFrames = 0
        self.old_decodeArgs = []
        self.videoPos = 1
        self.old_videoPos = 1
        self.duration = 0
        self.previewTimer = QTimer()
        self.previewTimer.setInterval(50)
        self.previewTimer.start()
        self.previewTimer.timeout.connect(self.generatePreview)

    def sub1CheckButtonClick(self):
        self.sub1CheckStatus = not self.sub1CheckStatus
        if self.sub1CheckStatus:
            self.sub1Check.setStyleSheet('background-color:#3daee9')
        else:
            self.sub1Check.setStyleSheet('background-color:#31363b')

    def sub2CheckButtonClick(self):
        self.sub2CheckStatus = not self.sub2CheckStatus
        if self.sub2CheckStatus:
            self.sub2Check.setStyleSheet('background-color:#3daee9')
        else:
            self.sub2Check.setStyleSheet('background-color:#31363b')

    def sub3CheckButtonClick(self):
        self.sub3CheckStatus = not self.sub3CheckStatus
        if self.sub3CheckStatus:
            self.sub3Check.setStyleSheet('background-color:#3daee9')
        else:
            self.sub3Check.setStyleSheet('background-color:#31363b')

    def sub4CheckButtonClick(self):
        self.sub4CheckStatus = not self.sub4CheckStatus
        if self.sub4CheckStatus:
            self.sub4Check.setStyleSheet('background-color:#3daee9')
        else:
            self.sub4Check.setStyleSheet('background-color:#31363b')

    def sub5CheckButtonClick(self):
        self.sub5CheckStatus = not self.sub5CheckStatus
        if self.sub5CheckStatus:
            self.sub5Check.setStyleSheet('background-color:#3daee9')
        else:
            self.sub5Check.setStyleSheet('background-color:#31363b')

    def layerButtonClick(self):
        self.layerCheckStatus = not self.layerCheckStatus
        if self.layerCheckStatus:
            self.layerCheck.setStyleSheet('background-color:#3daee9')
        else:
            self.layerCheck.setStyleSheet('background-color:#31363b')

    def setSavePath(self):
        savePath = QFileDialog.getSaveFileName(self, "选择视频输出文件夹", None,
                                               "MP4格式 (*.mp4)")[0]
        if savePath:
            self.outputEdit.setText(savePath)

    def setDefault(self, videoPath, videoWidth, videoHeight, duration, bitrate,
                   fps, subtitles):
        self.videoPath = videoPath
        self.videoWidth = videoWidth
        self.videoHeight = videoHeight
        self.setEncode.exportVideoWidth.setText(str(videoWidth))
        self.setEncode.exportVideoHeight.setText(str(videoHeight))
        self.setEncode.exportVideoBitrate.setText(str(bitrate))
        self.setEncode.exportVideoFPS.setText(str(fps))
        self.duration = duration
        self.advanced.setPlayRes(videoWidth, videoHeight)
        self.subtitles = copy.deepcopy(subtitles)
        for index in self.subtitles:
            if -1 in self.subtitles[index]:
                del self.subtitles[index][-1]

    def setPreviewSlider(self, p):
        pos = p.x() / self.previewSlider.width() * 1000
        if pos > 1000:
            pos = 1000
        elif pos < 0:
            pos = 0
        self.previewSlider.setValue(pos)
        self.videoPos = pos * self.duration // 1000000

    def ffmpegColor(self, color):
        color = color.upper()
        r = color[1:3]
        g = color[3:5]
        b = color[5:7]
        return '&H00%s%s%s' % (b, g, r)

    def collectArgs(self):
        self.decodeArgs = [[
            self.advanced.title.text(),
            self.advanced.originalScript.text(),
            self.advanced.translation.text(),
            self.advanced.editing.text(),
            self.advanced.timing.text(),
            self.advanced.scriptType.text(),
            self.advanced.collisions.currentText(),
            self.advanced.playResX.text(),
            self.advanced.playResY.text(),
            self.advanced.timer.text(),
            self.advanced.warpStyle.currentText().split(':')[0],
            self.advanced.scaleBS.currentText()
        ]]
        self.selectedSubDict = {}
        for subNumber, subCheck in enumerate([
                self.sub1CheckStatus, self.sub2CheckStatus,
                self.sub3CheckStatus, self.sub4CheckStatus,
                self.sub5CheckStatus
        ]):
            if subCheck:
                self.selectedSubDict[subNumber] = self.subDict[subNumber]
        self.subtitleArgs = {}
        for subNumber, font in self.selectedSubDict.items():
            if font.karaoke.isChecked():
                secondColor = self.ffmpegColor(font.secondColor)
            else:
                secondColor = '&H00000000'
            fontBold = -1 if font.fontBold else 0
            fontItalic = -1 if font.fontItalic else 0
            fontUnderline = -1 if font.fontUnderline else 0
            fontStrikeout = -1 if font.fontStrikeout else 0
            self.subtitleArgs[subNumber] = [
                font.fontName, font.fontSize,
                self.ffmpegColor(font.fontColor), secondColor,
                self.ffmpegColor(font.outlineColor),
                self.ffmpegColor(font.shadowColor), fontBold, fontItalic,
                fontUnderline, fontStrikeout, 100, 100, 0, 0, 1,
                font.outlineSizeBox.currentText(),
                font.shadowSizeBox.currentText(),
                font.align.currentText().split(':')[0],
                int(self.videoWidth * (font.LAlignSlider.value() / 100)),
                int(self.videoWidth * (font.RAlignSlider.value() / 100)),
                int(self.videoHeight * (font.VAlignSlider.value() / 100)), 1
            ]
        self.decodeArgs.append(self.subtitleArgs)
        self.decodeArgs.append([self.videoPath, self.layerCheckStatus])

    def exportSub(self):
        subtitlePath = QFileDialog.getSaveFileName(self, "选择字幕输出文件夹", None,
                                                   "ASS字幕文件 (*.ass)")[0]
        if subtitlePath:
            self.writeAss(subtitlePath, False, True)
            QMessageBox.information(self, '导出字幕', '导出完成', QMessageBox.Yes)

    def writeAss(self,
                 outputPath='temp_sub.ass',
                 preview=True,
                 tip=False,
                 pos=0):
        ass = codecs.open(outputPath, 'w', 'utf_8_sig')
        ass.write('[Script Info]\n')
        ass.write('Title: %s\n' % self.advanced.title.text())
        ass.write('OriginalScript: %s\n' % self.advanced.originalScript.text())
        ass.write('OriginalTranslation: %s\n' %
                  self.advanced.translation.text())
        ass.write('OriginalEditing: %s\n' % self.advanced.editing.text())
        ass.write('OriginalTiming: %s\n' % self.advanced.timing.text())
        ass.write('ScriptType: %s\n' % self.advanced.scriptType.text())
        ass.write('Collisions: %s\n' % self.advanced.collisions.currentText())
        ass.write('PlayResX: %s\n' % self.advanced.playResX.text())
        ass.write('PlayResY: %s\n' % self.advanced.playResY.text())
        ass.write('Timer: %s\n' % self.advanced.timer.text())
        ass.write('WrapStyle: %s\n' %
                  self.advanced.warpStyle.currentText().split(':')[0])
        ass.write('ScaledBorderAndShadow: %s\n\n' %
                  self.advanced.scaleBS.currentText())

        ass.write('[V4+ Styles]\n')
        ass.write(
            'Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, '
        )
        ass.write(
            'ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n'
        )
        for subNumber, fontArgs in self.subtitleArgs.items():
            style = 'Style: Subtitle_%s' % (subNumber + 1)
            for i in fontArgs:
                style += ',%s' % i
            ass.write('%s\n\n' % style)

        ass.write('[Events]\n')
        ass.write(
            'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n'
        )
        if preview:
            for subNumber in self.subtitleArgs:
                num = subNumber + 1
                if self.layerCheckStatus:
                    line = 'Dialogue: 0,0:00:00.00,0:00:10.00,%s,#%s,0,0,0,,%s\n' % (
                        'Subtitle_%s' % num, num, r'Hi! 我是第%s列字幕。' % num)
                else:
                    line = 'Dialogue: %s,0:00:00.00,0:00:10.00,%s,#%s,0,0,0,,%s\n' % (
                        subNumber, 'Subtitle_%s' % num, num,
                        'Hi! 我是第%s列字幕。' % num)
                ass.write(line)
            if tip:
                QMessageBox.information(self, '导出字幕', '导出完成', QMessageBox.Yes)
        else:
            if not pos:
                for subNumber in self.subtitleArgs:
                    for start, subData in self.subtitles[subNumber].items():
                        num = subNumber + 1
                        if self.layerCheckStatus:
                            line = 'Dialogue: 0,%s,%s,%s,#%s,0,0,0,,%s\n' % (
                                ms2Time(start), ms2Time(start + subData[0]),
                                'Subtitle_%s' % num, num, subData[1])
                        else:
                            line = 'Dialogue: %s,%s,%s,%s,#%s,0,0,0,,%s\n' % (
                                subNumber, ms2Time(start),
                                ms2Time(start + subData[0]),
                                'Subtitle_%s' % num, num, subData[1])
                        ass.write(line)
            else:
                for subNumber in self.subtitleArgs:
                    startKeys = list(self.subtitles[subNumber].keys())
                    for cnt, start in enumerate(startKeys):
                        if start / 1000 > pos and cnt:
                            start = startKeys[cnt - 1]
                            subData = self.subtitles[subNumber][start]
                            num = subNumber + 1
                            if self.layerCheckStatus:
                                line = 'Dialogue: 0,0:00:00.00,0:00:10.00,%s,#%s,0,0,0,,%s\n' % (
                                    'Subtitle_%s' % num, num, subData[1])
                            else:
                                line = 'Dialogue: %s,0:00:00.00,0:00:10.00,%s,#%s,0,0,0,,%s\n' % (
                                    subNumber, 'Subtitle_%s' % num, num,
                                    subData[1])
                            ass.write(line)
                            break
        ass.close()

    def generatePreview(self, force=False):
        self.collectArgs()
        if not self.selectedSubDict:
            self.exportSubButton.setEnabled(False)
        else:
            self.exportSubButton.setEnabled(True)
        if not self.videoPath or not self.outputEdit.text():
            self.startButton.setEnabled(False)
        else:
            self.startButton.setEnabled(True)
        if self.decodeArgs != self.old_decodeArgs or self.videoPos != self.old_videoPos or force:
            if os.path.exists('temp_sub.jpg'):
                os.remove('temp_sub.jpg')
            if self.decodeArgs != self.old_decodeArgs:
                self.old_decodeArgs = self.decodeArgs
                self.writeAss()
            elif self.videoPos != self.old_videoPos:
                self.old_videoPos = self.videoPos
                self.writeAss(preview=False, pos=self.videoPos)
            else:
                self.writeAss()
            videoWidth = self.setEncode.exportVideoWidth.text()
            videoHeight = self.setEncode.exportVideoHeight.text()
            bit = self.setEncode.exportVideoBitrate.text() + 'k'
            preset = ['veryslow', 'slower', 'medium', 'faster', 'ultrafast'
                      ][self.setEncode.exportVideoPreset.currentIndex()]
            cmd = [
                'utils/ffmpeg.exe', '-y', '-ss',
                str(self.videoPos), '-i', self.videoPath, '-frames', '1',
                '-vf', 'ass=temp_sub.ass', '-s',
                '%sx%s' % (videoWidth, videoHeight), '-b:v', bit, '-preset',
                preset, '-q:v', '1', '-f', 'image2', 'temp_sub.jpg'
            ]
            if not self.videoPath:
                self.preview.setText('请先在主界面选择视频')
                self.preview.setStyleSheet(
                    "QLabel{background:white;color:#232629}")
            else:
                p = subprocess.Popen(cmd)
                p.wait()
                pixmap = QPixmap('temp_sub.jpg')
                self.preview.setPixmap(pixmap)
        else:
            pass

    def setEncodeArgs(self):
        self.setEncode.hide()
        self.setEncode.show()

    def exportVideo(self):
        self.startButton.setText('停止')
        self.startButton.setStyleSheet('background-color:#3daee9')
        self.startButton.clicked.disconnect(self.exportVideo)
        self.startButton.clicked.connect(self.terminateEncode)
        self.processBar.setValue(0)
        outputPath = self.outputEdit.text()
        if os.path.exists(outputPath):
            os.remove(outputPath)
        if os.path.exists('temp_sub.ass'):
            os.remove('temp_sub.ass')
        self.previewTimer.stop()
        self.collectArgs()
        self.writeAss(preview=False)

        videoWidth = self.setEncode.exportVideoWidth.text()
        videoHeight = self.setEncode.exportVideoHeight.text()
        preset = ['veryslow', 'slower', 'medium', 'faster',
                  'ultrafast'][self.setEncode.exportVideoPreset.currentIndex()]
        audio = ''
        if self.setEncode.mixAudioPath.text():
            audio = self.setEncode.mixAudioPath.text()
        self.anime4k = self.setEncode.anime4KToken
        encoder = self.setEncode.encoder.currentIndex()
        bit = self.setEncode.exportVideoBitrate.text() + 'k'
        fps = self.setEncode.exportVideoFPS.text()
        cmd = [
            'utils/ffmpeg.exe', '-y', '-i', self.videoPath, '-b:v', bit, '-r',
            fps
        ]
        if audio:
            cmd += ['-i', audio, '-c:a', 'aac']
        cmd += [
            '-s',
            '%sx%s' % (videoWidth, videoHeight), '-preset', preset, '-vf',
            'ass=temp_sub.ass'
        ]
        if encoder == 1:
            cmd += ['-c:v', 'h264_nvenc']
        elif encoder == 2:
            cmd += ['-c:v', 'h264_amf']
        cmd.append(outputPath)

        self.videoEncoder = videoEncoder(self.videoPath, cmd)
        self.videoEncoder.processBar.connect(self.setProcessBar)
        self.videoEncoder.currentPos.connect(self.setEncodePreview)
        self.videoEncoder.encodeResult.connect(self.encodeFinish)
        self.videoEncoder.start()

    def setProcessBar(self, value):
        self.processBar.setValue(value)
        self.previewSlider.setValue(value * 10)

    def setEncodePreview(self, currentPos):
        self.writeAss(preview=False, pos=calSubTime(currentPos))
        cmd = [
            'utils/ffmpeg.exe', '-y', '-ss', currentPos, '-i', self.videoPath,
            '-frames', '1', '-vf', 'ass=temp_sub.ass', '-q:v', '1', '-f',
            'image2', 'temp_sub.jpg'
        ]
        p = subprocess.Popen(cmd)
        p.wait()
        pixmap = QPixmap('temp_sub.jpg')
        self.preview.setPixmap(pixmap)

    def encodeFinish(self, result):
        self.startButton.setText('开始合成')
        self.startButton.setStyleSheet('background-color:#31363b')
        self.startButton.clicked.disconnect(self.terminateEncode)
        self.startButton.clicked.connect(self.exportVideo)
        if result:
            self.previewTimer.start()
            self.processBar.setValue(100)
            QMessageBox.information(self, '导出视频', '导出完成', QMessageBox.Yes)
        else:
            self.previewTimer.start()
            self.processBar.setValue(0)
            QMessageBox.information(self, '导出视频', '导出视频失败!请检查参数或编码器是否选择正确',
                                    QMessageBox.Yes)
        self.generatePreview(force=True)

    def terminateEncode(self):
        self.startButton.setText('开始合成')
        self.startButton.setStyleSheet('background-color:#31363b')
        self.startButton.clicked.disconnect(self.terminateEncode)
        self.startButton.clicked.connect(self.exportVideo)
        try:
            p = psutil.Process(self.videoEncoder.p.pid)
            for proc in p.children(True):
                proc.kill()
            p.kill()
        except:
            pass
        self.videoEncoder.terminate()
        self.videoEncoder.quit()
        self.videoEncoder.wait()
        del self.videoEncoder
        self.processBar.setValue(0)
        QMessageBox.information(self, '导出视频', '中止导出', QMessageBox.Yes)
        self.generatePreview(force=True)
        self.previewTimer.start()
Ejemplo n.º 28
0
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle(
            "Automation.... WITH KITTENS!!!! AHHH I LOVE KITTENS")
        # Create Widgets
        self.fileLoader = QPushButton("Load Files")
        self.stopButton = QPushButton("Stop")
        self.fileBox = QComboBox()  # Holds name of files
        self.filePreview = QTextBrowser()  # Preview Files
        self.loadingBar = QProgressBar(self)
        self.preview = QTextBrowser()
        self.ConfirmButton = QPushButton("Start")
        # Variable Creation Area
        self.pictureDic = {}  # Holds the tings
        self.timerBool = bool
        # Create layout and add widgets
        layout = QVBoxLayout()
        # Design Area
        self.label2 = QLabel()
        self.label2.setText("Automating Kittens!")
        self.label2.setStyleSheet(
            "QLabel { background-color : black; color : white; font-size: 20px; text-align : "
            "center; }")
        self.label = QLabel()
        pixmap = QPixmap('pictures/helloKitten.png')
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.timer = QBasicTimer()
        self.step = 0
        self.label.setPixmap(pixmap)

        # Adding widgets to the layout
        layout.addWidget(self.label2)
        layout.addWidget(self.label)
        layout.addWidget(self.fileLoader)
        layout.addWidget(self.fileBox)
        layout.addWidget(self.filePreview)
        layout.addWidget(self.ConfirmButton)
        layout.addWidget(self.stopButton)
        self.loadingBar.setStyleSheet(
            "QProgressBar::chunk {background-color: red}")
        layout.addWidget(self.loadingBar)
        # Enable Minimize and maximize
        self.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
        self.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
        # Set layout
        self.setLayout(layout)
        p = self.palette()
        p.setColor(self.foregroundRole(), QColor(10, 10, 10, 127))
        p.setColor(self.backgroundRole(), QColor(0, 0, 127, 127))
        self.setPalette(p)
        self.setFixedWidth(450)
        self.setFixedHeight(700)
        # Connecting functions to buttons
        self.fileLoader.clicked.connect(self.loadFiles)
        self.ConfirmButton.clicked.connect(self.newStart)
        self.stopButton.clicked.connect(self.stop)
        self.fileBox.activated.connect(self.updatePreview)

    def start(self):
        print("Ready to Go")
        self.loadingBar.setStyleSheet(
            "QProgressBar::chunk {background-color: gold } QProgressBar {text-align: center}"
        )
        if bool(self.pictureDic) is False:
            self.filePreview.append("**** Empty Files **** \n")
            self.filePreview.append("**** Please load Files **** \n")
            self.timer.stop()
        else:
            self.filePreview.append("**** Starting Picture Search **** \n")
            self.searchThread = threadedSearch.thread_with_exception(
                "Searching", self.pictureDic)
            self.searchThread.start()
        pixmap = QPixmap('pictures/pawwingKitten.jpg')
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.label.setPixmap(pixmap)

    def loadFiles(self):
        print("We gone load them files doh")
        self.filePreview.append("**** Files Loaded **** \n")
        self.fileBox.clear()
        self.pictureDic.clear()
        with os.scandir('testpictures/') as files:
            for file in files:
                print(file.path)
                print(file.name)
                self.pictureDic.update({file.name: file.path})
                self.fileBox.addItem(file.name)
                self.filePreview.append("{} \n".format(file.name))
        self.filePreview.append("**** Files done loading **** \n")

    def newStart(self):
        pixmap = QPixmap('pictures/roaringKitten.jpg')
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.label.setPixmap(pixmap)
        self.timerBool = True
        global stepper
        stepper = 0
        self.loadingBar.setValue(0)
        self.loadingBar.setStyleSheet(
            "QProgressBar::chunk {background-color: red;} QProgressBar {text-align: center}"
        )
        self.startTracking()

    def updatePreview(self):
        self.label.clear()
        location = self.pictureDic[self.fileBox.currentText()]
        pixmap = QPixmap('{}'.format(location))
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.timer = QBasicTimer()
        self.step = 0
        self.label.setPixmap(pixmap)

    def startTracking(self):
        self.timer.start(80, self)

    def stop(self):
        self.timer.stop()
        try:
            self.searchThread.raise_exception()
            self.searchThread.join()
            self.filePreview.append("**** Sucessfully Killed thread **** \n")
        except:
            self.filePreview.append("**** No thread to kill! **** \n")
        pixmap = QPixmap('pictures/sadkitten.jpg')
        w = 440
        h = 200
        pixmap = pixmap.scaled(w,
                               h,
                               aspectMode=Qt.IgnoreAspectRatio,
                               mode=Qt.FastTransformation)
        self.label.setPixmap(pixmap)
        self.loadingBar.setValue(0)

    def timerEvent(self, event):
        if self.timerBool is True:
            global stepper
            stepper += 1
            self.loadingBar.setValue(stepper)
            if self.loadingBar.value() == 100:
                self.start()
                self.timerBool = False
                self.loadingBar.setStyleSheet(
                    "QProgressBar::chunk {background-color: green;} QProgressBar {text-align: center}"
                )
        else:
            try:
                printingMess = self.searchThread.getMessage()
                if printingMess != "":
                    self.filePreview.append("{} \n".format(printingMess))
            except:
                self.filePreview.append(
                    " *** No information from Thread *** \n")
Ejemplo n.º 29
0
    def __init__(self):
        self.videoPath = ''
        self.videoWidth = 1920
        self.videoHeight = 1080
        self.subtitles = {x: {} for x in range(5)}
        self.setEncode = encodeOption()

        super().__init__()
        self.setWindowTitle('字幕输出及合成')
        self.resize(1750, 800)
        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.preview = QLabel('效果预览')
        self.preview.setMaximumHeight(750)
        self.preview.setMaximumWidth(1300)
        self.layout.addWidget(self.preview, 0, 0, 6, 10)
        self.preview.setScaledContents(True)
        self.preview.setAlignment(Qt.AlignCenter)
        self.preview.setStyleSheet("QLabel{background:white;}")

        self.previewSlider = Slider()
        self.previewSlider.setOrientation(Qt.Horizontal)
        self.previewSlider.setMinimum(0)
        self.previewSlider.setMaximum(1000)
        self.previewSlider.pointClicked.connect(self.setPreviewSlider)
        self.layout.addWidget(self.previewSlider, 6, 0, 1, 10)

        self.option = QTabWidget()
        self.option.setMaximumWidth(450)
        self.layout.addWidget(self.option, 0, 10, 3, 1)
        self.subDict = {x: fontWidget() for x in range(5)}
        for subNumber, tabPage in self.subDict.items():
            self.option.addTab(tabPage, '字幕 %s' % (subNumber + 1))
        self.advanced = advanced(self.videoWidth, self.videoHeight)
        self.option.addTab(self.advanced, 'ASS字幕信息')

        self.startGrid = QWidget()
        self.layout.addWidget(self.startGrid, 3, 10, 3, 1)
        self.startLayout = QGridLayout()
        self.startGrid.setLayout(self.startLayout)
        self.sub1Check = QPushButton('字幕 1')
        self.sub1Check.setStyleSheet('background-color:#3daee9')
        self.sub2Check = QPushButton('字幕 2')
        self.sub3Check = QPushButton('字幕 3')
        self.sub4Check = QPushButton('字幕 4')
        self.sub5Check = QPushButton('字幕 5')
        self.sub1CheckStatus = True
        self.sub2CheckStatus = False
        self.sub3CheckStatus = False
        self.sub4CheckStatus = False
        self.sub5CheckStatus = False
        self.sub1Check.clicked.connect(self.sub1CheckButtonClick)
        self.sub2Check.clicked.connect(self.sub2CheckButtonClick)
        self.sub3Check.clicked.connect(self.sub3CheckButtonClick)
        self.sub4Check.clicked.connect(self.sub4CheckButtonClick)
        self.sub5Check.clicked.connect(self.sub5CheckButtonClick)
        self.startLayout.addWidget(self.sub1Check, 0, 0, 1, 1)
        self.startLayout.addWidget(self.sub2Check, 0, 1, 1, 1)
        self.startLayout.addWidget(self.sub3Check, 0, 2, 1, 1)
        self.startLayout.addWidget(self.sub4Check, 0, 3, 1, 1)
        self.startLayout.addWidget(self.sub5Check, 0, 4, 1, 1)
        self.layerCheck = QPushButton('禁止字幕重叠')
        self.layerCheck.setStyleSheet('background-color:#3daee9')
        self.layerCheckStatus = True
        self.layerCheck.clicked.connect(self.layerButtonClick)
        self.startLayout.addWidget(self.layerCheck, 1, 0, 1, 2)
        self.encodeSetup = QPushButton('编码设置')
        self.encodeSetup.clicked.connect(self.setEncodeArgs)
        self.startLayout.addWidget(self.encodeSetup, 1, 3, 1, 2)
        self.outputEdit = QLineEdit()
        self.startLayout.addWidget(self.outputEdit, 2, 0, 1, 4)
        self.outputButton = QPushButton('保存路径')
        self.startLayout.addWidget(self.outputButton, 2, 4, 1, 1)
        self.outputButton.clicked.connect(self.setSavePath)
        self.exportSubButton = QPushButton('导出字幕')
        self.exportSubButton.clicked.connect(self.exportSub)
        self.exportSubButton.setFixedHeight(50)
        self.startLayout.addWidget(self.exportSubButton, 3, 0, 1, 2)
        self.startButton = QPushButton('开始合成')
        self.startButton.clicked.connect(self.exportVideo)
        self.startButton.setFixedHeight(50)
        self.startLayout.addWidget(self.startButton, 3, 3, 1, 2)

        self.processBar = QProgressBar()
        self.processBar.setStyleSheet(
            "QProgressBar{border:1px;text-align:center;background:white}")
        self.processBar.setMaximumWidth(450)
        self.layout.addWidget(self.processBar, 6, 10, 1, 1)

        self.totalFrames = 0
        self.old_decodeArgs = []
        self.videoPos = 1
        self.old_videoPos = 1
        self.duration = 0
        self.previewTimer = QTimer()
        self.previewTimer.setInterval(50)
        self.previewTimer.start()
        self.previewTimer.timeout.connect(self.generatePreview)
class ProgressUpdater(QWidget):
    def __init__(self,
                 parent: QtCore.QObject = None,
                 window: QtWidgets.QMainWindow = None,
                 processingText: str = "Compressing...",
                 clickToStartText: str = "Click compress to start.") -> None:
        super().__init__(parent=parent)
        self.parentWindow: QtWidgets.QMainWindow = window
        self.processingText = processingText
        self.clickToStartText = clickToStartText
        self.isLoading = True
        #self.setFixedHeight(30)
        self.setUpWidgets()

    def setUpWidgets(self) -> None:
        self.wheelLabel = QLabel(self)
        self.progressBar = QProgressBar(self)
        self.progressBar.setAlignment(QtCore.Qt.AlignHCenter
                                      | QtCore.Qt.AlignVCenter)
        self.progressBar.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                       QtWidgets.QSizePolicy.Expanding)
        self.infoLabel = QLabel(self)
        self.infoLabel.setSizePolicy(QtWidgets.QSizePolicy.Ignored,
                                     QtWidgets.QSizePolicy.Ignored)

        self.mainLayout = QHBoxLayout()
        self.mainLayout.addWidget(self.wheelLabel)
        self.mainLayout.addWidget(self.progressBar)
        self.mainLayout.addWidget(self.infoLabel, stretch=1)

        self.wheelMovie = QtGui.QMovie(self)
        self.wheelMovie.setFileName(getPath("load.gif"))
        self.wheelMovie.setScaledSize(QtCore.QSize(20, 20))
        self.wheelMovie.start()

        self.wheelLabel.setMovie(self.wheelMovie)
        self.wheelLabel.hide()
        self.progressBar.setRange(0, 100)
        #self.progressBar.setFixedHeight(30)
        if (_platform == "win32"):
            self.parentWindow.taskbprogress.setRange(0, 100)
        self.progressBar.setValue(0)
        if (_platform == "win32"): self.parentWindow.taskbprogress.setValue(0)
        self.progressBar.setFixedSize(400, 20)
        self.progressBar.setFormat("Ready")
        self.infoLabel.setText(self.clickToStartText)

        self.mainLayout.setMargin(0)

        self.setLayout(self.mainLayout)

    def startLoading(self) -> None:
        self.isLoading = True
        if (_platform == "win32"): self.parentWindow.taskbprogress.show()
        if (_platform == "win32"): self.parentWindow.taskbprogress.setValue(0)
        self.progressBar.setValue(0)
        if (_platform == "win32"):
            self.parentWindow.taskbprogress.setRange(0, 0)
        self.progressBar.setRange(0, 0)
        self.infoLabel.setText(self.processingText)
        self.progressBar.setFormat("%p%")
        self.wheelLabel.show()

    def stopLoading(self) -> None:
        self.isLoading = False
        self.wheelLabel.hide()
        if (_platform == "win32"): self.parentWindow.taskbprogress.hide()
        if (_platform == "win32"):
            self.parentWindow.taskbprogress.setRange(0, 100)
        self.progressBar.setRange(0, 100)
        if (_platform == "win32"): self.parentWindow.taskbprogress.setValue(0)
        self.progressBar.setValue(0)
        self.progressBar.setFormat("Ready")
        self.infoLabel.setText(self.clickToStartText)

    def setText(self, text: str) -> None:
        self.infoLabel.setText(text)
        self.infoLabel.setToolTip(text)

    def setRange(self, min: int, max: int) -> None:
        self.progressBar.setRange(min, max)
        if (_platform == "win32"):
            self.parentWindow.taskbprogress.setRange(min, max)

    def setValue(self, value: int) -> None:
        self.progressBar.setValue(value)
        if (_platform == "win32"):
            self.parentWindow.taskbprogress.setValue(value)
Ejemplo n.º 31
0
    def paint(self, painter, option, index):
        progressBar = QProgressBar()
        style = """QProgressBar { color: #546E7A; }
        QProgressBar::chunk { background: #80CBC4;
        }"""

        progressBar.setAlignment(Qt.AlignCenter)
        progressBar.setTextVisible(True)

        progressBar.resize(option.rect.size())
        progressBar.setMinimum(0)
        progressBar.setMaximum(100)

        progressBar.setStyleSheet(style)

        dw = index.data()[0]
        tot = index.data()[1]
        if tot != 0:
            progressBar.setValue(round(dw/tot*100, 2))
        else:
            progressBar.setValue(0)
        progressBar.setFormat("{}/{} MB".format(round(dw/(
            1024*1024), 2), round(tot/(1024*1024), 2)))

        painter.save()
        painter.translate(option.rect.topLeft())
        progressBar.render(painter, QPoint(0, 0))
        painter.restore()