Beispiel #1
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.connectSignalsSlots()
        self.model = ''
        self.imageFile = ''
        self.remote = ''
        self.folderName = ''
        self.Failed = False

    def connectSignalsSlots(self):
        self.ui.browseFilesButton.clicked.connect(self.bbrowseFiles)
        self.ui.predictButton.clicked.connect(self.getPrediction)
        self.ui.fileList.itemSelectionChanged.connect(self.showImage)
        self.ui.actionExit.triggered.connect(self.quit)

    def quit(self):
        sys.exit(0)

    def connect(self):
        self.remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.remote.connect(('127.0.1.1', 50022))
        except ConnectionRefusedError:
            self.ui.txtOutput.append("Connection refused")
            self.failed = True

        response = server.getReply(self.remote)

        if response == "?":
            self.ui.txtOutput.append("Connected to server")
            return True
        else:
            return False

    def showImage(self):
        selectedImage = [
            item.text() for item in self.ui.fileList.selectedItems()
        ]
        self.imageFile = self.folderName + "/" + selectedImage[0]
        pixmap = QPixmap(self.imageFile)
        self.ui.picView.setPixmap(
            pixmap.scaled(self.ui.picView.width(), self.ui.picView.height()))

    def bbrowseFiles(self):
        self.folderName = file.browseFiles()
        self.ui.lblFilename.setText(self.folderName)

        images = file.addAllPngFiles(self.folderName)

        for item in images:
            self.ui.fileList.addItem(item)

    def sendModels(self):
        self.ui.txtOutput.append(f"Sending model: {self.model}")
        self.model = str(self.ui.modelList.currentText())
        reply = server.sendModel(self.model, self.remote)

    def getPrediction(self):
        connected = self.connect()

        if connected:
            self.ui.txtOutput.append(f"Sending image file: {self.imageFile}")
            server.sendImage(self.imageFile, self.remote)

            self.sendModels()

            self.ui.txtOutput.append("Waiting for prediction")
            pred = server.receivePred(self.remote)

            self.ui.txtOutput.append(f"got prediction {pred}")
            if pred == "P":
                pred = "Pneumonia"
            else:
                pred = "Normal"

            self.ui.lblPredict.setText(pred)
class VisualizerWindow(QMainWindow):
    """
    The main window of this application
    """

    instance = None

    def __init__(self):

        # Initialize superclass
        QMainWindow.__init__(self)
        self.setWindowIcon(QIcon(':/icon/icons/app.ico'))

        # Setup the UI defined in Qt Designer
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Generate the grid that will be interacted with
        self.numRows = 29  # Odd so that starting points are vertically centered
        self.numCols = 60
        self._setupGrid()

        # Define the start and end nodes
        self.start = Node.GRID[round(self.numRows / 2)][8]
        self.end = Node.GRID[round(self.numRows / 2)][-8]
        self.setStartNode(self.start)
        self.setEndNode(self.end)

        # -- User interaction variables --
        # Click & dragging
        self.changingStart = False  # Changing start node
        self.changingEnd = False  # Changing end node
        self.drawingWall = False  # Drawing a new wall
        self.erasingWall = False  # Deleting walls

        # Connecting button signals to functions
        self.connectSignals()
        self.ui.speedSlider.setValue(29)

        VisualizerWindow.instance = self

    def reset(self):
        """
        Resets the grid to its original state
        """

        for x in range(self.numRows):
            for y in range(self.numCols):
                cell = Node.GRID[x][y].cell
                cell.clear()
                cell.setWall(False)

        self.start.cell.clear()
        self.end.cell.clear()
        self.start.isStart = False
        self.end.isEnd = False

        self.start = Node.GRID[round(self.numRows / 2)][8]
        self.end = Node.GRID[round(self.numRows / 2)][-8]
        self.setStartNode(self.start)
        self.setEndNode(self.end)

    def _setupGrid(self):
        """
        Generates the grid of Cells along with the underlying Nodes that are used to visualize the selected algorithm
        """

        # First, generate the grid
        for x in range(self.numRows):
            for y in range(self.numCols):

                # Make the visual Cell representing the Node at x, y, then add it visually at those coordinates
                cell = Cell(Node(x, y), self)
                self.ui.gridLayout.addWidget(cell, x, y)

        # Then reiterate and populate the neighbors, with diagonals enabled by default
        self.populateNeighbors()

    def populateNeighbors(self, withDiagonals: bool = True):
        """
        Populates all Nodes' neighbors
        """

        for x in range(self.numRows):
            for y in range(self.numCols):
                Node.GRID[x][y].populateNeighbors(withDiagonals)

    def setStartNode(self, node: Node):
        """
        Sets node as the start node and updates the GUI with it too
        """
        if not node.isEnd:
            self.start.isStart = False
            node.isStart = True

            self.start.cell.draw(Cell.EMPTY)

            self.start = node
            node.cell.setStart()

    def setEndNode(self, node: Node):
        """
        Sets node as the end node and updates the GUI with it too
        """
        if not node.isStart:
            self.end.isEnd = False
            node.isEnd = True

            self.end.cell.draw(Cell.EMPTY)

            self.end = node
            node.cell.setEnd()

    def mouseReleaseEvent(self, event):
        """
        Performs the actions necessary depending on what the user was doing with their click.
        NOTE: The mouse press events are handled by the Cells
        """

        cell = self.childAt(
            event.pos())  # Not guaranteed that this is actually a cell yet

        if self.changingStart:
            QApplication.restoreOverrideCursor()
            self.changingStart = False

            # Check that it is a cell and that it isn't either of the start or end nodes
            if isinstance(cell,
                          Cell) and not (cell.node.isEnd or cell.node.isStart):
                cell.setWall(False)
                self.setStartNode(cell.node)
            else:
                self.setStartNode(self.start)

        elif self.changingEnd:
            QApplication.restoreOverrideCursor()
            self.changingEnd = False

            # Check that it is a cell and that it isn't either of the start or end nodes
            if isinstance(cell,
                          Cell) and not (cell.node.isEnd or cell.node.isStart):
                cell.setWall(False)
                self.setEndNode(cell.node)
            else:
                self.setEndNode(self.end)

        elif self.erasingWall:
            self.erasingWall = False

        elif self.drawingWall:
            self.drawingWall = False

    def mouseMoveEvent(self, event):
        """
        Determines if the dragging is to make a wall or to remove it
        """

        if self.drawingWall:
            # Get widget at that position
            cell = self.childAt(event.pos())

            # Check that it is a cell and that it isn't either of the start or end nodes
            if isinstance(cell,
                          Cell) and not (cell.node.isEnd or cell.node.isStart):
                cell.setWall(True)

        elif self.erasingWall:
            # Similar to above
            cell = self.childAt(event.pos())
            if isinstance(cell,
                          Cell) and not (cell.node.isEnd or cell.node.isStart):
                cell.setWall(False)

    def clearPastVisual(self):
        """
        Clears the visual that was last run
        """

        for x in range(self.numRows):
            for y in range(self.numCols):
                node = Node.GRID[x][y]

                # A*
                node.f = node.g = node.h = None

                if node.wall:
                    continue
                node.cell.draw(Cell.EMPTY)

                if node.isStart:
                    node.cell.setStart()
                elif node.isEnd:
                    node.cell.setEnd()

    def connectSignals(self):
        """
        Connects all necessary signals from GUI elements to their respective functions
        """

        self.ui.resetButton.clicked.connect(self.reset)
        self.ui.allowDiagonals.toggled.connect(self.populateNeighbors)

        def changeSpeed(val):
            # val ranges from 0 to 99. at 99, slowdown is .001, and at 0, .1
            algs.slowdown = .5 / (val + 1)

        self.ui.speedSlider.valueChanged.connect(changeSpeed)

        def runAStar():
            self.clearPastVisual()
            pathFound = algs.aStar(self.start, self.end)

            if not pathFound:
                QMessageBox.warning(self, 'No Path Found',
                                    'No paths were found.')

        self.ui.goButton.clicked.connect(runAStar)
class MainWindow(QMainWindow):
    def __init__(self, setting: Setting):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setting = setting
        self.click_event()

    def init_attr(self):
        # 初始化属性
        last_time = QDateTime.fromString(
            self.setting.get(Group.dynamic, Key.last_time), Qt.ISODate)
        self.ui.dateTimeEdit.setDateTime(last_time)
        # 初始化网页限制数
        self.ui.limitNum.setRange(-1, 200)
        self.ui.limitNum.setValue(
            int(self.setting.get(Group.dynamic, Key.limit_num)))

    def click_event(self):
        # 点击事件
        self.ui.openBtn.clicked.connect(self.open_dynamic_click)
        self.ui.scanBtn.clicked.connect(self.scan_dynamic_click)

    def open_dynamic_click(self):
        # 一键打开动态按钮
        # last_time = self.ui.dateTimeEdit.dateTime().toPython()
        # limit = self.ui.limitNum.value()

        # self.ui.detailTable.l

        # 打开链接
        url_list = [
            DYNAMIC_URL + item['bvid'] for item in self.wait_open_url_list
        ]
        open_myself_dynamic(url_list)
        # 页面更新最近一次扫描时间
        self.ui.dateTimeEdit.setDateTime(
            QDateTime.fromSecsSinceEpoch(self.last_time.timestamp()))
        # 保持最近一次扫描时间
        self.setting.set(Group.dynamic, Key.last_time,
                         self.last_time.isoformat())
        self.setting.set(Group.dynamic, Key.limit_num,
                         str(self.ui.limitNum.value()))

    def scan_dynamic_click(self):
        # 扫描动态
        limit = self.ui.limitNum.value()
        self.wait_open_url_list = to_obtain_dynamic_list(
            self.ui.dateTimeEdit.dateTime().toPython(), limit)
        # 将扫描结果显示在表格控件中
        self.scan_rst_view_table(self.wait_open_url_list)
        # 修改最后扫描时间
        self.last_time = datetime.datetime.now()

    def scan_rst_view_table(self, wait_open_url_list):
        detail_table_model = DetailTableModel(self.ui.detailTable)
        for item in wait_open_url_list:
            item['is_open'] = True
        detail_table_model.add_data(wait_open_url_list)
        # model = QStandardItemModel(0, 4, self.ui.detailTable)
        #
        # model.setHorizontalHeaderItem(0, QStandardItem("bvid"))
        # model.setHorizontalHeaderItem(1, QStandardItem("up"))
        # model.setHorizontalHeaderItem(2, QStandardItem("更新时间"))
        # model.setHorizontalHeaderItem(3, QStandardItem("是否打开"))
        #
        # for i in range(len(wait_open_url_list)):
        #     item = wait_open_url_list[i]
        #     c_index = 0
        #     for k_, v_ in item.items():
        #         model.setItem(i, c_index, QStandardItem(str(v_)))
        #         c_index += 1
        #     a = QStandardItem()
        #     a.setCheckable(True)
        #     a.setCheckState()
        #     model.setItem(i, 3, a)
        self.ui.detailTable.setModel(detail_table_model.get_model())
        self.ui.detailTable.setAlternatingRowColors(True)