Ejemplo n.º 1
0
    def init_ui(self):
        font = QFont()
        font.setPointSize(12)

        self.tableWidget = QTableWidget(self)
        self.tableWidget.setGeometry(QtCore.QRect(140, 0, 260, 300))
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setRowCount(0)

        self.buttonGroup = QButtonGroup(self)
        for n, text in enumerate(['Новичок', 'Эксперт', 'Бывалый']):
            rb = QRadioButton(self)
            rb.setGeometry(QtCore.QRect(30, 100 + 30 * n, 91, 17))
            rb.setText(text)
            rb.setFont(font)
            self.buttonGroup.addButton(rb)
            self.buttonGroup.setId(rb, n)

        self.buttonGroup.buttonClicked.connect(self.choose_table)

        self.tableWidget.setHorizontalHeaderLabels(["Имя", "Время"])
        self.tableWidget.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)

        self.game_stat = GameStat()
        self.buttonGroup.button(0).click()
Ejemplo n.º 2
0
    def test(self, step):
        a = 0
        j = 0

        data = get_data(self.topic_id)

        correct = data[step]

        self.question.setText(correct[2])
        self.question.setGeometry(QRect(50, 52, 600, 80))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.question.setFont(font)
        self.question.setWordWrap(True)

        numbers = (self.length - 1 if self.length < 4 else 3)
        failed = random.sample(get_unique_data(self.topic_id, correct[1]), numbers)
        for i in random.sample(failed + [correct], numbers + 1):
            a += 30
            j += 1
            button_name = "radioButton" + str(j)
            button_name = QRadioButton(self.layout)
            if correct[0] != i[0]:
                self.button_group.addButton(button_name, correct[0])
            else:
                self.button_group.addButton(button_name, 0)

            button_name.setGeometry(QRect(50, 100 + a, 255, 17))
            button_name.setObjectName("radioButton" + str(j))
            button_name.setText(i[1])
            button_name.toggled.connect(self.get_answer)
            button_name.show()

        self.input_first.setText('Вопрос № ' + str(self.step + 1) + ' из ' + str(self.length))
Ejemplo n.º 3
0
def radioButtonTest(p):
    btn1 = QRadioButton("男")
    btn1.setChecked(True)
    # btn1.setCheckable(False)
    btn1.toggled.connect(lambda: radioButtonHandler(btn1))
    btn1.setParent(p)
    btn1.setGeometry(10, 20, 80, 30)
    btn1.setShortcut("Alt+M")  # 设置快捷
    btn2 = QRadioButton("女")
    btn2.setParent(p)
    btn2.setGeometry(10, 60, 80, 30)
    btn2.setShortcut("Alt+F")  # 设置快捷
    # 创建分组
    zu1 = QButtonGroup(p)  # 创建一个按钮分组实例
    # 参数2 给按钮设置一个id,不同分组的id可以重复
    # 如果id为-1,则将为该按钮分配一个id。自动分配的ID保证为负数,从-2开始。
    zu1.addButton(btn1, 1)  # 给按钮分组实例添加按钮
    zu1.addButton(btn2, 2)  # 给按钮分组实例添加按钮
    zu1.setExclusive(False)  #是否独占
    zu1.buttonToggled[int, bool].connect(zuButtonToggledHandler)
Ejemplo n.º 4
0
 def add_radio_button_field(self,
                            f_title,
                            top,
                            left,
                            items,
                            default_value,
                            layout='vertical',
                            label_margin=2,
                            label_font_size=LABEL_FONT_SIZE,
                            field_size=4):
     # add control to radio button field, set geometry, label and items
     label = QLabel(self.parent)
     label.setText(f_title)
     font = QFont()
     font.setPointSize(label_font_size)
     label.setFont(font)
     geo_label = QRect(left * self.width_step, top,
                       label_margin * self.width_step, 30)
     label.setGeometry(geo_label)
     i = 0
     button_group = QButtonGroup(self.parent)
     for but in items:
         button = QRadioButton(self.parent)
         if layout == 'vertical':
             geo_button = QRect((left + label_margin) * self.width_step,
                                top + (i) * 10,
                                field_size * self.width_step, 30)
             i += 2
         else:
             add = round((len(but) / 7), 0)
             geo_button = QRect(
                 (left + label_margin + i + 1) * self.width_step, top,
                 field_size * self.width_step, 30)
             i += 1
             i += add
         button.setText(but)
         if but == default_value:
             button.setChecked(True)
         button.setGeometry(geo_button)
         button_group.addButton(button)
     return button_group
Ejemplo n.º 5
0
class Second(QMainWindow):
    def __init__(self, parent=None):
        super(Second, self).__init__(parent)
        self.setMinimumSize(QSize(300, 150))
        self.setWindowTitle("Select option")

        layout = QHBoxLayout()
        self.b1 = QRadioButton("Android")
        self.b1.setChecked(True)
        self.b1.toggled.connect(lambda: self.btnstate(self.b1))
        layout.addWidget(self.b1)
        self.b1.setGeometry(20, 20, 320, 40)

        layout = QHBoxLayout()
        self.b2 = QRadioButton("Web")
        self.b2.toggled.connect(lambda: self.btnstate(self.b2))
        layout.addWidget(self.b2)
        self.b2.setGeometry(20, 50, 320, 40)

        self.btn = QPushButton('Submit', self)
        self.btn.clicked.connect(self.submitClickBox)
        self.btn.setGeometry(200, 100, 50, 35)

    def btnstate(self, b):
        if b.text() == "Android":
            if b.isChecked() == True:
                print("Android checked")
            else:
                print("Android not checked")
        elif b.text() == "Web":
            if b.isChecked() == True:
                print("Web Checked")
            else:
                print("Web not checked")

    def submitClickBox(self, state):
        self.close()

def radio2_event():
    global group2
    print("Button ID : ", group2.checkedId(), " / Button text : ", group2.checkedButton().text())


if __name__ == '__main__':
    app = QApplication(sys.argv)

    radio1_1 = QRadioButton('Radio 1_1')
    radio1_2 = QRadioButton('Radio 1_2')
    radio2_1 = QRadioButton('Radio 2_1')
    radio2_2 = QRadioButton('Radio 2_2')

    radio1_1.setGeometry(250, 100, 200, 50)
    radio1_2.setGeometry(500, 100, 200, 50)
    radio2_1.setGeometry(750, 100, 200, 50)
    radio2_2.setGeometry(1000, 100, 200, 50)

    group1 = QButtonGroup()
    group1.addButton(radio1_1, 1)
    group1.addButton(radio1_2, 2)

    group2 = QButtonGroup()
    group2.addButton(radio2_1, 1)
    group2.addButton(radio2_2, 2)

    radio1_1.show()
    radio1_2.show()
    radio2_1.show()
Ejemplo n.º 7
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(685, 443)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 20, 400, 400))
        self.label.setText("")
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(560, 50, 91, 21))
        self.lineEdit.setObjectName("lineEdit")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(520, 50, 31, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(520, 90, 21, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(560, 90, 91, 21))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(560, 130, 91, 21))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(520, 130, 31, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(520, 170, 131, 31))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        self.radiobutton = QRadioButton(self.centralwidget)
        self.radiobutton.setChecked(True)
        self.radiobutton.setFont(font)

        self.radiobutton_2 = QRadioButton(self.centralwidget)
        self.radiobutton_2.setChecked(True)
        self.radiobutton_2.setFont(font)
        self.radiobutton_2.setGeometry(QtCore.QRect(90, 5, 140, 15))

        self.radiobutton_3 = QRadioButton(self.centralwidget)
        self.radiobutton_3.setChecked(True)
        self.radiobutton_3.setFont(font)
        self.radiobutton_3.setGeometry(QtCore.QRect(160, 5, 210, 16))

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

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label_2.setText(_translate("MainWindow", "lon"))
        self.label_3.setText(_translate("MainWindow", "lat"))
        self.label_4.setText(_translate("MainWindow", "spn"))
        self.pushButton.setText(_translate("MainWindow", "Загрузить"))
        self.radiobutton.setText(_translate("MainWindow", "Спутник"))
        self.radiobutton_2.setText(_translate("MainWindow", "Схема"))
        self.radiobutton_3.setText(_translate("MainWindow", "Гибрид"))
Ejemplo n.º 8
0
class RSTP(QWidget):
    def __init__(self):
        super().__init__()

        self.raster = None

        self.tab1 = QLabel(self)
        self.setWindowTitle('RSTP')
        self.resize(480, 720)
        # Initialize tab screen
        self.widget = QTabWidget(self)
        self.widget.setGeometry(0, 0, 1280, 720)
        self.widget.addTab(self.tab1, "Merging")

        self.landsat8 = QRadioButton('Landsat 8', self.tab1)
        self.landsat7 = QRadioButton('Landsat 7', self.tab1)
        self.landsat5 = QRadioButton('Landsat 5', self.tab1)
        self.sentinel2 = QRadioButton('Sentinel 2', self.tab1)
        self.choose_input = QPushButton('Выберите файлы', self.tab1)
        self.text_input = QListWidget(self.tab1)
        self.start_merging = QPushButton("Начать объединение", self.tab1)
        self.save_merging = QPushButton('Сохранить результат', self.tab1)
        self.rgb_btn = QPushButton("Вывод в натуральных цветах", self.tab1)
        self.false1_btn = QPushButton('Вывод в искусственных цветах',
                                      self.tab1)
        self.water_surface_btn = QPushButton('Вывод в сочетании ИК-каналов',
                                             self.tab1)
        self.show_btn = QPushButton("Показать", self.tab1)

        self.setTab1()
        self.setTab2()
        self.setTab4()
        self.show()

    def setTab1(self):  # объединение
        self.landsat8.setGeometry(0, 0, 100, 20)
        self.landsat7.setGeometry(0, 20, 100, 20)
        self.landsat5.setGeometry(0, 40, 100, 20)
        self.sentinel2.setGeometry(0, 60, 100, 20)
        # кнопка для выбора файлов
        self.choose_input.setGeometry(0, 100, 200, 20)
        self.choose_input.clicked.connect(self.choose_files)
        # куда выводится выбор файлов
        self.text_input.setGeometry(0, 120, 200, 400)
        # кнопка начала процесса объединения
        self.start_merging.setGeometry(0, 540, 200, 20)
        self.start_merging.clicked.connect(self.merging_process)
        # кнопка сохранения
        self.save_merging.setGeometry(0, 560, 200, 20)
        self.save_merging.clicked.connect(self.merging_save)
        # кнопка вывода изображения в натуральных цветах
        self.rgb_btn.setGeometry(0, 580, 200, 20)
        self.rgb_btn.clicked.connect(self.rgb_show)
        self.false1_btn.setGeometry(0, 600, 200, 20)
        self.false1_btn.clicked.connect(self.false1_show)
        self.water_surface_btn.setGeometry(0, 620, 200, 20)
        self.water_surface_btn.clicked.connect(self.water_surface_show)
        self.show_btn.setGeometry(0, 640, 200, 20)

    def setTab2(self):  # яркостная температура
        self.tab2 = QWidget(self)

        # Add tabs
        self.widget.addTab(self.tab2, "BT")
        # радиокнопки
        self.TIRS = QRadioButton('Landsat 8 TIRS', self.tab2)
        self.TIRS.setGeometry(0, 0, 120, 20)
        self.ETM = QRadioButton('Landsat 7 ETM+', self.tab2)
        self.ETM.setGeometry(0, 20, 120, 20)
        self.TM = QRadioButton('Landsat 5 TM', self.tab2)
        self.TM.setGeometry(0, 40, 120, 20)
        self.MSI = QRadioButton('Sentinel 2 MSI', self.tab2)
        self.MSI.setGeometry(0, 60, 120, 20)
        # выбор канала
        self.thermal_select = QPushButton('Выберите канал', self.tab2)
        self.thermal_select.setGeometry(0, 80, 200, 20)
        self.thermal_select.clicked.connect(self.bt_select)
        # сохранение
        self.thermal_save = QPushButton('Сохранить файл', self.tab2)
        self.thermal_save.setGeometry(0, 100, 200, 20)
        self.thermal_save.clicked.connect(self.bt_save)
        # показ
        self.thermal_show = QPushButton('Показ результата', self.tab2)
        self.thermal_show.setGeometry(0, 120, 200, 20)
        self.thermal_show.clicked.connect(self.bt_show)

    def setTab4(self):  # кластеризация
        self.tab4 = QWidget(self)
        self.widget.addTab(self.tab4, 'Clustering')
        self.cluster_select = QPushButton(
            'Выберите мульти-\nспектральный набор данных', self.tab4)
        self.cluster_select.setGeometry(0, 0, 200, 40)
        self.cluster_select.clicked.connect(self.cluster_selection)

    def choose_files(self):
        self.text_input.clear()
        self.fname = QFileDialog.getOpenFileNames(self, 'Open file', 'C:/')

        if not self.fname:
            print('Please, select files again')
        else:
            print(self.fname)
            for i in self.fname:
                self.text_input.addItem(str(i))
            for i in range(len(self.fname)):
                print(self.fname[i])

    def merging_process(self):
        self.bands = 0
        self.raster = Landsat8(self.fname[1])
        print(self.fname)
        print('проверка условия')
        if self.sentinel2.isChecked():
            band = gdal.Open(str(self.fname[2]))
            self.x = band.RasterXSize
            self.y = band.RasterYSize
            self.proj = band.GetProjection()
            self.transform = band.GetGeoTransform()
            print('условие пройдено')
            print(self.x, self.y)
        else:
            band = gdal.Open(str(self.fname[1]))
            self.x = band.RasterXSize
            self.y = band.RasterYSize
            self.proj = band.GetProjection()
            self.transform = band.GetGeoTransform()
            print('условие пройдено')
            print(self.x, self.y)
        print('пробегаемся по каналам')
        for i in range(len(self.fname)):
            self.bands = self.bands + 1
            print(self.bands)
            band = gdal.Open(str(self.fname[i]))
            print('большое условие')
            if self.landsat8.isChecked():  # ландсат 8
                # к нормализованным добавить множитель uint16bit, выводить через matplotlib нормализованные, а в файл добавлять ненормализованные
                if 'B1' in self.fname[i]:
                    self.coastal_aerosol = band.GetRasterBand(1).ReadAsArray()
                    self.coastal_aerosol[self.coastal_aerosol == 0] = numpy.nan
                elif 'B2' in self.fname[i]:
                    self.blue = band.GetRasterBand(1).ReadAsArray()
                    self.blue[self.blue == 0] = numpy.nan
                elif 'B3' in self.fname[i]:
                    self.green = band.GetRasterBand(1).ReadAsArray()
                    self.green[self.green == 0] = numpy.nan
                elif 'B4' in self.fname[i]:
                    self.red = band.GetRasterBand(1).ReadAsArray()
                    self.red[self.red == 0] = numpy.nan
                elif 'B5' in self.fname[i]:
                    self.NIR = band.GetRasterBand(1).ReadAsArray()
                    self.NIR[self.NIR == 0] = numpy.nan
                elif 'B6' in self.fname[i]:
                    self.SWIR1 = band.GetRasterBand(1).ReadAsArray()
                    self.SWIR1[self.SWIR1 == 0] = numpy.nan
                elif 'B7' in self.fname[i]:
                    self.SWIR2 = band.GetRasterBand(1).ReadAsArray()
                    self.SWIR2[self.SWIR2 == 0] = numpy.nan
            elif self.landsat7.isChecked() or self.landsat5.isChecked(
            ):  # ландсат 7, 5
                if 'B1' in self.fname[i]:
                    self.blue = band.GetRasterBand(1).ReadAsArray()
                    self.blue[self.blue == 0] = numpy.nan
                elif 'B2' in self.fname[i]:
                    self.green = band.GetRasterBand(1).ReadAsArray()
                    self.green[self.green == 0] = numpy.nan
                elif 'B3' in self.fname[i]:
                    self.red = band.GetRasterBand(1).ReadAsArray()
                    self.red[self.red == 0] = numpy.nan
                elif 'B4' in self.fname[i]:
                    self.NIR = band.GetRasterBand(1).ReadAsArray()
                    self.NIR[self.NIR == 0] = numpy.nan
                elif 'B5' in self.fname[i]:
                    self.SWIR1 = band.GetRasterBand(1).ReadAsArray()
                    self.SWIR1[self.SWIR1 == 0] = numpy.nan
                elif 'B6' in self.fname[i]:
                    self.TIR = band.GetRasterBand(1).ReadAsArray()
                    self.TIR[self.TIR == 0] = numpy.nan
                elif 'B7' in self.fname[i]:
                    self.SWIR2 = band.GetRasterBand(1).ReadAsArray()
                    self.SWIR2[self.SWIR2 == 0] = numpy.nan
            elif self.sentinel2.isChecked():  # сентинель 2
                if 'B01' in self.fname[i]:
                    self.coastal_aerosol = band.GetRasterBand(1).ReadAsArray()
                elif 'B02' in self.fname[i]:
                    self.blue = band.GetRasterBand(1).ReadAsArray()
                    #self.blue[self.blue == 0] = numpy.nan
                elif 'B03' in self.fname[i]:
                    self.green = band.GetRasterBand(1).ReadAsArray()
                    #self.green[self.green == 0] = numpy.nan
                elif 'B04' in self.fname[i]:
                    self.red = band.GetRasterBand(1).ReadAsArray()
                    #self.red[self.red == 0] = numpy.nan
                elif 'B05' in self.fname[i]:
                    self.VRE1 = band.GetRasterBand(1).ReadAsArray()
                    #self.VRE1[self.VRE1 == 0] = numpy.nan
                elif 'B06' in self.fname[i]:
                    self.VRE2 = band.GetRasterBand(1).ReadAsArray()
                    #self.VRE2[self.green == 0] = numpy.nan
                elif 'B07' in self.fname[i]:
                    self.VRE3 = band.GetRasterBand(1).ReadAsArray()
                    #self.VRE3[self.VRE3 == 0] = numpy.nan
                elif 'B08' in self.fname[i]:
                    self.NIR = band.GetRasterBand(1).ReadAsArray()
                    #self.NIR[self.NIR == 0] = numpy.nan
                elif 'B09' in self.fname[i]:
                    self.water_vapour = band.GetRasterBand(1).ReadAsArray()
                    #self.water_vapour[self.water_vapour == 0] = numpy.nan
                elif 'B10' in self.fname[i]:
                    self.SWIR1 = band.GetRasterBand(1).ReadAsArray()
                    #self.SWIR1[self.SWIR1 == 0] = numpy.nan
                elif 'B11' in self.fname[i]:
                    self.SWIR2 = band.GetRasterBand(1).ReadAsArray()
                    #self.SWIR2[self.SWIR2 == 0] = numpy.nan
                elif 'B12' in self.fname[i]:
                    self.SWIR3 = band.GetRasterBand(1).ReadAsArray()
                    #self.SWIR3[self.SWIR3 == 0] = numpy.nan

        QMessageBox.question(
            self, 'Предпроцесс завершён',
            'Начните сохранение обработанных данных или их показ',
            QMessageBox.Ok, QMessageBox.Ok)

    def merging_save(self):
        print('start stacking')
        driver = gdal.GetDriverByName("GTiff")
        outputname = QFileDialog.getSaveFileName(self, 'Save file')
        if outputname is None:
            QMessageBox.question(self, 'Выберите снова', "ВЫберите снова файл",
                                 QMessageBox.Ok, QMessageBox.Ok)
        output = driver.Create(str(outputname), self.x, self.y, self.bands,
                               gdal.GDT_UInt16)
        if self.landsat8.isChecked():
            allbands = numpy.stack(
                (self.coastal_aerosol, self.blue, self.green, self.red,
                 self.NIR, self.SWIR1, self.SWIR2))
            for i in range(self.bands):
                output.GetRasterBand(i + 1).WriteArray(allbands[i])
        elif self.landsat7.isChecked() or self.landsat5.isChecked():
            allbands = numpy.stack((self.blue, self.green, self.red, self.NIR,
                                    self.SWIR1, self.TIR, self.SWIR2))
            for i in range(self.bands):
                output.GetRasterBand(i + 1).WriteArray(allbands[i])
        elif self.sentinel2.isChecked():
            for i in range(self.bands):
                print('большое сохранение')
                if i + 1 == 1:
                    output.GetRasterBand(i + 1).WriteArray(
                        self.coastal_aerosol)
                elif i + 1 == 2:
                    output.GetRasterBand(i + 1).WriteArray(self.blue)
                elif i + 1 == 3:
                    output.GetRasterBand(i + 1).WriteArray(self.green)
                elif i + 1 == 4:
                    output.GetRasterBand(i + 1).WriteArray(self.red)
                elif i + 1 == 5:
                    output.GetRasterBand(i + 1).WriteArray(self.VRE1)
                elif i + 1 == 6:
                    output.GetRasterBand(i + 1).WriteArray(self.VRE2)
                elif i + 1 == 7:
                    output.GetRasterBand(i + 1).WriteArray(self.VRE3)
                elif i + 1 == 8:
                    output.GetRasterBand(i + 1).WriteArray(self.NIR)
                elif i + 1 == 9:
                    output.GetRasterBand(i + 1).WriteArray(self.water_vapour)
                elif i + 1 == 10:
                    output.GetRasterBand(i + 1).WriteArray(self.SWIR1)
                elif i + 1 == 11:
                    output.GetRasterBand(i + 1).WriteArray(self.SWIR2)
                elif i + 1 == 12:
                    output.GetRasterBand(i + 1).WriteArray(self.SWIR3)
        output.SetProjection(self.proj)
        output.SetGeoTransform(self.transform)
        allbands = None
        output = None

        QMessageBox.question(
            self, 'Сохранение завершено',
            'Теперь вы можете открыть сохраненный файл в QGIS/ArcGIS',
            QMessageBox.Ok, QMessageBox.Ok)

    def rgb_show(self):  # натуральные цвета
        if self.landsat8.isChecked():
            rgb = numpy.dstack((self.red, self.green, self.blue))
            scaled_rgb = (rgb * (255 / 65535)).astype(numpy.uint8)

            plotted = plt.imshow(scaled_rgb)
            plt.xlabel('Сочетание красного, зелёного и синего каналов')
            plt.show()
        if self.landsat7.isChecked() or self.landsat5.isChecked():
            rgb = numpy.dstack((self.red, self.green, self.blue))
            plotted = plt.imshow(rgb)
            plt.xlabel('Сочетание красного, зелёного и синего каналов')
            plt.show()
        if self.sentinel2.isChecked():
            QMessageBox.question(
                self, 'Недоступно',
                "К сожалению, показ недоступен для Sentinel 2", QMessageBox.Ok,
                QMessageBox.Ok)
            '''
            rgb = numpy.dstack((self.red, self.green, self.blue))
            scaled_rgb = (rgb * (255 / 65535)).astype(numpy.uint8)

            plotted = plt.imshow(rgb)
            plt.xlabel('Сочетание красного, зелёного и синего каналов')
            plt.show()
            '''

    def false1_show(self):  # инфракрасный, ближний ИК + красный + зеленый
        if self.landsat8.isChecked():
            nrg = numpy.dstack((self.NIR, self.red, self.green))
            scaled_nrg = (nrg * (255 / 65535)).astype(numpy.uint8)

            plotted = plt.imshow(scaled_nrg)
            plt.xlabel('Сочетание красного, зелёного и синего каналов')
            plt.show()
        if self.landsat7.isChecked() or self.landsat5.isChecked():
            nrg = numpy.dstack((self.NIR, self.red, self.green))
            plotted = plt.imshow(nrg)
            plt.xlabel('Сочетание красного, зелёного и синего каналов')
            plt.show()
        if self.sentinel2.isChecked():
            QMessageBox.question(
                self, 'Недоступно',
                "К сожалению, показ недоступен для Sentinel 2", QMessageBox.Ok,
                QMessageBox.Ok)

    def water_surface_show(self):  # проникает через дым, SWIR2+SWIR1+NIR
        if self.landsat8.isChecked():
            water_surface = numpy.dstack((self.SWIR2, self.SWIR1, self.NIR))
            scaled_water_surface = (water_surface * (255 / 65535)).astype(
                numpy.uint8)
            plotted = plt.imshow(scaled_water_surface)
            plt.xlabel('Сочетание ИК каналов')
            plt.show()
        if self.landsat7.isChecked() or self.landsat5.isChecked():
            water_surface = numpy.dstack((self.SWIR2, self.SWIR1, self.NIR))
            plotted = plt.imshow(water_surface)
            plt.xlabel('Сочетание ИК каналов')
            plt.show()
        if self.sentinel2.isChecked():
            QMessageBox.question(
                self, 'Недоступно',
                "К сожалению, показ недоступен для Sentinel 2", QMessageBox.Ok,
                QMessageBox.Ok)

    def del_processed(self):
        del self.coastal_aerosol, self.blue, self.green, self.red, self.NIR, self.SWIR1, self.SWIR2, self.SWIR3, self.VRE1, self.VRE2, self.VRE3, self.TIR
        self.text_input.clear()
        del self.x, self.y, self.proj, self.transform
        self.bands = 0
        self.fname = []
        QMessageBox.question(self, '[ДАННЫЕ УДАЛЕНЫ]',
                             'Данные удалены из памяти', QMessageBox.Ok,
                             QMessageBox.Ok)

    def bt_select(self):
        # считывание метадаты
        metaname, _ = QFileDialog.getOpenFileName(
            self, 'Open metadata', 'C:/',
            'Text files (*.txt);;Текстовый документ (*.txt)')
        if not metaname:
            print('Please, select file again')
        else:
            print(metaname)
        # считывание канала
        fname, _ = QFileDialog.getOpenFileName(
            self, 'Open file', 'C:/',
            'TIF format (*.tif *.TIF);;TIFF format (*.tiff *.TIFF)')
        if fname == '':
            print('Please, select file again')
        else:
            thermalds = gdal.Open(fname)
            thermalband = thermalds.GetRasterBand(1)
            print(fname)
            self.x = thermalds.RasterXSize
            self.y = thermalds.RasterYSize
            self.proj = thermalds.GetProjection()
            self.transform = thermalds.GetGeoTransform()

        if self.TIRS.isChecked():
            # проверка констант через mtl файл
            if 'B10' in fname:
                metadata = open(metaname)
                for line in metadata:
                    if 'K1_CONSTANT_BAND_10' in line:
                        K1_CONSTANT_BAND_10 = float(line[26:-2])
                        print(K1_CONSTANT_BAND_10)
                    elif 'K2_CONSTANT_BAND_10' in line:
                        K2_CONSTANT_BAND_10 = float(line[26:-2])
                        print(K2_CONSTANT_BAND_10)
                therm1 = numpy.array(thermalband.ReadAsArray(),
                                     dtype=numpy.float32)
                therm1[therm1 == 0] = numpy.nan

                therm_radiance = (therm1 * 0.0003342) + 0.1

                self.therm_BT = K2_CONSTANT_BAND_10 / numpy.log(
                    (K1_CONSTANT_BAND_10 / therm_radiance) + 1)
            elif 'B11' in fname:
                metadata = open(metaname)
                for line in metadata:
                    if 'K1_CONSTANT_BAND_11' in line:
                        K1_CONSTANT_BAND_11 = float(line[26:-2])
                        print(K1_CONSTANT_BAND_11)
                    elif 'K2_CONSTANT_BAND_11' in line:
                        K2_CONSTANT_BAND_11 = float(line[26:-2])
                        print(K2_CONSTANT_BAND_11)
                therm1 = numpy.array(thermalband.ReadAsArray(),
                                     dtype=numpy.float32)
                therm1[therm1 == 0] = numpy.nan

                therm_radiance = (therm1 * 0.0003342) + 0.1
                self.therm_BT = K2_CONSTANT_BAND_11 / numpy.log(
                    (K1_CONSTANT_BAND_11 / therm_radiance) + 1)
        QMessageBox.question(
            self, 'Предпроцесс завершен',
            'Вы можете сохранить файл с результатом или отобразить его в отдельном окне',
            QMessageBox.Ok, QMessageBox.Ok)

    def bt_save(self):
        driver = gdal.GetDriverByName("GTiff")
        metadata = driver.GetMetadata()
        outputname, _ = QFileDialog.getSaveFileName(self, 'Save file', 'C:/')
        output = driver.Create(str(outputname), self.x, self.y, 1,
                               gdal.GDT_Float32)
        output.GetRasterBand(1).WriteArray(self.therm_BT)
        output.SetProjection(self.proj)
        output.SetGeoTransform(self.transform)
        output = None
        QMessageBox.question(self, 'Файл сохранен', 'Файл сохранен успешно',
                             QMessageBox.Ok, QMessageBox.Ok)

    def bt_show(self):  # показ яркостной температуры
        plotted = plt.imshow(self.therm_BT)
        plt.xlabel('Brightness temperature, Celsius')
        plt.show()

    def ndvi_selection(
            self):  # нужно доделать или исключить из списка инструментов
        self.ndvi_list.clear()
        fname, _ = QFileDialog.getOpenFileNames(self, 'Open file', 'C:/')
        if fname == [] or len(fname) > 2:
            print('Please, select files again or select only two channels')
            QMessageBox.question(
                self, 'Не удалось выбрать файлы',
                'Убедитесь, что вы выбрали красный и ближний инфракрасный каналы.',
                QMessageBox.Ok, QMessageBox.Ok)
        else:
            print(fname)
            for i in fname:
                self.text_input.addItem(str(i))
            for i in range(len(fname)):
                print(fname[i])
        Red = gdal.Open(fname[0])
        x = Red.RasterXSize
        y = Red.RasterYSize
        proj = Red.GetProjection()
        transform = Red.GetGeoTransform()
        NIR = gdal.Open(fname[1])
        NIRar = NIR.GetRasterBand(1).ReadAsArray().astype(numpy.float32)
        NIRarmin = NIRar.min()
        NIRarmax = NIRar.max()
        # therm_radiance=(therm1 * 0.0003342) + 0.1
        Redar = Red.GetRasterBand(1).ReadAsArray().astype(numpy.float32)
        Redarmax = Redar.max()
        Redarmin = Redar.min()
        NIRnorm = numpy.divide((NIRar - NIRarmin), (NIRarmax - NIRarmin))
        Rednorm = numpy.divide((Redar - Redarmin), (Redarmax - Redarmin))

        NDVInorm = numpy.divide((NIRnorm - Rednorm), (NIRnorm + Rednorm))
        plotted = plt.imshow(NDVInorm)
        plt.xlabel('NDVI normalized')
        plt.show()

        NDVI = numpy.divide((NIRar - Redar), (NIRar + Redar))
        plotted = plt.imshow(NDVI)
        plt.xlabel('NDVI non-normalized')
        plt.show()

        QMessageBox.question(self, 'Файл сохранен', 'Файл сохранен успешно',
                             QMessageBox.Ok, QMessageBox.Ok)

    def ndvi_saving(self):
        pass
        # a = 1
        # driver = gdal.GetDriverByName("GTiff")
        # metadata = driver.GetMetadata()
        # outputname, _ = QFileDialog.getSaveFileName(self, 'Save file', 'C:/')
        # output=driver.Create(str(outputname), x, y, 1,  gdal.GDT_Float32)
        # output.GetRasterBand(1).WriteArray(NDVI)
        # output.SetProjection( proj )
        # output.SetGeoTransform( transform )
        # output = None

    def cluster_selection(self):
        a = 1

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
Ejemplo n.º 9
0
class Ui_Dialog(object):
    def __init__(self, Dialog):
        super(Ui_Dialog, self).__init__()
        # ----- App Design ----- #
        # To make this to work in Fullscreen; set 'self.window_width' and 'self.window_height' to 'size.width()' and 'size.height()'
        # To make this to work in Fullscreen-Windowed; set 'self.window_width' and 'self.window_height' to 'rect.width()' and 'rect.height()'
        self.window_width = 500
        self.window_height = 800
        # self.window_width = size.width()    # Fullscreen
        # self.window_height = size.height()  # Fullscreen
        self.drop_down_width = self.window_width // 2 + 50
        self.notation_width = self.drop_down_width // 2
        self.widget_height = self.window_height // 20
        self.label_width = self.window_width // 4
        self.label_padding_left = self.window_width // 20
        self.content_padding_left = self.label_padding_left + self.label_width
        self.padding_top = self.window_height // 10
        self.v_space_between_widgets = self.window_height // 5

        self.app_font = QFont()
        self.output_text_font = QFont()
        self.app_font.setPointSize(
            (self.window_width + self.window_height) // 100)
        self.output_text_font.setPointSize(
            (self.window_width + self.window_height) // 120)

        self.label_style = 'color: rgb(176, 85, 87);'
        self.option_menu_style = 'color: rgb(158, 212, 124);'
        self.input_menu_style = 'color: rgb(15, 99, 189);'
        self.output_text_style = 'color: rgba(255, 255, 255, 150);'
        self.reset_button_style = '\
            background-color: red;\
            border-radius: 15px;\
            color: rgb(0, 0, 0);'

        # ----- App Window Settings ----- #
        Dialog.setObjectName("Dialog")
        self.set_window_resizable(window_obj=Dialog,
                                  width=self.window_width,
                                  height=self.window_height,
                                  flag=False)

        # ----- Widgets ----- #
        self.notation_label = QLabel(Dialog)
        self.notation_S = QRadioButton(Dialog)
        self.notation_b = QRadioButton(Dialog)
        self.option_label = QLabel(Dialog)
        self.option_menu = QComboBox(Dialog)
        self.input_label = QLabel(Dialog)
        self.input_menu = QComboBox(Dialog)
        self.output_label = QLabel(Dialog)
        self.output_text = QLineEdit(Dialog)
        self.reset_button = QPushButton(Dialog)
        self.va_button = QPushButton(Dialog)

        # ----- Music Logic ----- #
        music = Music()
        self.notesS = music.notesS
        self.notesb = music.notesb
        self.notes = self.notesS
        self.options_menu_vals = tuple()
        with open(features, 'r') as f:
            self.options_menu_vals = tuple([x.strip() for x in f.readlines()])
        self.input_menu_vals = tuple()
        self.rel_maj_min_options = ('Relative Major', 'Relative Minor')
        self.major_minor_options = ('Major', 'Minor')
        self.guitar_frets_options = tuple([str(i) for i in range(1, 23)
                                           ])  # For Capo position entry
        self.sub_menu_selected = dict()  # To Keep track of options selected
        self.select_data = '--Select--'
        self.option_change_detect = ''
        self.input_change_detect = ''

        # ----- Voice Assistant ----- #
        self.va = Voice_Assistant()

    def setupUi(self, Dialog):
        # Notations
        self.notation_label.setFont(self.app_font)
        self.notation_label.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width, self.widget_height))
        self.notation_label.setObjectName("notation_label")
        self.notation_label.setStyleSheet(self.label_style)
        self.notation_S.setFont(self.app_font)
        self.notation_S.setGeometry(
            QtCore.QRect(self.content_padding_left, self.padding_top,
                         self.notation_width, self.widget_height))
        self.notation_S.setObjectName("notation_S")
        self.notation_S.setChecked(True)
        self.notation_b.setFont(self.app_font)
        self.notation_b.setGeometry(
            QtCore.QRect(self.content_padding_left + self.notation_width,
                         self.padding_top, self.notation_width,
                         self.widget_height))
        self.notation_b.setObjectName("notation_b")

        self.padding_top += self.v_space_between_widgets
        # Option Menu
        self.option_label.setFont(self.app_font)
        self.option_label.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width, self.widget_height))
        self.option_label.setObjectName("options_label")
        self.option_label.setStyleSheet(self.label_style)
        self.option_menu.setFont(self.app_font)
        self.option_menu.setGeometry(
            QtCore.QRect(self.content_padding_left, self.padding_top - 2,
                         self.drop_down_width, self.widget_height))
        self.option_menu.setObjectName("option_menu")

        self.option_menu.addItem(self.select_data)
        self.option_menu.addItems(self.options_menu_vals)
        self.option_menu.currentIndexChanged.connect(
            self.option_selection_change)
        # self.option_menu.lineEdit().setAlignment(QtCore.Qt.AlignCenter)
        self.option_menu.setStyleSheet(self.option_menu_style)

        self.padding_top += self.v_space_between_widgets
        # Input Menu
        self.input_label.setFont(self.app_font)
        self.input_label.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width, self.widget_height))
        self.input_label.setObjectName("input_label")
        self.input_label.setStyleSheet(self.label_style)
        self.input_menu.setFont(self.app_font)
        self.input_menu.setGeometry(
            QtCore.QRect(self.content_padding_left, self.padding_top - 2,
                         self.drop_down_width, self.widget_height))
        self.input_menu.setObjectName("input_menu")
        self.input_menu.setDisabled(True)
        self.input_menu.setStyleSheet(self.input_menu_style)

        self.padding_top += self.v_space_between_widgets
        # Output
        self.output_label.setFont(self.app_font)
        self.output_label.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width, self.widget_height))
        self.output_label.setObjectName("output_label")
        self.output_label.setStyleSheet(self.label_style)
        self.output_text.setFont(self.output_text_font)
        self.output_text.setGeometry(
            QtCore.QRect(self.content_padding_left, self.padding_top - 2,
                         self.drop_down_width, self.widget_height))
        self.output_text.setObjectName("output_text")
        self.output_text.setDisabled(True)
        self.output_text.setStyleSheet(self.output_text_style)

        self.padding_top += self.v_space_between_widgets // 2
        # App RESET
        self.reset_button.setFont(self.app_font)
        self.reset_button.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width + self.drop_down_width,
                         self.widget_height))
        self.reset_button.setObjectName("reset_button")
        self.reset_button.clicked.connect(self.reset)
        self.reset_button.setIcon(QtGui.QIcon(reset_icon))
        self.reset_button.setIconSize(
            QtCore.QSize(self.widget_height, self.widget_height))
        self.reset_button.setStyleSheet(self.reset_button_style)

        self.padding_top += self.v_space_between_widgets // 2
        # Voice Assitant
        self.va_button.setFont(self.app_font)
        self.va_button.setGeometry(
            QtCore.QRect(self.label_padding_left, self.padding_top,
                         self.label_width + self.drop_down_width,
                         self.widget_height))
        self.va_button.setObjectName("va_button")
        self.va_button.clicked.connect(self.Voice_Assistant_Call)
        self.va_button.setIcon(QtGui.QIcon(app_logo))
        self.va_button.setIconSize(
            QtCore.QSize(self.widget_height, self.widget_height))
        self.va_button.setStyleSheet(self.reset_button_style)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def option_selection_change(self):
        selected_text = self.option_menu.currentText()

        # ----- Detect change in menu selection ----- #
        if self.option_change_detect != selected_text:
            print(self.sub_menu_selected)
            print('Option Menu Change Detected')
            # self.input_menu.clear()
            self.output_text.clear(
            )  # This is working; "input_menu.clear()" getting hanged
            self.input_menu.addItem(self.select_data)
            print('Input Menu cleared')
            self.option_change_detect = selected_text
            print('New opt change detect set')

        # ----- Change Input Menu Values ----- #
        if selected_text != self.select_data:
            print('Option Item Selected:', selected_text)
            self.input_menu.setDisabled(False)
            if selected_text == self.options_menu_vals[0]:  # Major Scale
                print('maj scale')
                if self.notation_S.isChecked():
                    self.notes = self.notesS
                elif self.notation_b.isChecked():
                    self.notes = self.notesb
                self.input_menu_vals = self.notes
            elif selected_text == self.options_menu_vals[1]:  # Major Chord
                print('maj chord')
                if self.notation_S.isChecked():
                    self.notes = self.notesS
                elif self.notation_b.isChecked():
                    self.notes = self.notesb
                self.input_menu_vals = self.notes
            elif selected_text == self.options_menu_vals[
                    2]:  # Chords in Major Scale
                print('chords in maj scale')
                if self.notation_S.isChecked():
                    self.notes = self.notesS
                elif self.notation_b.isChecked():
                    self.notes = self.notesb
                self.input_menu_vals = self.notes
            print('rcvd inp menu vals')
            self.input_menu.addItems(self.input_menu_vals)
            self.input_menu.currentIndexChanged.connect(
                self.input_selection_change)
            print('set inp menu vals')
        else:
            self.input_menu.clear()
            self.input_menu.setDisabled(True)

        # ----- To Keep track of Selections ----- #
        if self.option_menu.currentText(
        ) not in self.sub_menu_selected and self.option_menu.currentText(
        ) != self.select_data:
            self.sub_menu_selected[self.option_menu.currentText()] = []

    def input_selection_change(self):
        selected_text = self.input_menu.currentText()

        # ----- Detect change in menu selection ----- #
        if self.input_change_detect != selected_text:
            self.input_change_detect = selected_text

        # ----- Action performed on Input Menu Values ----- #
        if selected_text != self.select_data:
            option_menu_selected_text = self.option_menu.currentText()
            if option_menu_selected_text == self.options_menu_vals[
                    0]:  # Major Scale
                note = selected_text
                music = Music(note)
                result = music.major_scale()
                self.output_text.setText('     '.join(result))
            elif option_menu_selected_text == self.options_menu_vals[
                    1]:  # Major Chord
                note = selected_text
                music = Music(note)
                result = music.major_chord()
                self.output_text.setText('     '.join(result))
            elif option_menu_selected_text == self.options_menu_vals[
                    2]:  # Chords in Major Scale
                note = selected_text
                music = Music(note)
                result = music.chords_in_major_scale()
                self.output_text.setText('     '.join(result))

        # ----- To Keep track of Selections ----- #
        if self.option_menu.currentText() != self.select_data:
            if self.option_menu.currentText() in self.sub_menu_selected:
                self.sub_menu_selected[self.option_menu.currentText()].append(
                    selected_text)
                self.sub_menu_selected[self.option_menu.currentText()] = list(
                    set(self.sub_menu_selected[
                        self.option_menu.currentText()]))
            else:
                self.sub_menu_selected[self.option_menu.currentText()] = list(
                    set([selected_text]))

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Music Theory Guide"))
        self.notation_label.setText(_translate("Dialog", "Notation"))
        self.notation_S.setIcon(QtGui.QIcon(sharp_icon))
        self.notation_b.setIcon(QtGui.QIcon(flat_icon))
        self.option_label.setText(_translate("Dialog", "Options"))
        self.input_label.setText(_translate("Dialog", "Input"))
        self.output_label.setText(_translate("Dialog", "Output"))
        self.output_text.setText(_translate("Dialog", ""))
        self.reset_button.setText(_translate("Dialog", "Reset Application"))
        self.va_button.setText(_translate("Dialog", "Voice Assistant"))

    def set_window_resizable(self, window_obj, width, height, flag=False):
        if not flag:
            window_obj.setGeometry(rect.width() // 2 - width // 2,
                                   rect.height() // 2 - height // 2, width,
                                   height)
            window_obj.setMaximumHeight(height)
            window_obj.setMinimumHeight(height)
            window_obj.setMaximumWidth(width)
            window_obj.setMinimumWidth(width)
        else:
            window_obj.resize(width, height)

    def reset(self):
        self.notation_S.setChecked(True)
        self.option_menu.setCurrentIndex(0)
        self.input_menu.clear()
        self.output_text.setText('')

    def Voice_Assistant_Call(self):
        self.va.start_AI_engine()
Ejemplo n.º 10
0
class AppStimed(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)  #memanggil beberapa fungsi

        self.tableModel()
        self.groupBoxOther()
        self.txtAction()
        self.btnAction()
        self.gridLayout1()
        self.gridLayout2()
        self.gridLayout3()
        self.verticalLay()

        self.setWindowTitle("Data Mahasiswa STIMED Nusa Palapa")
        self.setGeometry(340, 50, 658, 650)
        self.setWindowIcon(QIcon("folderIcon/memed.png"))

    def tableModel(self):
        self.table = QTableWidget(0, 6)
        self.table.setHorizontalHeaderLabels(
            ['Nim', 'Nama', 'Jurusan', 'Tahun Masuk', 'Alamat', 'Agama'])
        self.table.setEditTriggers(
            QTableWidget.NoEditTriggers)  #nonaktifkan untuk edit di tabel
        self.table.setSelectionBehavior(
            QTableWidget.SelectRows)  #agar semua 1 baris terseleksi

    def groupBoxOther(self):
        self.groupBoxJrsn = QGroupBox(" [ Pilih Jurusan ] ", self)
        self.groupBoxForm = QGroupBox(" [ Isi Form ] ", self)
        self.groupBoxBtn = QGroupBox(" [ Tekan Tombol Berikut ] ", self)
        self.groupBoxCari = QGroupBox(" [ Search && Order ] ", self)

        self.radio1 = QRadioButton("TI (S1)", self.groupBoxJrsn)
        self.radio1.setGeometry(10, 20, 110, 20)
        self.radio2 = QRadioButton("SI (S1)", self.groupBoxJrsn)
        self.radio2.setGeometry(10, 40, 110, 20)

        self.radio1.toggled.connect(self.radio1Checked)
        self.radio2.toggled.connect(self.radio2Checked)

        self.lineV = QFrame(self.groupBoxJrsn)
        self.lineV.setGeometry(200, 10, 20, 50)
        self.lineV.setFrameShape(QFrame.VLine)
        self.lineV.setFrameShadow(QFrame.Sunken)

    def txtAction(self):
        self.lblNim = QLabel("Nim                        :")
        self.txtNim = QLineEdit()
        self.txtNim.setPlaceholderText("ex : 01510002 - tekan tombol help")
        self.txtNim.setMaxLength(8)

        self.lblNama = QLabel("Nama                     :")
        self.txtNama = QLineEdit()
        self.txtNama.setPlaceholderText("ex : imo")

        self.lblTahun = QLabel("Tahun Masuk         : ")
        self.txtTahun = QLineEdit()
        self.txtTahun.setPlaceholderText("ex : 2015")
        self.txtTahun.setMaxLength(4)

        self.lblAlamat = QLabel("Alamat                   :")
        self.txtAlamat = QLineEdit()
        self.txtAlamat.setPlaceholderText("ex : Jl. Budidaya, Antang")

        self.lblAgama = QLabel("Agama                   :")
        self.txtAgama = QLineEdit()
        self.txtAgama.setPlaceholderText("ex : Islam")

        self.lblCari = QLabel("Cari Nama             :", self.groupBoxCari)
        self.lblCari.setGeometry(10, 20, 100, 10)
        self.txtCari = QLineEdit()
        self.txtCari.setPlaceholderText("ex : Rafika")
        self.lblOrder = QLabel("<u>Urutkan semua data secara Asc :</u>",
                               self.groupBoxCari)

        self.lblKeterangan = QLabel("<u>Keterangan Jurusan</u> :",
                                    self.groupBoxJrsn)
        self.lblKeterangan.setGeometry(250, 10, 110, 13)
        self.lblJrsan = QLabel("", self.groupBoxJrsn)
        self.lblJrsan.setGeometry(250, 30, 110, 13)

    def btnAction(self):
        self.btnSimpan = QPushButton('&Simpan')
        self.btnSimpan.clicked.connect(self.simpanData)
        self.btnSimpan.clicked.connect(self.loadData)

        self.btnUpdate = QPushButton('&Update')
        self.btnUpdate.clicked.connect(self.updateData)
        self.btnUpdate.clicked.connect(self.loadData)

        self.btnEdit = QPushButton('&Edit')
        self.btnEdit.clicked.connect(self.editData)

        self.btnHapus = QPushButton('&Hapus')
        self.btnHapus.clicked.connect(self.hapusData)

        self.btnReset = QPushButton('&Reset')
        self.btnReset.clicked.connect(self.resetTxt)
        self.btnReset.clicked.connect(self.loadData)

        self.btnExit = QPushButton('&Exit')
        self.btnExit.clicked.connect(self.close)

        self.btnPrint = QPushButton('&Print')
        self.btnPrint.clicked.connect(self.printTable)

        self.information = QPushButton('&Help')
        self.information.clicked.connect(self.helpMeWoi)

        self.btnCari = QPushButton("Cari", self.groupBoxCari)
        self.btnCari.clicked.connect(self.cariData)

        self.btnOrderNamaAsc = QPushButton("Order by nama", self.groupBoxCari)
        self.btnOrderNamaAsc.clicked.connect(self.loadData)
        self.btnOrderNamaAsc.clicked.connect(self.orderNamaAsc)

        self.btnOrderThnAsc = QPushButton("Order by tahun masuk",
                                          self.groupBoxCari)
        self.btnOrderThnAsc.clicked.connect(self.loadData)
        self.btnOrderThnAsc.clicked.connect(self.orderThnAsc)

    def gridLayout1(self):  #txt,jrsn,label
        self.grid = QGridLayout(self.groupBoxForm)
        self.grid.setContentsMargins(10, 10, 110, 10)
        self.grid.addWidget(self.lblNim, 0, 0)
        self.grid.addWidget(self.txtNim, 0, 1)
        self.grid.addWidget(self.lblNama, 1, 0)
        self.grid.addWidget(self.txtNama, 1, 1)
        self.grid.addWidget(self.groupBoxJrsn, 2, 1, 12, 1)
        self.grid.addWidget(self.lblTahun, 17, 0)
        self.grid.addWidget(self.txtTahun, 17, 1)
        self.grid.addWidget(self.lblAlamat, 18, 0)
        self.grid.addWidget(self.txtAlamat, 18, 1)
        self.grid.addWidget(self.lblAgama, 19, 0)
        self.grid.addWidget(self.txtAgama, 19, 1)

    def gridLayout2(self):  #gboxCari
        self.grid2 = QGridLayout(self.groupBoxCari)
        self.grid2.setContentsMargins(110, 5, 110,
                                      5)  #margin kiri,atas, kanan, bawah
        self.grid2.addWidget(self.txtCari, 0, 0, 1,
                             0)  #baris 0 kolom 0 sampai, kolom 1
        self.grid2.addWidget(self.btnCari, 1, 0, 1, 0)
        self.grid2.addWidget(self.lblOrder, 2, 0, 1, 0)
        self.grid2.addWidget(self.btnOrderNamaAsc, 3, 0)
        self.grid2.addWidget(self.btnOrderThnAsc, 3, 1)

    def gridLayout3(self):  #actionBtn
        self.grid3 = QGridLayout(self.groupBoxBtn)
        self.grid3.addWidget(self.btnSimpan, 0, 0)
        self.grid3.addWidget(self.btnHapus, 1, 0)
        self.grid3.addWidget(self.btnEdit, 0, 1)
        self.grid3.addWidget(self.btnUpdate, 1, 1)
        self.grid3.addWidget(self.btnPrint, 0, 2)
        self.grid3.addWidget(self.btnReset, 1, 2)
        self.grid3.addWidget(self.btnExit, 0, 3)
        self.grid3.addWidget(self.information, 1, 3)

    def verticalLay(self):
        self.vbx = QVBoxLayout()
        self.vbx.addWidget(self.groupBoxForm)
        self.vbx.addWidget(self.groupBoxCari)
        self.vbx.addWidget(self.groupBoxBtn)
        self.vbx.addWidget(self.table)

        self.setLayout(self.vbx)  #membuat vbx sebagai Layout utama

    def radio1Checked(self, enable):
        if enable:
            self.lblJrsan.setText("Teknik Informatika")

    def radio2Checked(self, enable):
        if enable:
            self.lblJrsan.setText("Sistem Informasi")

    def cariData(self):
        print("ini cari")
        cariNama = self.txtCari.text()
        index = 0
        query = QSqlQuery()
        query.exec_(
            "SELECT * FROM tbl_mahasiswa WHERE nama LIKE '%{0}%'".format(
                cariNama))

        while query.next():
            nimMhs = query.value(0)
            namaMhs = query.value(1)
            jrsMhs = query.value(2)
            thnMhs = query.value(3)
            alamatMhs = query.value(4)
            agamaMhs = query.value(5)

            self.table.setRowCount(index + 1)
            self.table.setItem(index, 0, QTableWidgetItem(str(nimMhs)))
            self.table.setItem(index, 1, QTableWidgetItem(namaMhs))
            self.table.setItem(index, 2, QTableWidgetItem(jrsMhs))
            self.table.setItem(index, 3, QTableWidgetItem(str(thnMhs)))
            self.table.setItem(index, 4, QTableWidgetItem(alamatMhs))
            self.table.setItem(index, 5, QTableWidgetItem(agamaMhs))
            index += 1

    def loadData(self):
        index = 0
        query = QSqlQuery()
        query.exec_("SELECT * FROM tbl_mahasiswa")

        while query.next():
            nimMhs = query.value(0)
            namaMhs = query.value(1)
            jrsMhs = query.value(2)
            thnMhs = query.value(3)
            alamatMhs = query.value(4)
            agamaMhs = query.value(5)

            self.table.setRowCount(index + 1)
            self.table.setItem(index, 0, QTableWidgetItem(str(nimMhs)))
            self.table.setItem(index, 1, QTableWidgetItem(namaMhs))
            self.table.setItem(index, 2, QTableWidgetItem(jrsMhs))
            self.table.setItem(index, 3, QTableWidgetItem(str(thnMhs)))
            self.table.setItem(index, 4, QTableWidgetItem(alamatMhs))
            self.table.setItem(index, 5, QTableWidgetItem(agamaMhs))
            index += 1

    def simpanData(self):
        try:
            nimMhs = self.txtNim.text()
            namaMhs = self.txtNama.text()
            jrsMhs = self.lblJrsan.text()
            thnMhs = int(self.txtTahun.text())
            alamatMhs = self.txtAlamat.text()
            agamaMhs = self.txtAgama.text()

            query = QSqlQuery()
            query.exec_("INSERT INTO tbl_mahasiswa VALUES('{0}', '{1}', '{2}', {3}, '{4}', '{5}')".\
                        format(nimMhs, namaMhs, jrsMhs, thnMhs, alamatMhs, agamaMhs))
        except ValueError:
            QMessageBox.critical(
                self, "Terjadi Error", "Coba periksa data yang anda input.\n"
                "Mungkin terjadi kesalahan padan penginputan\n\n"
                "Klik Yes untuk mencoba lagi.", QMessageBox.Yes)
        self.resetTxt()

    def editData(self):
        try:
            selected = self.table.currentIndex()
            if not selected.isValid() or len(self.table.selectedItems()) < 1:
                return

            print(not selected.isValid())
            self.nimMhs = self.table.selectedItems()[0]
            namaMhs = self.table.selectedItems()[1]
            jrsMhs = self.table.selectedItems()[2]
            thnMhs = self.table.selectedItems()[3]
            alamatMhs = self.table.selectedItems()[4]
            agamaMhs = self.table.selectedItems()[5]

            self.txtNim.setText(str(self.nimMhs.text()))
            self.txtNama.setText(str(namaMhs.text()))
            self.lblJrsan.setText(str(jrsMhs.text()))
            self.txtTahun.setText(str(thnMhs.text()))
            self.txtAlamat.setText(str(alamatMhs.text()))
            self.txtAgama.setText(str(agamaMhs.text()))
        except ValueError:
            print(ValueError)

    def updateData(self):
        try:
            namaMhs = self.txtNama.text()
            jrsMhs = self.lblJrsan.text()
            thnMhs = int(self.txtTahun.text())
            alamatMhs = self.txtAlamat.text()
            agamaMhs = self.txtAgama.text()

            query = QSqlQuery()
            query.exec_("UPDATE tbl_mahasiswa SET nama='{0}', jurusan='{1}', thn_masuk={2},\
                        alamat='{3}', agama='{4}' WHERE nim='{5}'"\
                        .format(namaMhs, jrsMhs, thnMhs, alamatMhs, agamaMhs,self.nimMhs.text()))
        except ValueError:
            QMessageBox.critical(
                self, "Update Gagal", "Coba periksa data yang anda input.\n"
                "Mungkin terjadi kesalahan pada penginputan\n\n"
                "Klik Yes untuk mencoba lagi.", QMessageBox.Yes)
        self.resetTxt()

    def hapusData(self):
        selected = self.table.currentIndex()
        if not selected.isValid() or len(self.table.selectedItems()) < 1:
            return

        nimMhs = self.table.selectedItems()[0]
        query = QSqlQuery()
        try:
            query.exec_("delete from tbl_mahasiswa where nim = " +
                        nimMhs.text())
        except ValueError:
            QMessageBox.critical(
                self, "Hapus Gagal", "Coba periksa data Table\n\n"
                "Klik Yes untuk mencoba lagi.", QMessageBox.Yes)
        self.table.removeRow(selected.row())
        self.table.setCurrentIndex(QModelIndex())

    def resetTxt(self):
        self.txtNim.clear()
        self.txtNama.clear()
        self.txtTahun.clear()
        self.txtAlamat.clear()
        self.txtAgama.clear()
        self.txtCari.clear()

    def orderNamaAsc(self):
        index = 0
        query = QSqlQuery()
        query.exec_("SELECT * FROM tbl_mahasiswa ORDER BY nama ASC")
        while query.next():
            nimMhs = query.value(0)
            namaMhs = query.value(1)
            jrsMhs = query.value(2)
            thnMhs = query.value(3)
            alamatMhs = query.value(4)
            agamaMhs = query.value(5)

            self.table.setRowCount(index + 1)
            self.table.setItem(index, 0, QTableWidgetItem(str(nimMhs)))
            self.table.setItem(index, 1, QTableWidgetItem(namaMhs))
            self.table.setItem(index, 2, QTableWidgetItem(jrsMhs))
            self.table.setItem(index, 3, QTableWidgetItem(str(thnMhs)))
            self.table.setItem(index, 4, QTableWidgetItem(alamatMhs))
            self.table.setItem(index, 5, QTableWidgetItem(agamaMhs))
            index += 1

    def orderThnAsc(self):
        index = 0
        query = QSqlQuery()
        query.exec_("SELECT * FROM tbl_mahasiswa ORDER BY thn_masuk ASC")
        while query.next():
            nimMhs = query.value(0)
            namaMhs = query.value(1)
            jrsMhs = query.value(2)
            thnMhs = query.value(3)
            alamatMhs = query.value(4)
            agamaMhs = query.value(5)

            self.table.setRowCount(index + 1)
            self.table.setItem(index, 0, QTableWidgetItem(str(nimMhs)))
            self.table.setItem(index, 1, QTableWidgetItem(namaMhs))
            self.table.setItem(index, 2, QTableWidgetItem(jrsMhs))
            self.table.setItem(index, 3, QTableWidgetItem(str(thnMhs)))
            self.table.setItem(index, 4, QTableWidgetItem(alamatMhs))
            self.table.setItem(index, 5, QTableWidgetItem(agamaMhs))
            index += 1

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Message', "Yakin ingin keluar ? ",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def printTable(self):
        printer = QPrinter(QPrinter.ScreenResolution)
        dlg = QPrintPreviewDialog(printer)
        view = PrintView()
        view.setModel(self.table.model())
        dlg.paintRequested.connect(view.printIni)
        dlg.exec_()

    def helpMeWoi(self):
        QMessageBox.information(self,"Butuh Bantuan ka kodong :V","<b>PETUNJUK !  **  <br/>I HAVE NEW RULES CIKA :V</b><br/><br/><br/>"\
                                "<i><b>IKUTI ATURANKU NAH :</b><br/><br/>"
                                "1. Penulisan nim masih belum bisa diawali dengan 0, karena tipe data Int<br/>"
                                "bila diubah ke Varchar maka database pada aplikasi tidak dapat terhapus<br/>"
                                "mungkin ada cara, but we, '<u>not found</u>' -,-<br/><br/>"
                                "2. Untuk update data, pilih terlebih dahulu data pada tabel setelah itu tekan<br/>"
                                "tombol edit dan akan muncul data yang terpilih dan tekan update jika selesai.<br/><br/>"
                                "3. Saat ini nim tidak dapat di update karena nim sebagai PrimaryKey<br/>"
                                "mungkin ada cara tapi kami belum menemukan source cara update PrimaryKey.<br/><br/><br/>"
                                "<i>Create on 08/02/2018,</i><br/>"
                                "<b>Created by: V:<b>")

    def db_connect(self, filename, server):
        db = QSqlDatabase.addDatabase(server)
        db.setDatabaseName(filename)
        ok = db.open()
        if not ok:
            QMessageBox.critical(
                self, "Tidak dapat membuka database", "Tidak dapat"
                "terhubung ke database.\n"
                "Cari di google tentang SQLite support. Baca tentang QtSQL"
                "\n\n\nKlik Ok untuk keluar.", QMessageBox.Ok)
            sys.exit()

    def db_create(self):
        query = QSqlQuery()
        query.exec_(
            "CREATE TABLE tbl_mahasiswa(nim VARCHAR(8) PRIMARY KEY,"
            "nama VARCHAR(20) NOT NULL, jurusan VARCHAR(15) NOT NULL, thn_masuk int, alamat VARCHAR(30) NOT NULL,\
                    agama VARCHAR(20) NOT NULL)")
        query.exec_(
            "insert into tbl_mahasiswa values('01510002', 'Rafika Ramayanti', 'Sistem Informasi', 2015,\
                    'Jl. Budidaya, antang', 'Islam')")

    def init(self, filename, server):
        import os
        if not os.path.exists(filename):
            self.db_connect(filename, server)
            self.db_create()
        else:
            self.db_connect(filename, server)
Ejemplo n.º 11
0
class new(
        QMainWindow
):  ####################################################################################################
    def __init__(self):
        super().__init__()
        self.title = 'Updating...'
        self.left = 500
        self.top = 200
        self.width = 390
        self.height = 400
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        heading = QLabel("Registration Form", self)
        heading.setGeometry(150, 20, 90, 13)
        with con:
            cur = con.cursor()
            print("Start")
            #cur.execute("SELECT * FROM Form WHERE EMAIL='%s'"%flag)
            print("Fetching,")

            rows = cur.fetchall()
            for row in rows:
                print("Username ="******"Password ="******"ReTyped =", row[2])
                print("Hint Question =", row[3])
                print("Hint Answer =", row[4])
                print("Gender =", row[5])
                print("Email =", row[6])

        username = QLabel("Username", self)
        username.setGeometry(60, 50, 50, 13)

        password = QLabel("Password", self)
        password.setGeometry(60, 80, 47, 13)

        re_pass = QLabel("Retype Password", self)
        re_pass.setGeometry(42, 110, 90, 13)

        hint_ques = QLabel("Hint Question", self)
        hint_ques.setGeometry(49, 140, 70, 13)

        hint_pass = QLabel("Hint Password", self)
        hint_pass.setGeometry(48, 180, 70, 13)

        gender = QLabel("Gender", self)
        gender.setGeometry(60, 220, 40, 13)

        mail = QLabel("Email ID", self)
        mail.setGeometry(60, 250, 47, 13)

        self.line_user = QLineEdit(self)
        self.line_user.setGeometry(160, 50, 190, 20)
        #self.line_user="******"

        self.line_pass = QLineEdit(self)
        self.line_pass.setEchoMode(QtWidgets.QLineEdit.Password)
        self.line_pass.setGeometry(160, 80, 190, 20)

        self.line_pass2 = QLineEdit(self)
        self.line_pass2.setEchoMode(QtWidgets.QLineEdit.Password)
        self.line_pass2.setGeometry(160, 110, 190, 20)

        self.box_ques = QComboBox(self)
        self.box_ques.setGeometry(160, 140, 190, 22)
        self.box_ques.addItem("What is your Name?")
        self.box_ques.addItem("What is your favourite Colour?")
        self.box_ques.addItem("In which City do you Live?")
        self.box_ques.addItem("What is your Nickname?")
        self.box_ques.addItem("Which Car do you Own?")

        self.line_hint = QLineEdit(self)
        self.line_hint.setGeometry(160, 180, 190, 20)
        self.line_hint.setEchoMode(QtWidgets.QLineEdit.Password)

        self.male_button = QRadioButton("Male", self)
        self.male_button.setGeometry(160, 220, 51, 17)

        self.female_button = QRadioButton("Female", self)
        self.female_button.setGeometry(270, 220, 60, 17)

        self.line_mail = QLineEdit(self)
        self.line_mail.setGeometry(160, 250, 190, 20)

        update_done = QPushButton("Update", self)
        update_done.setGeometry(120, 300, 75, 23)
Ejemplo n.º 12
0
class YuToolsDailyPlan(QWidget):
    def __init__(self):
        super().__init__()
        ActionDao.auto_update_action()
        self.txt_content = QPlainTextEdit(self)
        self.txt_content.setGeometry(10, 10, 350, 50)

        self.rb_begin = QRadioButton(self)
        self.rb_begin.setText('Begin')
        self.rb_begin.setChecked(True)
        self.rb_begin.setGeometry(10, 70, 50, 22)

        self.de_begin = QDateEdit(self)
        self.de_begin.setDate(QDate.currentDate())
        self.de_begin.setGeometry(70, 70, 90, 22)

        self.rb_begin.clicked.connect(
            lambda: self.rb_select_date(self.de_begin))

        self.rb_deadline = QRadioButton(self)
        self.rb_deadline.setText("Deadline")
        self.rb_deadline.setGeometry(180, 70, 60, 22)

        self.de_deadline = QDateEdit(self)
        self.de_deadline.setDate(QDate.currentDate().addDays(7))
        self.de_deadline.setGeometry(250, 70, 90, 22)

        self.rb_deadline.clicked.connect(
            lambda: self.rb_select_date(self.de_deadline))

        self.calendar_select = QCalendarWidget(self)
        self.calendar_select.setGeometry(10, 100, 256, 190)
        self.calendar_select.clicked.connect(self.select_date)

        self.combo_frequency = QComboBox(self)
        self.combo_frequency.addItem(PlanFrequency.NoRepeat.name)
        self.combo_frequency.addItem(PlanFrequency.Day.name)
        self.combo_frequency.addItem(PlanFrequency.Week.name)
        self.combo_frequency.addItem(PlanFrequency.Month.name)
        self.combo_frequency.addItem(PlanFrequency.Quarter.name)
        self.combo_frequency.addItem(PlanFrequency.Year.name)
        self.combo_frequency.setGeometry(280, 100, 80, 26)

        self.sb_repeat = QSpinBox(self)
        self.sb_repeat.setMinimum(1)
        self.sb_repeat.setGeometry(280, 130, 80, 26)

        self.cb_include = QCheckBox(self)
        self.cb_include.setText("Include Begin")
        self.cb_include.setChecked(True)
        self.cb_include.setGeometry(280, 160, 80, 26)

        self.combo_importance = QComboBox(self)
        self.combo_importance.addItem('Important')
        self.combo_importance.addItem('Unimportant')
        self.combo_importance.setGeometry(280, 190, 80, 26)

        self.combo_urgency = QComboBox(self)
        self.combo_urgency.addItem('Urgent')
        self.combo_urgency.addItem('Non-Urgent')
        self.combo_urgency.setGeometry(280, 220, 80, 26)

        self.btn_save = QPushButton(self)
        self.btn_save.setGeometry(280, 260, 80, 26)
        self.btn_save.setText("Save")
        self.btn_save.clicked.connect(self.save_plan)

        self.tb_plan = QTableView(self)
        self.tb_plan.horizontalHeader().setStretchLastSection(True)
        self.tb_plan.horizontalHeader().setSectionResizeMode(
            QHeaderView.Custom)
        self.tb_plan.verticalHeader().hide()
        self.tb_plan.setGeometry(370, 10, 421, 281)

        self.line_importance = QFrame(self)
        self.line_importance.setGeometry(390, 295, 20, 435)
        self.line_importance.setFrameShape(QFrame.VLine)
        self.line_importance.setFrameShadow(QFrame.Sunken)

        self.line_urgency = QFrame(self)
        self.line_urgency.setGeometry(5, 480, 791, 16)
        self.line_urgency.setFrameShape(QFrame.HLine)
        self.line_urgency.setFrameShadow(QFrame.Sunken)

        self.combo_ac_list_filter = QComboBox(self)
        self.combo_ac_list_filter.addItem('Wait')
        self.combo_ac_list_filter.addItem('Going')
        self.combo_ac_list_filter.addItem('Done')
        self.combo_ac_list_filter.addItem('Cancel')
        self.combo_ac_list_filter.addItem('Expire')
        self.combo_ac_list_filter.addItem('Will')
        self.combo_ac_list_filter.addItem('All')
        self.combo_ac_list_filter.setCurrentIndex(1)
        self.combo_ac_list_filter.setGeometry(375, 478, 50, 20)
        self.combo_ac_list_filter.currentIndexChanged.connect(
            self.change_tb_ac_list)

        self.tb_ac_first = QTableView(self)
        self.tb_ac_first.horizontalHeader().setStretchLastSection(True)
        self.tb_ac_first.horizontalHeader().setSectionResizeMode(
            QHeaderView.Custom)
        self.tb_ac_first.verticalHeader().hide()
        self.tb_ac_first.setItemDelegateForColumn(
            3, ActionStatusDelegate(self.tb_ac_first))
        self.tb_ac_first.setGeometry(410, 300, 381, 178)

        self.tb_ac_second = QTableView(self)
        self.tb_ac_second.horizontalHeader().setStretchLastSection(True)
        self.tb_ac_second.horizontalHeader().setSectionResizeMode(
            QHeaderView.Custom)
        self.tb_ac_second.verticalHeader().hide()
        self.tb_ac_second.setItemDelegateForColumn(
            3, ActionStatusDelegate(self.tb_ac_second))
        self.tb_ac_second.setGeometry(10, 300, 381, 178)

        self.tb_ac_third = QTableView(self)
        self.tb_ac_third.horizontalHeader().setStretchLastSection(True)
        self.tb_ac_third.horizontalHeader().setSectionResizeMode(
            QHeaderView.Custom)
        self.tb_ac_third.verticalHeader().hide()
        self.tb_ac_third.setItemDelegateForColumn(
            3, ActionStatusDelegate(self.tb_ac_third))
        self.tb_ac_third.setGeometry(10, 498, 381, 178)

        self.tb_ac_fourth = QTableView(self)
        self.tb_ac_fourth.horizontalHeader().setStretchLastSection(True)
        self.tb_ac_fourth.horizontalHeader().setSectionResizeMode(
            QHeaderView.Custom)
        self.tb_ac_fourth.verticalHeader().hide()
        self.tb_ac_fourth.setItemDelegateForColumn(
            3, ActionStatusDelegate(self.tb_ac_fourth))
        self.tb_ac_fourth.setGeometry(410, 498, 381, 178)

        self.tb_acs = {
            1: self.tb_ac_first,
            2: self.tb_ac_second,
            3: self.tb_ac_third,
            4: self.tb_ac_fourth
        }

        self.refresh_tb_plan()

        for index in range(1, 5):
            self.refresh_tb_action(index)

    def rb_select_date(self, de_target):
        self.calendar_select.setSelectedDate(de_target.date())

    def select_date(self):
        date = self.calendar_select.selectedDate()
        if self.rb_begin.isChecked():
            self.de_begin.setDate(date)
        elif self.rb_deadline.isChecked():
            self.de_deadline.setDate(date)

    def save_plan(self):
        code, data = self.valid_check()
        if code == -1:
            QMessageBox.critical(self, 'Error', data)
            return

        code2, actions = self.generate_actions(data)
        if code2 == -1:
            QMessageBox.critical(self, 'Error', actions)
            return
        plan_id = PlanDao.add_plan(data)
        ActionDao.add_actions(actions, plan_id)

        self.txt_content.clear()

        self.refresh_tb_plan()
        self.refresh_tb_action(tb_index=code)

    def valid_check(self):
        content = self.txt_content.toPlainText().replace('\n', '.')
        if content.strip(' ').strip('.').strip(' ') == '':
            return -1, 'Content must be a normal string!'
        begin = self.de_begin.date()
        deadline = self.de_deadline.date()
        now = QDate.currentDate()
        diff_begin = now.daysTo(begin)
        diff_deadline = now.daysTo(deadline)
        if diff_begin < 0 or diff_deadline < 0 or diff_deadline < diff_begin:
            return -1, 'Deadline date must be farther than begin date and both of them must be farther than Now'
        begin_date = datetime.date(begin.year(), begin.month(), begin.day())
        deadline = datetime.date(deadline.year(), deadline.month(),
                                 deadline.day())
        frequency = self.combo_frequency.currentText()
        repeat = self.sb_repeat.value()
        importance = self.combo_importance.currentText()
        degree_importance = False if importance.lower().startswith(
            'un') else True
        urgent = self.combo_urgency.currentText()
        degree_urgent = False if urgent.lower().startswith('non') else True
        plan = Plan(content=content,
                    begin_date=begin_date,
                    deadline=deadline,
                    frequency=PlanFrequency[frequency],
                    repeat=repeat,
                    degree_importance=degree_importance,
                    degree_urgency=degree_urgent)
        if degree_importance and degree_urgent:
            code = 1
        elif degree_importance and not degree_urgent:
            code = 2
        elif not degree_importance and not degree_urgent:
            code = 3
        elif not degree_importance and degree_urgent:
            code = 4
        return code, plan

    def generate_actions(self, plan):
        action_list = []
        begin = QDate(plan.begin_date)
        deadline = QDate(plan.deadline)

        include = self.cb_include.isChecked()
        if plan.frequency == PlanFrequency.NoRepeat:
            days = begin.daysTo(deadline)
            if not include:
                if days == 0:
                    return -1, 'There is not time to complete the plan'
            for i in range(plan.repeat):
                action = Action(content=plan.content,
                                begin_date=plan.begin_date,
                                deadline=plan.deadline,
                                degree_importance=plan.degree_importance,
                                degree_urgency=plan.degree_urgency,
                                status=1)
                action_list.append(action)
        elif plan.frequency == PlanFrequency.Day:
            days = begin.daysTo(deadline)
            if not include:
                if days == 0:
                    return -1, 'There is not time to complete the plan'
            for day in range(days + 1):
                if not include and day == 0:
                    continue
                begin_date = begin.addDays(day)
                begin_date = datetime.date(begin_date.year(),
                                           begin_date.month(),
                                           begin_date.day())
                for i in range(plan.repeat):
                    action = Action(content=plan.content,
                                    begin_date=begin_date,
                                    deadline=begin_date,
                                    degree_importance=plan.degree_importance,
                                    degree_urgency=plan.degree_urgency,
                                    status=1)
                    action_list.append(action)
        elif plan.frequency == PlanFrequency.Week:
            begin_week, begin_year = begin.weekNumber()
            begin_day_of_week = begin.dayOfWeek()
            deadline_week, deadline_year = deadline.weekNumber()
            weeks = deadline_week + (deadline_year -
                                     begin_year) * 52 - begin_week
            if not include:
                if weeks == 0:
                    return -1, 'There is not time to complete the plan'
            current_week_deadline = begin.addDays(7 - begin_day_of_week)
            for week in range(weeks + 1):
                if not include and week == 0:
                    continue
                current_week_deadline = current_week_deadline.addDays(7 * week)
                current_week_begin = current_week_deadline.addDays(-6)
                if week == 0:
                    begin_date = plan.begin_date
                    if week == weeks:
                        deadline = plan.deadline
                    else:
                        deadline = datetime.date(current_week_deadline.year(),
                                                 current_week_deadline.month(),
                                                 current_week_deadline.day())
                elif week == weeks:
                    begin_date = datetime.date(current_week_begin.year(),
                                               current_week_begin.month(),
                                               current_week_begin.day())
                    deadline = plan.deadline
                else:
                    begin_date = datetime.date(current_week_begin.year(),
                                               current_week_begin.month(),
                                               current_week_begin.day())
                    deadline = datetime.date(current_week_deadline.year(),
                                             current_week_deadline.month(),
                                             current_week_deadline.day())
                for i in range(plan.repeat):
                    action = Action(content=plan.content,
                                    begin_date=begin_date,
                                    deadline=deadline,
                                    degree_importance=plan.degree_importance,
                                    degree_urgency=plan.degree_urgency,
                                    status=1)
                    action_list.append(action)
        elif plan.frequency == PlanFrequency.Month:
            begin_year = begin.year()
            deadline_year = deadline.year()
            years = deadline_year - begin_year
            begin_month = begin.month()
            deadline_month = deadline.month()
            months = deadline_month + 12 * years - begin_month
            if not include:
                if months == 0:
                    return -1, 'There is not time to complete the plan'
            current_year = begin_year
            for month in range(months + 1):
                if not include and month == 0:
                    continue
                current_month = begin_month + month
                if current_month > 12:
                    current_month -= 12
                    current_year += 1
                if month == 0:
                    begin_date = plan.begin_date
                    if month == months:
                        deadline = plan.deadline
                    else:
                        deadline = datetime.date(current_year, current_month,
                                                 begin.daysInMonth())
                elif month == months:
                    begin_date = datetime.date(current_year, current_month, 1)
                    deadline = plan.deadline
                else:
                    begin_date = datetime.date(current_year, current_month, 1)
                    deadline = datetime.date(current_year, current_month, 1)
                    deadline = datetime.date(
                        current_year, current_month,
                        QDate(deadline.year(), deadline.month(),
                              deadline.day()).daysInMonth())
                for i in range(plan.repeat):
                    action = Action(content=plan.content,
                                    begin_date=begin_date,
                                    deadline=deadline,
                                    degree_importance=plan.degree_importance,
                                    degree_urgency=plan.degree_urgency,
                                    status=1)
                    action_list.append(action)
        elif plan.frequency == PlanFrequency.Quarter:
            begin_year = begin.year()
            deadline_year = deadline.year()
            years = deadline_year - begin_year
            begin_month = begin.month()
            deadline_month = deadline.month()
            begin_quarter = (begin_month + 2) / 3
            deadline_quarter = (deadline_month + 2) / 3
            quarters = deadline_quarter + years * 4 - begin_quarter
            if not include:
                if quarters == 0:
                    return -1, 'There is not time to complete the plan'
            current_year = begin_year
            for quarter in range(quarters + 1):
                if not include and quarter == 0:
                    continue
                current_quarter = begin_quarter + quarter
                if current_quarter > 4:
                    current_quarter -= 4
                    current_year += 1
                begin_month = (current_quarter - 1) * 3 + 1
                deadline_month = begin_month + 2
                if quarter == 0:
                    begin_date = plan.begin_date
                    if quarter == quarters:
                        deadline = plan.deadline
                    else:
                        deadline = datetime.date(
                            current_year, deadline_month,
                            (30 if deadline_month == 4 else 31))
                elif quarter == quarters:
                    begin_date = datetime.date(current_year, begin_month, 1)
                    deadline = plan.deadline
                else:
                    begin_date = datetime.date(current_year, begin_month, 1)
                    deadline = datetime.date(
                        current_year, deadline_month,
                        (30 if deadline_month == 4 else 31))
                for i in range(plan.repeat):
                    action = Action(content=plan.content,
                                    begin_date=begin_date,
                                    deadline=deadline,
                                    degree_importance=plan.degree_importance,
                                    degree_urgency=plan.degree_urgency,
                                    status=1)
                    action_list.append(action)
        elif plan.frequency == PlanFrequency.Year:
            begin_year = begin.year()
            deadline_year = deadline.year()
            years = deadline_year - begin_year
            if not include:
                if years == 0:
                    return -1, 'There is not time to complete the plan'
            for year in range(years + 1):
                if not include and year == 0:
                    continue
                current_year = begin_year + year
                if year == 0:
                    begin_date = plan.begin_date
                    if year == years:
                        deadline = plan.deadline
                    else:
                        deadline = datetime.date(current_year, 12, 31)
                elif year == years:
                    begin_date = datetime.date(current_year, 1, 1)
                    deadline = plan.deadline
                else:
                    begin_date = datetime.date(current_year, 1, 1)
                    deadline = datetime.date(current_year, 12, 31)
                for i in range(plan.repeat):
                    action = Action(content=plan.content,
                                    begin_date=begin_date,
                                    deadline=deadline,
                                    degree_importance=plan.degree_importance,
                                    degree_urgency=plan.degree_urgency,
                                    status=1)
                    action_list.append(action)
        return 0, action_list

    def change_tb_ac_list(self):
        for index in range(1, 5):
            self.refresh_tb_action(index)

    def refresh_tb_plan(self):
        plans = PlanDao.query_plans()
        model = QStandardItemModel(len(plans), 3)
        model.setHorizontalHeaderLabels(['Content', 'Frequency', 'Flag'])
        row_index = 0
        for plan in plans:
            qsi_content = QStandardItem(plan.content)
            qsi_content.setEditable(False)
            qsi_frequency = QStandardItem(plan.frequency.name)
            qsi_frequency.setEditable(False)
            qsi_flag = QStandardItem('{},{}'.format(
                'Important' if plan.degree_importance else 'Unimportant',
                'Urgency' if plan.degree_urgency else 'Non-urgency'))
            qsi_flag.setEditable(False)
            model.setItem(row_index, 0, qsi_content)
            model.setItem(row_index, 1, qsi_frequency)
            model.setItem(row_index, 2, qsi_flag)
            row_index += 1
        self.tb_plan.setModel(model)
        self.tb_plan.setColumnWidth(0, 220)
        self.tb_plan.setColumnWidth(1, 70)
        self.tb_plan.setColumnWidth(2, 100)

    def refresh_tb_action(self, tb_index):
        tb_action = self.tb_acs[tb_index]
        ac_list_filter = self.combo_ac_list_filter.currentIndex()
        actions = ActionDao.query_actions(tb_index, ac_list_filter)
        model = QStandardItemModel(len(actions), 3)
        model.setHorizontalHeaderLabels(
            ['Content', 'Begin', 'Deadline', 'Status'])
        row_index = 0
        for action in actions:
            qsi_content = QStandardItem(action.content)
            qsi_content.setEditable(False)
            qsi_begin_date = QStandardItem(
                action.begin_date.strftime("%Y/%m/%d"))
            qsi_content.setEditable(False)
            qsi_deadline = QStandardItem(action.deadline.strftime("%Y/%m/%d"))
            qsi_deadline.setEditable(False)
            qsi_status = QStandardItem()
            qsi_status.setData({'id': action.id, 'status': action.status})
            qsi_status.setEditable(False)
            model.setItem(row_index, 0, qsi_content)
            model.setItem(row_index, 1, qsi_begin_date)
            model.setItem(row_index, 2, qsi_deadline)
            model.setItem(row_index, 3, qsi_status)
            row_index += 1
        tb_action.setModel(model)
        tb_action.setColumnWidth(0, 150)
        tb_action.setColumnWidth(1, 75)
        tb_action.setColumnWidth(2, 75)
        tb_action.setColumnWidth(3, 40)

    def change_status(self, tb_action, act_id, status):
        if status == 0:
            QMessageBox.information(self, 'Tip', 'Please wait for beginning')
        elif status == 1:
            menu = QMenu(tb_action)
            done_act = menu.addAction(QIcon('icons/daily_plan/done.png'),
                                      'Done')
            cancel_act = menu.addAction(QIcon('icons/daily_plan/cancel.png'),
                                        'Cancel')
            act = menu.exec_(
                tb_action.mapToGlobal(
                    QPoint(self.sender().x(),
                           self.sender().y() + 10)))
            refresh = False
            if act == done_act:
                ActionDao.update_action(act_id, 2)
                refresh = True
            elif act == cancel_act:
                ActionDao.update_action(act_id, 3)
                refresh = True
            if refresh:
                self.refresh_tb_action(
                    list(self.tb_acs.keys())[list(
                        self.tb_acs.values()).index(tb_action)])
        elif status == 2:
            QMessageBox.information(
                self, 'Tip', 'You are good that had completed the task')
        elif status == 3:
            QMessageBox.information(self, 'Tip',
                                    'It is sadly you had canceled this task')
        elif status == 4:
            QMessageBox.information(
                self, 'Tip',
                'It is sorry that this task had expired and you cannot operate it'
            )
Ejemplo n.º 13
0
class ReptileView(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.defaultView()
        self.reloadUI()
        self.reptileType = -1
        self.errorPath = ''

    def defaultView(self):
        self.setWindowFlags(QtCore.Qt.WindowTitleHint
                            | QtCore.Qt.WindowCloseButtonHint)
        self.resize(viewWid, viewHei)
        self.setFixedSize(viewWid, viewHei)
        self.setStyleSheet('background-color:#fff')
        self.center()
        self.setWindowTitle(zfjTools.baseTitle)

    def initUI(self):
        font = QtGui.QFont()
        font.setPointSize(18)
        margin_top = margin_size
        titleLab = QLabel('爬虫工具', self)
        titleLab.setStyleSheet('color:#d4237a;')
        titleLab.setAlignment(Qt.AlignCenter)
        titleLab.setGeometry(
            QtCore.QRect(margin_size, margin_top, viewWid - margin_size * 2,
                         40))
        titleLab.setFont(font)
        backMainViewBtn = QtWidgets.QPushButton(self)
        backMainViewBtn.setGeometry(
            QtCore.QRect(margin_size, margin_top + 7.5, 50, 25))
        backMainViewBtn.setObjectName('logInBtn')
        backMainViewBtn.setText(_translate('MainWindow', '返回'))
        backMainViewBtn.setStyleSheet(
            'color:#1667ea;background-color:#fff;border:1px solid #1667ea;')
        backMainViewBtn.clicked.connect(self.backMainViewBtnClick)
        font.setPointSize(14)
        backMainViewBtn.setFont(font)
        margin_top += 40 + margin_size
        addLab = QLabel('请输入爬取地址:', self)
        addLab.setStyleSheet('color:#000000;')
        addLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        addLab.setGeometry(QtCore.QRect(margin_size, margin_top, 110, 30))
        font.setPointSize(14)
        addLab.setFont(font)
        self.addEdit = QtWidgets.QLineEdit(self)
        self.addEdit.setGeometry(
            QtCore.QRect(110 + margin_size * 2, margin_top,
                         viewWid - 110 - margin_size * 3, 30))
        font.setPointSize(14)
        self.addEdit.setFont(font)
        self.addEdit.setText('https://m.mzitu.com/23463')
        margin_top += 30 + margin_size
        line_lab = QLabel(self)
        line_lab.setStyleSheet('background-color:#dcdcdc')
        line_lab.setGeometry(QtCore.QRect(0, margin_top, viewWid, 1))
        margin_top += 1 + margin_size
        smlTitLab = QLabel('爬取方式', self)
        smlTitLab.setStyleSheet('color:#d4237a;')
        smlTitLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        smlTitLab.setGeometry(QtCore.QRect(margin_size, margin_top, 135, 30))
        smlTitLab.setFont(font)
        margin_top += 30 + margin_size
        self.sysBtn = QRadioButton('自动爬取资源文件', self)
        self.sysBtn.setStyleSheet('color:#000;')
        self.sysBtn.setGeometry(
            QtCore.QRect(margin_size * 2, margin_top, 200, 30))
        self.sysBtn.setChecked(False)
        self.sysBtn.toggled.connect(lambda: self.radioBtnClick())
        margin_top += 30 + margin_size
        self.checkBoxList = []
        titLabArr = ['图片资源', '音频资源', '视频资源']
        for index in range(0, len(titLabArr)):
            margin_x = margin_size * 4 + (90 + margin_size * 4) * index
            checkBox = QCheckBox(titLabArr[index], self)
            checkBox.setStyleSheet('color:#000;')
            checkBox.stateChanged.connect(self.checkBoxClick)
            checkBox.setGeometry(QtCore.QRect(margin_x, margin_top, 90, 30))
            self.checkBoxList.append(checkBox)

        margin_top += 30 + margin_size
        self.customBtn = QRadioButton('自定义爬取节点', self)
        self.customBtn.setStyleSheet('color:#000;')
        self.customBtn.setGeometry(
            QtCore.QRect(margin_size * 2, margin_top, 200, 30))
        self.customBtn.setChecked(False)
        self.customBtn.toggled.connect(lambda: self.radioBtnClick())
        margin_top += 30 + margin_size
        nodeTitLabWid = 48
        fatherLab = QLabel('父节点:', self)
        fatherLab.setStyleSheet('color:#000;')
        fatherLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        fatherLab.setGeometry(
            QtCore.QRect(margin_size * 4, margin_top, nodeTitLabWid, 30))
        font.setPointSize(14)
        fatherLab.setFont(font)
        editWid = (viewWid - margin_size * 11 - nodeTitLabWid * 2) / 2
        self.fatherNodeEdit = QtWidgets.QLineEdit(self)
        self.fatherNodeEdit.setGeometry(
            QtCore.QRect(margin_size * 5 + nodeTitLabWid, margin_top, editWid,
                         30))
        font.setPointSize(14)
        self.fatherNodeEdit.setFont(font)
        self.fatherNodeEdit.setText('//div[@class="pMain"]/div')
        childLab = QLabel('子节点:', self)
        childLab.setStyleSheet('color:#000;')
        childLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        childLab.setGeometry(
            QtCore.QRect(margin_size * 6 + 45 + editWid, margin_top,
                         nodeTitLabWid, 30))
        font.setPointSize(14)
        childLab.setFont(font)
        self.childNodeEdit = QtWidgets.QLineEdit(self)
        self.childNodeEdit.setGeometry(
            QtCore.QRect(margin_size * 7 + nodeTitLabWid * 2 + editWid,
                         margin_top, editWid, 30))
        font.setPointSize(14)
        self.childNodeEdit.setFont(font)
        self.childNodeEdit.setText('./a/img/@src')
        margin_top += 38
        tipsLab = QLabel(
            '例如:父节点//div[@class="pMain"]/div,子节点./a/img/@src;使用此功能需知晓XPath规则!',
            self)
        tipsLab.setStyleSheet('color:#87b753;')
        tipsLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        tipsLab.setGeometry(
            QtCore.QRect(margin_size * 4, margin_top,
                         viewWid - margin_size * 8, 20))
        font.setPointSize(12)
        tipsLab.setFont(font)
        margin_top += 20 + margin_size
        smlTitLab = QLabel('储存路径', self)
        smlTitLab.setStyleSheet('color:#d4237a;')
        smlTitLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        smlTitLab.setGeometry(QtCore.QRect(margin_size, margin_top, 135, 30))
        font.setPointSize(14)
        smlTitLab.setFont(font)
        margin_top += 30 + margin_size
        pathEditWid = viewWid - margin_size * 5 - 100
        self.pathEdit = QtWidgets.QLineEdit(self)
        self.pathEdit.setGeometry(
            QtCore.QRect(margin_size * 2, margin_top, pathEditWid, 30))
        font.setPointSize(14)
        self.pathEdit.setFont(font)
        self.pathEdit.setText('/Users/zhangfujie/Desktop/Obfuscated')
        pathBtn = QtWidgets.QPushButton(self)
        pathBtn.setGeometry(
            QtCore.QRect(margin_size * 3 + pathEditWid, margin_top, 100, 30))
        pathBtn.setText(_translate('MainWindow', '选择文件夹'))
        pathBtn.setStyleSheet(
            'color:#000000;background-color:#efeff3;border:1px solid #efeff3;')
        pathBtn.clicked.connect(self.pathBtnClick)
        pathBtn.setFont(font)
        margin_top += 30 + margin_size
        stateTitLab = QLabel('爬取结果', self)
        stateTitLab.setStyleSheet('color:#d4237a;')
        stateTitLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        stateTitLab.setGeometry(QtCore.QRect(margin_size, margin_top, 135, 30))
        font.setPointSize(14)
        stateTitLab.setFont(font)
        margin_top += 30 + margin_size
        self.resultLab = QLabel('暂无爬取数据', self)
        self.resultLab.setStyleSheet('color:#000;')
        self.resultLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.resultLab.setGeometry(
            QtCore.QRect(margin_size * 2, margin_top,
                         viewWid - margin_size * 4, 30))
        font.setPointSize(12)
        self.resultLab.setFont(font)
        margin_top += 30 + margin_size * 5
        startReptileBtn = QtWidgets.QPushButton(self)
        startReptileBtn.setGeometry(
            QtCore.QRect((viewWid - 160) / 2, margin_top, 160, 40))
        startReptileBtn.setText(_translate('MainWindow', '开始爬取'))
        startReptileBtn.setStyleSheet(
            'background-color:#fff;color:#cc0066;border:1px solid #cc0066;')
        startReptileBtn.clicked.connect(self.startReptileBtnClick)
        font.setPointSize(18)
        startReptileBtn.setFont(font)
        margin_top += 30 + margin_size * 2
        self.showLab = QLabel('--', self)
        self.showLab.setStyleSheet('color:#87b753;')
        self.showLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.showLab.setGeometry(
            QtCore.QRect(margin_size * 2, margin_top, pathEditWid, 30))
        font.setPointSize(12)
        self.showLab.setFont(font)
        errorBtn = QtWidgets.QPushButton(self)
        errorBtn.setGeometry(
            QtCore.QRect(margin_size * 3 + pathEditWid + margin_size + 5,
                         margin_top, 100, 30))
        errorBtn.setText(_translate('MainWindow', '查看错误列表'))
        errorBtn.setStyleSheet('color:#87b753;border:1px solid #fff;')
        errorBtn.clicked.connect(self.errorBtnClick)
        errorBtn.setFont(font)
        margin_top += 30 + margin_size
        line_lab_1 = QLabel(self)
        line_lab_1.setStyleSheet('background-color:#dcdcdc')
        line_lab_1.setGeometry(QtCore.QRect(0, margin_top, viewWid, 1))
        margin_top += 1 + margin_size
        downLab_wid = (viewWid - margin_size * 3) / 2
        self.accountLab = QLabel('账号:', self)
        self.accountLab.setStyleSheet('color:#000;')
        self.accountLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.accountLab.setGeometry(
            QtCore.QRect(margin_size, margin_top, downLab_wid, 30))
        font.setPointSize(13)
        self.accountLab.setFont(font)
        self.timeLab = QLabel('时间:', self)
        self.timeLab.setStyleSheet('color:#000;')
        self.timeLab.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.timeLab.setGeometry(
            QtCore.QRect(margin_size * 2 + downLab_wid, margin_top,
                         downLab_wid, 30))
        font.setPointSize(13)
        self.timeLab.setFont(font)
        margin_top += 30 + margin_size

    def backMainViewBtnClick(self):
        personinfo = ZFJPersoninfo()
        if personinfo.mainRootView != None:
            personinfo.mainRootView.show()
            self.close()
        else:
            print('mainRootView')

    def startReptileBtnClick(self):
        url = self.addEdit.text().strip()
        if len(url) == 0:
            self.megBoxInfor('')
            return
        if self.reptileType == -1:
            self.megBoxInfor('')
            return
        savePath = self.pathEdit.text()
        if len(savePath) == 0:
            self.megBoxInfor('')
            return
        if os.path.exists(savePath) == False:
            self.megBoxInfor('')
            return
        if not savePath.endswith('/'):
            savePath += '/'
        self.errorPath = savePath + 'error.txt'
        if os.path.exists(self.errorPath) == False:
            open(self.errorPath, 'w').close()
        resultLabText = ''
        if self.reptileType == 0:
            checkCount = 0
            for checkBox in self.checkBoxList:
                if checkBox.checkState() == Qt.Checked:
                    checkCount += 1
                    continue

            if checkCount == 0:
                self.megBoxInfor('')
                return
            isImage = True if self.checkBoxList[0].checkState(
            ) == Qt.Checked else False
            isAudio = True if self.checkBoxList[1].checkState(
            ) == Qt.Checked else False
            isVideo = True if self.checkBoxList[2].checkState(
            ) == Qt.Checked else False
            self.showLab.setText('......')
            tub = reptileService.getResourceUrlList(url, isImage, isAudio,
                                                    isVideo)
            if isImage == True:
                resultLabText += ' ' + str(len(tub[0])) + ''
                self.imagePath = savePath + './images'
                if os.path.exists(self.imagePath) == False:
                    os.mkdir(self.imagePath)
            if isAudio == True:
                resultLabText += ' ' + str(len(tub[1])) + ''
                self.audioPath = savePath + './audios'
                if os.path.exists(self.audioPath) == False:
                    os.mkdir(self.audioPath)
            if isVideo == True:
                resultLabText += ' ' + str(len(tub[2])) + ''
                self.videPath = savePath + './vides'
                if os.path.exists(self.videPath) == False:
                    os.mkdir(self.videPath)
            self.resultLab.setText(resultLabText)
            self.saveResourceTub(tub)
        else:
            if self.reptileType == 1:
                fatherNode = self.fatherNodeEdit.text().strip().replace(
                    ',', ',').strip(',').strip()
                if len(fatherNode) == 0:
                    self.megBoxInfor('')
                    return
                childNode = self.childNodeEdit.text().strip().replace(
                    ',', ',').strip(',').strip()
                if len(childNode) == 0:
                    self.megBoxInfor('')
                    return
                savePath = self.pathEdit.text()
                if len(savePath) == 0:
                    self.megBoxInfor('')
                    return
                if os.path.exists(savePath) == False:
                    self.megBoxInfor('')
                    return
                if not savePath.endswith('/'):
                    savePath += '/'
                self.errorPath = savePath + 'error.txt'
                if os.path.exists(self.errorPath) == False:
                    open(self.errorPath, 'w').close()
                self.showLab.setText('......')
                dataArray = reptileService.getNoteInfors(
                    url, fatherNode, childNode)
                resultLabText += ' ' + str(len(dataArray)) + ''
                self.resultLab.setText(resultLabText)
                self.saveNodeData(dataArray, savePath)

    def saveResourceTub(self, tub):
        global headers
        errorStr = ''
        isImage = True if self.checkBoxList[0].checkState(
        ) == Qt.Checked else False
        isAudio = True if self.checkBoxList[1].checkState(
        ) == Qt.Checked else False
        isVideo = True if self.checkBoxList[2].checkState(
        ) == Qt.Checked else False
        if isImage == True:
            imageUrlList = tub[0]
            for index in range(0, len(imageUrlList)):
                imageObj = imageUrlList[index]
                if '$==$' in imageObj:
                    imageName = imageObj.split('$==$')[0]
                    imgUrl = imageObj.split('$==$')[-1]
                    img = base64.urlsafe_b64decode(imgUrl + '=' *
                                                   (4 - len(imgUrl) % 4))
                    try:
                        open(self.imagePath + '/' + imageName, 'wb').write(img)
                    except Exception as e:
                        try:
                            errorStr += 'image:data:image;' + imageObj.split(
                                '$==$')[-1] + '\n'
                        finally:
                            e = None
                            del e

                else:
                    headers['Referer'] = imageObj
                    imageName = zfjTools.getTimestamp() + str(
                        random.randint(100, 999)) + str(random.randint(
                            10, 99)) + '.' + imageObj.split('.')[-1]
                    req = requests.get(imageObj, headers=headers, stream=True)
                    if req.status_code == 200:
                        try:
                            open(self.imagePath + '/' + imageName,
                                 'wb').write(req.content)
                        except Exception as e:
                            try:
                                errorStr += 'image:' + imageObj + '\n'
                            finally:
                                e = None
                                del e

                    else:
                        errorStr += 'image:' + imageObj + '\n'
                    self.showLab.setText('' + str(index + 1) + '')
                    QApplication.processEvents()

        if isAudio == True:
            audioUrlList = tub[1]
            for index in range(0, len(audioUrlList)):
                audioUrl = audioUrlList[index]
                headers['Referer'] = audioUrl
                imageName = zfjTools.getTimestamp() + str(
                    random.randint(100, 999)) + str(random.randint(
                        10, 99)) + '.' + audioUrl.split('.')[-1]
                req = requests.get(audioUrl, headers=headers, stream=True)
                if req.status_code == 200:
                    try:
                        open(self.audioPath + '/' + imageName,
                             'wb').write(req.content)
                    except Exception as e:
                        try:
                            errorStr += 'audio:' + imageObj + '\n'
                        finally:
                            e = None
                            del e

                else:
                    errorStr += 'audio:' + imageObj + '\n'
                self.showLab.setText('' + str(index + 1) + '')
                QApplication.processEvents()

        if isVideo == True:
            videoUrlList = tub[2]
            for index in range(0, len(videoUrlList)):
                videoUr = videoUrlList[index]
                headers['Referer'] = videoUr
                imageName = zfjTools.getTimestamp() + str(
                    random.randint(100, 999)) + str(random.randint(
                        10, 99)) + '.' + videoUr.split('.')[-1]
                req = requests.get(videoUr, headers=headers, stream=True)
                if req.status_code == 200:
                    try:
                        open(self.videPath + '/' + imageName,
                             'wb').write(req.content)
                    except Exception as e:
                        try:
                            errorStr += 'video:' + imageObj + '\n'
                        finally:
                            e = None
                            del e

                else:
                    errorStr += 'video:' + imageObj + '\n'
                self.showLab.setText('' + str(index + 1) + '')
                QApplication.processEvents()

        self.showLab.setText('')
        QApplication.processEvents()
        if len(errorStr) > 0:
            if len(self.errorPath) > 0:
                open(self.errorPath, 'w').write(errorStr)

    def saveNodeData(self, dataArray, savePath):
        if len(dataArray) == 0:
            self.showLab.setText('')
            return
        self.showLab.setText('')
        nodesDataPath = savePath + 'nodes:' + zfjTools.getTimestamp() + '.txt'
        if os.path.exists(nodesDataPath) == False:
            open(nodesDataPath, 'w').close()
        dataStr = ''
        for item in dataArray:
            dataStr += str(item) + '\n'

        open(nodesDataPath, 'w').write(dataStr)
        self.showLab.setText('')
        subprocess.call(['open', nodesDataPath])

    def regularVerification(self, node):
        mail = re.compile('^([a-zA-z])+\\[@class="+[A-Z0-9a-z._+-]+"+\\]$')
        if re.search(mail, node):
            return True
        else:
            return False

    def pathBtnClick(self):
        file_dir = ''
        try:
            file_dir = QFileDialog.getExistingDirectory(
                self, 'open file', '/Users/')
        except Exception as e:
            try:
                file_dir = ','
            finally:
                e = None
                del e

        self.pathEdit.setText(file_dir)

    def errorBtnClick(self):
        if len(self.errorPath) == 0:
            self.megBoxInfor('')
        else:
            subprocess.call(['open', self.errorPath])

    def radioBtnClick(self):
        if self.sysBtn.isChecked() == True:
            self.reptileType = 0
        else:
            if self.customBtn.isChecked() == True:
                self.reptileType = 1
                for checkBox in self.checkBoxList:
                    checkBox.setCheckState(Qt.Unchecked)

    def checkBoxClick(self):
        if self.sysBtn.isChecked() != True:
            for checkBox in self.checkBoxList:
                checkBox.setCheckState(Qt.Unchecked)

    def reloadUI(self):
        personinfo = ZFJPersoninfo()
        self.accountLab.setText(':' + str(personinfo.account))
        self.timeLab.setText(':' + personinfo.expireDate.replace('"', ''))

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def megBoxInfor(self, infor):
        QMessageBox.information(self, '', infor, QMessageBox.Yes)
Ejemplo n.º 14
0
class UiYoutube(PageWindow):  # Youtube UI and Youtube Download Manager
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setWindowTitle("Youtube Downloader")

    def initUI(self):
        self.setupUi(self)

    def UiTest(self):  # Used for testing UI
        self.progressBar.setVisible(True)
        self.pushButton.setVisible(False)
        self.groupBox_for_videoFormats.setVisible(False)
        self.groupBox_for_typeSelection.setVisible(False)
        self.label_for_SizeDisplay.setVisible(True)
        self.label_for_FilenameDisplay.setVisible(True)

    def type_vid(self):  # Executed, if the type video is selected
        """ Changes the UI for video downloading """
        self.groupBox_for_typeSelection.setVisible(False)
        self.groupBox_for_videoFormats.setVisible(True)
        self.resolution_comboBox.setVisible(True)
        self.pushButton.setVisible(True)
        self.progressive_checkbox.setVisible(True)
        QMessageBox.question(
            self, 'NOTE',
            "HD Videos are stored separately as Audio and Only Video "
            "formats in youtube.\nUse High"
            " resolution option to download HD video and combine it with"
            " audio with FFMPEG for best result.\n**-->>SD(480p-) videos "
            "are available in combined form.", QMessageBox.Ok)
        TYPE = "video"
        data.add('type', TYPE)
        print('Type -> video proceeding to qual,format setup')

    def type_aud(self):  # Executed, if the type Audio is selected
        """ Establishes connection and downloads audio """
        print('Type audio -> ask loc and start download')
        TYPE = "audio"
        data.add('type', TYPE)
        self.groupBox_for_typeSelection.setVisible(False)
        self.Title_label.setText('PLEASE WAIT...\nStarting Download..')
        path_to_save = QFileDialog.getExistingDirectory()
        print(path_to_save)
        data.add('loc', path_to_save)
        print(data, '@ type aud')
        try:
            yt = YouTube(data.get('url'))
            aud_stream = yt.streams.filter(type='audio').first(
            )  # Establish connection and gets audio stream
        except:
            print('OOPs!')
            QMessageBox.question(self, 'ELITE', 'Server Connection Failed!!',
                                 QMessageBox.Ok)
            exit(0)
        if aud_stream is None:  # Check if audio stream is available
            print('SGS_ERROR-404_NO_STREAM')
            QMessageBox.question(
                self, 'ELITE', 'Selected Stream not available\nPing Streams'
                ' from other menu or retry a different stream', QMessageBox.Ok)
            exit(0)
        else:
            try:
                aud_stream.download(str(
                    data.get('loc')))  # Download in given location
                print('SGS_CODE_SUCCESS')
                QMessageBox.question(self, 'ELITE', 'Download succesful !!!',
                                     QMessageBox.Ok)
            except:
                print('ERROR_IN_DOWNLOAD')
                QMessageBox.question(self, 'ELITE', 'Download Failed !!!',
                                     QMessageBox.Ok)
                exit(0)
        exit(0)

    def progress_check(self, stream=None, chunk=None, remaining=None):
        """ Computes percentage for displaying in progressbar """
        percentage = (100 * (data.get('size') - remaining)) / data.get('size')
        self.progressBar.setValue(int(percentage))

    def download_manager_vid(self):  # Downloads Youtube videos
        """ Establishes connection and selects reqd. stream and downloads it """
        try:
            yt = YouTube(data.get('url'),
                         on_progress_callback=self.progress_check)
        except:
            print('internet??')
            return 'Server Connection failed! \nCheck Internet and URL'
        resolution = data.get('qual')
        format = data.get('format')
        path = data.get('loc')
        Progressive_or_not = data.get('ext')
        if Progressive_or_not:
            if resolution == 'any' and format == 'mp4':
                self.selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not,
                    file_extension=format).order_by('resolution').last()
            elif format == 'any' and resolution == 'any':
                self.selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not).order_by(
                        'resolution').last()
            else:
                self.selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not,
                    file_extension=format).get_by_resolution(resolution)
        if not Progressive_or_not:
            if resolution == 'any' and format == 'mp4':
                self.selected_stream = yt.streams.filter(
                    type='video',
                    file_extension=format).order_by('resolution').last()
            elif format == 'any' and resolution == 'any':
                self.selected_stream = yt.streams.filter(
                    type='video').order_by('resolution').last()
            else:
                self.selected_stream = yt.streams.filter(
                    file_extension=format).get_by_resolution(resolution)
        if self.selected_stream is None:
            print('SGS_ERROR-404_NO_STREAM')
            return 'Selected Stream not available\nPing Streams' + 'from other menu or retry a different stream'
        data.add('size', self.selected_stream.filesize)
        self.selected_stream.download(path)
        print('SGS_CODE_SUCCESS')
        return 'Download Successful !!'

    def get_VideoSpecs(self):
        """Gets Video specifications and location and adjusts UI accordingly"""
        if self.mp4_radioButton.isChecked():
            print('Mp4 is selected -- proceed 147')
            data.add('format', 'mp4')
        elif self.webm_radioButton.isChecked():
            print('WEBM is selected -- proceed 149')
            data.add('format', 'webm')
        else:
            data.add('format', 'any')
        QUALITY = str(self.resolution_comboBox.currentText())
        data.add('qual', QUALITY)
        if self.progressive_checkbox.isChecked():
            data.add('ext', False)
            print('Progressive - False')
        else:
            data.add('ext', True)
            print('Progressive - True')
        print(data.get('format'), data.get('qual'), data.get('ext'),
              "End of info collection")
        self.groupBox_for_videoFormats.setVisible(False)
        self.pushButton.setVisible(False)
        self.progressive_checkbox.setVisible(False)
        self.resolution_comboBox.setVisible(False)
        self.Title_label.setText('PLEASE WAIT...\nStarting Download...')
        self.Title_label.setVisible(True)
        try:
            yt = YouTube(data.get('url'))
        except:
            QMessageBox.question(
                self, 'ELITE',
                'Server Connection Failed!!\nCheck url or Internet',
                QMessageBox.Ok)
            print('internet??')
            exit(0)
        resolution = data.get('qual')
        format = data.get('format')
        Progressive_or_not = data.get('ext')
        if Progressive_or_not:
            if resolution == 'any' and format == 'mp4':
                selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not,
                    file_extension=format).order_by('resolution').last()
            elif format == 'any' and resolution == 'any':
                selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not).order_by(
                        'resolution').last()
            else:
                selected_stream = yt.streams.filter(
                    progressive=Progressive_or_not,
                    file_extension=format).get_by_resolution(resolution)
        if not Progressive_or_not:
            if resolution == 'any' and format == 'mp4':
                selected_stream = yt.streams.filter(
                    type='video',
                    file_extension=format).order_by('resolution').last()
            elif format == 'any' and resolution == 'any':
                selected_stream = yt.streams.filter(
                    type='video').order_by('resolution').last()
            else:
                selected_stream = yt.streams.filter(
                    file_extension=format).get_by_resolution(resolution)
        if selected_stream is None:
            QMessageBox.question(
                self, 'ELITE', 'Selected Stream not available\nPing Streams'
                ' from other menu or retry a different stream', QMessageBox.Ok)
            print('SGS_ERROR-404_NO_STREAM @ 484')
            exit(0)
        filesize = (selected_stream.filesize) * (10**-6)
        filename = selected_stream.default_filename
        self.label_for_SizeDisplay.setText("FILE SIZE: " +
                                           str(round(filesize, 2)) + ' MB')
        self.label_for_SizeDisplay.setVisible(True)
        self.label_for_FilenameDisplay.setText('VIDEO NAME: ' + str(filename))
        self.label_for_FilenameDisplay.setVisible(True)
        self.progressBar.setVisible(True)
        self.pushButton_.setVisible(False)
        path_to_save = QFileDialog.getExistingDirectory(self)
        print(path_to_save)
        data.add('loc', path_to_save)
        print(data)
        message_from_func = self.download_manager_vid()
        QMessageBox.question(self, 'ELITE', message_from_func, QMessageBox.Ok)
        exit(0)

    def setupUi(self, youtube_setup):
        """Sets up the page UI"""
        youtube_setup.setObjectName("youtube_setup")
        self.centralwidget = QWidget(youtube_setup)
        self.centralwidget.setObjectName("centralwidget")
        self.resolution_comboBox = QComboBox(self.centralwidget)
        self.resolution_comboBox.setGeometry(QRect(410, 110, 100, 33))
        self.resolution_comboBox.setObjectName("resolution_comboBox")
        list_quality = ['any', '240p', '360p', '720p', '1080p']
        self.resolution_comboBox.addItems(list_quality)
        self.resolution_comboBox.setVisible(False)
        self.progressive_checkbox = QCheckBox(self.centralwidget)
        self.progressive_checkbox.setGeometry(QRect(20, 230, 350, 50))
        self.progressive_checkbox.setObjectName("check_box")
        self.progressive_checkbox.setVisible(False)
        self.Title_label = QLabel(self.centralwidget)
        self.Title_label.setGeometry(QRect(170, 10, 261, 51))
        self.label_for_SizeDisplay = QLabel(self.centralwidget)
        self.label_for_SizeDisplay.setGeometry(QRect(160, 160, 180, 41))
        self.label_for_SizeDisplay.setObjectName("label_for_SizeDisplay")
        self.label_for_SizeDisplay.setVisible(False)
        self.label_info = QLabel(self.centralwidget)
        self.label_info.setGeometry(QRect(20, 310, 260, 20))
        self.label_info.setObjectName("label_info")
        font = QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.Title_label.setFont(font)
        self.Title_label.setObjectName("Title_label")
        self.groupBox_for_typeSelection = QGroupBox(self.centralwidget)
        self.groupBox_for_typeSelection.setGeometry(QRect(200, 90, 191, 121))
        self.groupBox_for_typeSelection.setObjectName(
            "groupBox_for_typeSelection")
        self.type_audio_radioButton = QRadioButton(
            self.groupBox_for_typeSelection)
        self.type_audio_radioButton.setGeometry(QRect(40, 40, 104, 23))
        self.type_audio_radioButton.setObjectName("type_audio_radioButton")
        self.type_audio_radioButton.clicked.connect(lambda: self.type_aud())
        self.type_video_radioButton = QRadioButton(
            self.groupBox_for_typeSelection)
        self.type_video_radioButton.setGeometry(QRect(40, 70, 104, 23))
        self.type_video_radioButton.setObjectName("type_video_radioButton")
        self.type_video_radioButton.clicked.connect(lambda: self.type_vid())
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QRect(460, 290, 88, 33))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setVisible(False)
        self.pushButton.clicked.connect(lambda: self.get_VideoSpecs())
        self.pushButton_ = QPushButton(self.centralwidget)
        self.pushButton_.setGeometry(QRect(460, 290, 88, 33))
        self.pushButton_.setObjectName("pushButton")
        self.pushButton_.setVisible(False)
        self.pushButton_.clicked.connect(
            lambda: self.YoutubeManager.download_manager_vid(self))
        self.groupBox_for_videoFormats = QGroupBox(self.centralwidget)
        self.groupBox_for_videoFormats.setGeometry(QRect(200, 90, 141, 111))
        self.groupBox_for_videoFormats.setObjectName(
            "groupBox_for_videoFormats")
        self.groupBox_for_videoFormats.setVisible(False)
        self.mp4_radioButton = QRadioButton(self.groupBox_for_videoFormats)
        self.mp4_radioButton.setGeometry(QRect(20, 30, 104, 23))
        self.mp4_radioButton.setObjectName("mp4_radioButton")
        self.webm_radioButton = QRadioButton(self.groupBox_for_videoFormats)
        self.webm_radioButton.setGeometry(QRect(20, 60, 104, 23))
        self.webm_radioButton.setObjectName("webm_radioButton")
        self.progressBar = QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QRect(90, 230, 391, 23))
        self.progressBar.setProperty("value", 24)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.setVisible(False)
        self.label_for_FilenameDisplay = QLabel(self.centralwidget)
        self.label_for_FilenameDisplay.setGeometry(QRect(75, 110, 500, 50))
        self.label_for_FilenameDisplay.setObjectName(
            "label_for_FilenameDisplay")
        self.label_for_FilenameDisplay.setVisible(False)
        youtube_setup.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(youtube_setup)
        self.menubar.setGeometry(QRect(0, 0, 586, 25))
        self.menubar.setObjectName("menubar")
        youtube_setup.setMenuBar(self.menubar)
        self.progressBar.setValue(0)
        self.statusbar = QStatusBar(youtube_setup)
        self.statusbar.setObjectName("statusbar")
        youtube_setup.setStatusBar(self.statusbar)

        self.retranslateUi(youtube_setup)
        QMetaObject.connectSlotsByName(youtube_setup)

    def retranslateUi(self, youtube_setup):
        _translate = QCoreApplication.translate
        youtube_setup.setWindowTitle(
            _translate("youtube_setup", "Youtube Video Download-ELITELOADER"))
        self.Title_label.setText(
            _translate("youtube_setup", "Select Format and Quality"))
        self.label_for_SizeDisplay.setText(_translate("ELITE", "SIZE:"))
        self.label_for_FilenameDisplay.setText(_translate(
            "ELITE", "FILENAME:"))
        self.groupBox_for_typeSelection.setTitle(
            _translate("youtube_setup", "Type"))
        self.progressive_checkbox.setText(
            _translate('youtube_setup', "High Resolution/Non-Progressive"))
        self.type_audio_radioButton.setText(
            _translate("youtube_setup", "Audio"))
        self.label_info.setText(
            _translate("StartPage_Url",
                       "*This checking process may take longer"))
        self.type_video_radioButton.setText(
            _translate("youtube_setup", "Video"))
        self.pushButton.setText(_translate("youtube_setup", "Proceed"))
        self.pushButton_.setText(_translate("youtube_setup", "Download"))
        self.groupBox_for_videoFormats.setTitle(
            _translate("youtube_setup", "Format"))
        self.mp4_radioButton.setText(_translate("youtube_setup", "MP4"))
        self.webm_radioButton.setText(_translate("youtube_setup", "WEBM"))

    class YoutubeManager:  # Manage Youtube Downloads
        def __init__(self):
            pass

        def ping(
                self):  # Check Available Streams and returns a list of streams
            try:
                yt = YouTube(data.get('url'))
                pingster = yt.streams.all()
                return pingster
            except:
                print('Error in connection')
                return 'Error in connection\nCheck URL and Internet'
Ejemplo n.º 15
0
class UiFacebook(PageWindow):  # Facebook UI
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setWindowTitle("FaceBook - ELITELOADER")

    def initUI(self):
        self.setupUi(self)

    def Progressbar_Manager(self, current, total, width):
        pct = (current / total) * 100
        self.progressBar.setValue(int(pct))

    def Download_H(self):  # For High Quality
        ERASE_LINE = '\x1b[2K'
        Location = os_path.join(data.get('loc'))
        try:
            html = requests.get(data.get('url'))
            hdvideo_url = search('hd_src:"(.+?)"', html.text)[1]
        except requests.ConnectionError as e:
            print("OOPS!! Connection Error.")
            return 'Connection Error\n' + 'Check your Internet'
        except requests.Timeout as e:
            print("OOPS!! Timeout Error")
            return 'Network Timeout'
        except requests.RequestException as e:
            print("OOPS!! General Error or Invalid URL")
            return 'General Error or Invalid URL'
        except (KeyboardInterrupt, SystemExit):
            print("Ok ok, quitting")
            exit(1)
        except TypeError:
            print("Video May be Private or Hd version not available")
            return 'Video May Private or Hd version not available'
        else:
            hd_url = hdvideo_url.replace('hd_src:"', '')
            print("\n")
            print("High Quality: " + hd_url)
            print("[+] Video Started Downloading")
            wget.download(hd_url, Location, bar=self.Progressbar_Manager)
            stdout.write(ERASE_LINE)
            print("\n")
            print("Video downloaded")
            return 'Video Downloaded Successfully !!'

    def Download_L(self):  # For Low Quality
        ERASE_LINE = '\x1b[2K'
        Location = os_path.join(data.get('loc'))
        try:
            html = requests.get(data.get('url'))
            sdvideo_url = search('sd_src:"(.+?)"', html.text)[1]
        except requests.ConnectionError as e:
            print("OOPS!! Connection Error.")
            return 'Connection Error\n' + 'Check your Internet'
        except requests.Timeout as e:
            print("OOPS!! Timeout Error")
            return 'Network Timeout'
        except requests.RequestException as e:
            print("OOPS!! General Error or Invalid URL")
            return 'General Error or Invalid URL'
        except (KeyboardInterrupt, SystemExit):
            print("Ok ok, quitting")
            exit(1)
        except TypeError:
            print("Video May Private or Invalid URL")
            return 'Video May be Private or Invalid URL'
        else:
            sd_url = sdvideo_url.replace('sd_src:"', '')
            print("\n")
            print("Normal Quality: " + sd_url)
            print("[+] Video Started Downloading")
            wget.download(sd_url, Location, bar=self.Progressbar_Manager)
            stdout.write(ERASE_LINE)
            print("\n")
            print("Video downloaded")
            return 'Video Downloaded Successfully !!'

    def Selector(self):
        """ Identifies which Quality is reqd."""
        if self.HighQual_radioButton.isChecked():
            print('HQ selected--fwding to manager')
            self.groupBox_forQuality.setVisible(False)
            self.pushButton.setVisible(False)
            self.label.setText('PLEASE WAIT..\nSTARTING DOWNLOAD...')
            sgs = QFileDialog.getExistingDirectory()
            print(sgs)
            data.add('loc', sgs)
            self.progressBar.setVisible(True)
            print(data)
            msg = self.Download_H()
            QMessageBox.question(self, 'ELITE', msg, QMessageBox.Ok)
            exit(0)

        if self.LowQual_radioButton.isChecked():
            print('LQ selected--fwding to manager')
            self.groupBox_forQuality.setVisible(False)
            self.pushButton.setVisible(False)
            self.label.setText('PLEASE WAIT..\nSTARTING DOWNLOAD...')
            sgs = QFileDialog.getExistingDirectory()
            print(sgs)
            data.add('loc', sgs)
            self.progressBar.setVisible(True)
            print(data)
            msg = self.Download_L()
            QMessageBox.question(self, 'ELITE', msg, QMessageBox.Ok)
            exit(0)

    def setupUi(self, facebook_dwn):
        facebook_dwn.setObjectName("facebook_dwn")
        facebook_dwn.resize(586, 379)
        self.centralwidget = QWidget(facebook_dwn)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(220, 10, 250, 61))
        font = QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setObjectName("Title_label")
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QRect(460, 290, 88, 33))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(lambda: self.Selector())
        self.groupBox_forQuality = QGroupBox(self.centralwidget)
        self.groupBox_forQuality.setGeometry(QRect(200, 90, 141, 111))
        self.groupBox_forQuality.setObjectName("groupBox_for_videoFormats")
        self.HighQual_radioButton = QRadioButton(self.groupBox_forQuality)
        self.HighQual_radioButton.setGeometry(QRect(20, 30, 104, 23))
        self.HighQual_radioButton.setObjectName("mp4_radioButton")
        self.LowQual_radioButton = QRadioButton(self.groupBox_forQuality)
        self.LowQual_radioButton.setGeometry(QRect(20, 60, 104, 23))
        self.LowQual_radioButton.setObjectName("webm_radioButton")
        self.progressBar = QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QRect(110, 180, 391, 23))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.setVisible(False)
        facebook_dwn.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(facebook_dwn)
        self.menubar.setGeometry(QRect(0, 0, 586, 25))
        self.menubar.setObjectName("menubar")
        facebook_dwn.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(facebook_dwn)
        self.statusbar.setObjectName("statusbar")
        facebook_dwn.setStatusBar(self.statusbar)

        self.retranslateUi(facebook_dwn)
        QMetaObject.connectSlotsByName(facebook_dwn)

    def retranslateUi(self, facebook_dwn):
        _translate = QCoreApplication.translate
        facebook_dwn.setWindowTitle(
            _translate("facebook_dwn", "Facebook Video Download-ELITELOADER"))
        self.label.setText(_translate("facebook_dwn", "Select  Quality"))
        self.pushButton.setText(_translate("facebook_dwn", "Proceed"))
        self.groupBox_forQuality.setTitle(_translate("facebook_dwn",
                                                     "Quality"))
        self.HighQual_radioButton.setText(
            _translate("facebook_dwn", "High Quality"))
        self.LowQual_radioButton.setText(
            _translate("facebook_dwn", "Low Quality"))
Ejemplo n.º 16
0
def radioButton(tela, nome, x, y, largura, altura):
    radio_button = QRadioButton(nome, tela)
    radio_button.setGeometry(QRect(x, y, largura, altura))

    return radio_button
Ejemplo n.º 17
0
class UiBackgroundWidget(object):
    """
    UiBackgroundWidget
    User interface for the background remove window.
    """
    def __init__(self, background_widget):

        # set window title, object name and widget size
        background_widget.setWindowTitle("Remove Background")
        background_widget.setObjectName("background_widget")
        background_widget.resize(320, 321)

        # group box for pixel selection
        self.group_box = QGroupBox(background_widget)
        self.group_box.setTitle("Pixel Selection")
        self.group_box.setGeometry(QRect(10, 10, 300, 68))
        self.group_box.setObjectName("group_box")

        # radio button for focused pixel selection
        self.focused_pixel_radio_button = QRadioButton(self.group_box)
        self.focused_pixel_radio_button.setText("Focused Pixel")
        self.focused_pixel_radio_button.setGeometry(QRect(0, 20, 220, 22))
        self.focused_pixel_radio_button.setChecked(True)
        self.focused_pixel_radio_button.setObjectName(
            "focused_pixel_radio_button")

        # radio button for whole selection
        self.whole_map_radio_button = QRadioButton(self.group_box)
        self.whole_map_radio_button.setText("Whole Map")
        self.whole_map_radio_button.setGeometry(QRect(0, 42, 220, 22))
        self.whole_map_radio_button.setObjectName("whole_map_radio_button")

        # group box for background settings
        self.group_box_2 = QGroupBox(background_widget)
        self.group_box_2.setTitle("Background Settings")
        self.group_box_2.setGeometry(QRect(10, 78, 300, 204))
        self.group_box_2.setObjectName("group_box_2")

        # radio button for minimum counts
        self.minimum_counts_radio_button = QRadioButton(self.group_box_2)
        self.minimum_counts_radio_button.setText("Minimum Counts")
        self.minimum_counts_radio_button.setGeometry(QRect(0, 20, 220, 22))
        self.minimum_counts_radio_button.setChecked(True)
        self.minimum_counts_radio_button.setObjectName(
            "minimum_counts_radio_button")

        # radio button for interval average
        self.interval_average_radio_button = QRadioButton(self.group_box_2)
        self.interval_average_radio_button.setText("Interval Average")
        self.interval_average_radio_button.setGeometry(QRect(0, 42, 220, 22))
        self.interval_average_radio_button.setObjectName(
            "interval_average_radio_button")

        # label for interval selection
        self.label_5 = QLabel(self.group_box_2)
        self.label_5.setText("Int. Boundaries")
        self.label_5.setGeometry(QRect(40, 64, 121, 27))
        self.label_5.setObjectName("label_5")

        # slider for lower interval boundary
        self.lower_boundary_slider = QSlider(self.group_box_2)
        self.lower_boundary_slider.setEnabled(False)
        self.lower_boundary_slider.setGeometry(QRect(160, 64, 70, 29))
        self.lower_boundary_slider.setOrientation(Qt.Horizontal)
        self.lower_boundary_slider.setObjectName("lower_boundary_slider")

        # slider for the upper inverval boundary
        self.upper_boundary_slider = QSlider(self.group_box_2)
        self.upper_boundary_slider.setEnabled(False)
        self.upper_boundary_slider.setGeometry(QRect(230, 64, 70, 29))
        self.upper_boundary_slider.setOrientation(Qt.Horizontal)
        self.upper_boundary_slider.setObjectName("upper_boundary_slider")

        # background from pixel radio
        self.background_from_pixel_radio_button = QRadioButton(
            self.group_box_2)
        self.background_from_pixel_radio_button.setText(
            "Background from Map Pixel")
        self.background_from_pixel_radio_button.setGeometry(
            QRect(0, 91, 220, 22))
        self.background_from_pixel_radio_button.setObjectName(
            "background_from_pixel_radio_button")

        # label for x pixel selection
        self.label_7 = QLabel(self.group_box_2)
        self.label_7.setText("X")
        self.label_7.setGeometry(QRect(40, 113, 16, 27))
        self.label_7.setObjectName("label_7")

        # spin box for x pixel selection
        self.x_spin_box = QSpinBox(self.group_box_2)
        self.x_spin_box.setEnabled(False)
        self.x_spin_box.setGeometry(QRect(60, 113, 61, 27))
        self.x_spin_box.setObjectName("x_spin_box")

        # label for y pixel selection
        self.label_8 = QLabel(self.group_box_2)
        self.label_8.setText("Y")
        self.label_8.setGeometry(QRect(140, 113, 16, 27))
        self.label_8.setObjectName("label_8")

        # spin box for y pixel selection
        self.y_spin_box = QSpinBox(self.group_box_2)
        self.y_spin_box.setEnabled(False)
        self.y_spin_box.setGeometry(QRect(160, 113, 61, 27))
        self.y_spin_box.setObjectName("y_spin_box")

        # radio button for file background
        self.background_from_file_radio_button = QRadioButton(self.group_box_2)
        self.background_from_file_radio_button.setText("Background from File")
        self.background_from_file_radio_button.setEnabled(True)
        self.background_from_file_radio_button.setGeometry(
            QRect(0, 140, 220, 22))
        self.background_from_file_radio_button.setObjectName(
            "background_from_file_radio_button")

        # label for file selection
        self.label_9 = QLabel(self.group_box_2)
        self.label_9.setText("File")
        self.label_9.setGeometry(QRect(40, 167, 31, 27))
        self.label_9.setObjectName("label_9")

        # line edit for file path
        self.file_path_line_edit = QLineEdit(self.group_box_2)
        self.file_path_line_edit.setEnabled(False)
        self.file_path_line_edit.setGeometry(QRect(70, 167, 171, 27))
        self.file_path_line_edit.setObjectName("file_path_line_edit")

        # file browse button
        self.file_browse_push_button = QPushButton(self.group_box_2)
        self.file_browse_push_button.setText("...")
        self.file_browse_push_button.setEnabled(False)
        self.file_browse_push_button.setGeometry(QRect(250, 167, 31, 27))
        self.file_browse_push_button.setObjectName("file_browse_push_button")

        # remove background button
        self.remove_background_push_button = QPushButton(background_widget)
        self.remove_background_push_button.setText("Remove Background")
        self.remove_background_push_button.setGeometry(QRect(
            150, 283, 161, 27))
        self.remove_background_push_button.setObjectName(
            "remove_background_push_button")
Ejemplo n.º 18
0
class mainWidgets(QWidget):
    signal = pyqtSignal([int, dict])
    historyNum = 0

    def __init__(self):
        super().__init__()
        self.initUI()
        self.state = 'stopped'
        self.type = 'udp'
        self.threads = None
        self.server = None
        self.connection = None

    def initUI(self):
        self.setWindowFlags(Qt.WindowCloseButtonHint)
        self.setFixedSize(600, 360)
        self.setWindowTitle('Let\'s chat!')

        self.label1 = QLabel(self)
        self.label1.setText('remote IP:')
        self.label1.setFont(QFont("SansSerif", 12))
        self.label1.setGeometry(35, 30, 60, 16)

        self.remoteIPLine = defaultLine(self)
        self.remoteIPLine.setGeometry(105, 28, 120, 20)

        self.label2 = QLabel(self)
        self.label2.setText('remote port:')
        self.label2.setFont(QFont("SansSerif", 12))
        self.label2.setGeometry(245, 30, 80, 16)

        self.remotePortLine = defaultLine(self)
        self.remotePortLine.setGeometry(325, 28, 60, 20)

        self.udpBt = QRadioButton(self)
        self.udpBt.setText("udp")
        self.udpBt.setFont(QFont("SansSerif", 12))
        self.udpBt.setGeometry(405, 28, 60, 20)
        self.udpBt.setChecked(True)

        self.udpBindBt = defaultButton(self)
        self.udpBindBt.setText('bind')
        self.udpBindBt.setFont(QFont("SansSerif", 12))
        self.udpBindBt.setGeometry(455, 28, 50, 20)

        self.udpLabel = QLabel(self)
        self.udpLabel.setText('stopped')
        self.udpLabel.setFont(QFont("SansSerif", 12))
        self.udpLabel.setGeometry(510, 30, 60, 16)

        self.label3 = QLabel(self)
        self.label3.setText('nickname:')
        self.label3.setFont(QFont("SansSerif", 12))
        self.label3.setGeometry(35, 65, 60, 16)

        self.playerLine = defaultLine(self)
        self.playerLine.setGeometry(105, 63, 120, 20)

        self.label4 = QLabel(self)
        self.label4.setText('local port:')
        self.label4.setFont(QFont("SansSerif", 12))
        self.label4.setGeometry(249, 65, 80, 16)

        self.localPortLine = defaultLine(self)
        self.localPortLine.setGeometry(325, 63, 60, 20)

        self.tcpBt = QRadioButton(self)
        self.tcpBt.setText("tcp")
        self.tcpBt.setFont(QFont("SansSerif", 12))
        self.tcpBt.setGeometry(405, 63, 40, 20)

        self.tcpBindBt = defaultButton(self)
        self.tcpBindBt.setText('bind')
        self.tcpBindBt.setFont(QFont("SansSerif", 12))
        self.tcpBindBt.setGeometry(455, 63, 50, 20)
        self.tcpBindBt.setVisible(False)

        self.connectBt = defaultButton(self)
        self.connectBt.setText('connect')
        self.connectBt.setFont(QFont("SansSerif", 12))
        self.connectBt.setGeometry(510, 63, 50, 20)
        self.connectBt.setVisible(False)

        self.tcpLabel = QLabel(self)
        self.tcpLabel.setFont(QFont("SansSerif", 12))
        self.tcpLabel.setVisible(False)

        self.btGroup = QButtonGroup(self)
        self.btGroup.addButton(self.udpBt)
        self.btGroup.addButton(self.tcpBt)

        self.historyWidget = QWidget(self)
        self.historyWidget.setStyleSheet('background-color:#ffffff;')
        self.historyWidget.setGeometry(80, 100, 436, 0)

        self.scroll = QScrollArea(self)
        self.scroll.setStyleSheet(
            'QScrollArea{border: 0px; background-color:#ffffff; border-radius:10px; padding:2px 2px}'
        )
        self.scroll.setGeometry(80, 100, 440, 200)

        self.scroll.setWidget(self.historyWidget)

        self.messageLine = defaultLine(self)
        self.messageLine.setGeometry(120, 320, 240, 20)

        self.clearBt = defaultButton(self)
        self.clearBt.setText('clear')
        self.clearBt.setFont(QFont("SansSerif", 12))
        self.clearBt.setGeometry(390, 320, 40, 20)

        self.sendBt = defaultButton(self)
        self.sendBt.setText('send')
        self.sendBt.setFont(QFont("SansSerif", 12))
        self.sendBt.setGeometry(450, 320, 40, 20)

        self.udpBt.clicked.connect(self.slot_selectUDPMode)
        self.tcpBt.clicked.connect(self.slot_selectTCPMode)
        self.udpBindBt.clicked.connect(self.slot_Bind)
        self.tcpBindBt.clicked.connect(self.slot_Bind)
        self.clearBt.clicked.connect(self.slot_clear)
        self.sendBt.clicked.connect(self.slot_send)
        self.connectBt.clicked.connect(self.slot_connect)

        self.signal.connect(self.slot_signalHandler)

        self.show()

    def slot_selectUDPMode(self):
        self.state = 'stopped'
        self.type = 'udp'
        self.udpBindBt.setVisible(True)
        self.udpLabel.setVisible(True)
        self.tcpBindBt.setText('bind')
        self.tcpBindBt.setVisible(False)
        self.tcpLabel.setVisible(False)
        self.connectBt.setVisible(False)
        print('select udp mode')

    def slot_selectTCPMode(self):
        self.state = 'stopped'
        self.type = 'tcp'
        self.udpLabel.setText('stopped')
        self.udpBindBt.setText('bind')
        self.udpBindBt.setVisible(False)
        self.udpLabel.setVisible(False)
        self.tcpBindBt.setVisible(True)
        self.connectBt.setVisible(True)
        print('select tcp mode')

    def slot_Bind(self):
        if self.state == 'stopped':
            if self.localPortLine.text().isdigit() == False:
                QMessageBox.warning(self, 'Error',
                                    'local port is invalid!\n(1025~65535)')
                return

            localPort = int(self.localPortLine.text())
            if localPort <= 1024 or localPort > 65535:
                QMessageBox.warning(
                    self, 'Error',
                    'please use the free local port!\n(1025~65535)')
                return

            self.state = 'listening'
            self.threads = threading.Thread(target=self.listen,
                                            args=(localPort, ),
                                            daemon=True)
            self.threads.start()

        elif self.state == 'listening' or self.state == 'connecting':
            self.state = 'stopped'

    def listen(self, port):
        if self.type == 'udp':
            udp = threading.Thread(target=self.udp_setup,
                                   args=('0.0.0.0', port),
                                   daemon=True)
            udp.start()
            self.udpLabel.setText('listeing')
            self.udpBindBt.setText('release')

        elif self.type == 'tcp':
            tcp = threading.Thread(target=self.tcp_setup,
                                   args=('0.0.0.0', port),
                                   daemon=True)
            tcp.start()
            self.connectBt.setVisible(False)
            self.tcpLabel.setText('listening')
            self.tcpLabel.setGeometry(510, 65, 60, 16)
            self.tcpLabel.setVisible(True)
            self.tcpBindBt.setText('release')

        else:
            self.state = 'stopped'
            self.server = None
            self.connection = None
            return

        while True:
            if self.state == 'stopped':
                if self.server != None:
                    self.server.close()
                if self.type == 'udp':
                    self.udpLabel.setText('stopped')
                    self.udpBindBt.setText('bind')
                elif self.type == 'tcp':
                    self.udpBindBt.setVisible(False)
                    self.udpLabel.setVisible(False)
                    self.tcpBindBt.setText('bind')
                    self.connectBt.setVisible(True)
                    self.tcpLabel.setVisible(False)
                print('listen stopped')
                break

    def udp_setup(self, ip, port):
        try:
            self.server = socket(AF_INET, SOCK_DGRAM)
            self.server.bind((ip, port))
            print('udp listening (localhost, ' + str(port) + ')')
        except:
            self.state = 'stopped'
            self.signal[int, dict].emit(1, {})
            return
        else:
            try:
                while True:
                    data, addr = self.server.recvfrom(1024)
                    try:
                        dic = json.loads(data.decode('utf-8'))
                    except:
                        print('udp server get data which is not json format!')
                    else:
                        history = threading.Thread(target=self.signal_recvMsg,
                                                   args=(dic, ))
                        history.start()
            except:
                if self.server == None:
                    print('udp server is closed')
                else:
                    print('revieve data wrong')
            else:
                self.server.close()

    def tcp_setup(self, ip, port):
        if self.state == 'listening':
            try:
                self.server = socket(AF_INET, SOCK_STREAM)
                self.server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
                self.server.bind((ip, port))
                self.server.listen(1)
                print('tcp listening (localhost, ' + str(port) + ')')
            except:
                self.state = 'stopped'
                self.signal[int, dict].emit(1, {})
                return
            else:
                while True:
                    try:
                        self.connection, address = self.server.accept()
                    except:
                        print('the connection is closed')
                        break
                    else:
                        self.tcpLabel.setText('success')
                        self.remoteIPLine.setText(address[0])
                        self.remotePortLine.setText(str(address[1]))
                        t = threading.Thread(target=self.tcp_recv,
                                             args=(self.connection, ))
                        t.start()

        elif self.state == 'connecting':
            try:
                self.connection = socket(AF_INET, SOCK_STREAM)
                self.connection.connect((ip, port))
                print('tcp connected with (localhost, ' + str(port) + ')')
            except:
                self.state = 'stopped'
                self.signal[int, dict].emit(1, {})
                return
            else:
                self.localPortLine.setText(
                    str(self.connection.getsockname()[1]))
                self.signal[int, dict].emit(4, {})
                t = threading.Thread(target=self.tcp_recv,
                                     args=(self.connection, ))
                t.start()

    def tcp_recv(self, connection):
        while True:
            try:
                data = connection.recv(1024)
                try:
                    dic = json.loads(data.decode('utf-8'))
                except:
                    print('tcp server get data which is not json format!')
                    break
                else:
                    history = threading.Thread(target=self.signal_recvMsg,
                                               args=(dic, ))
                    history.start()
            except:
                print('the connection is close!')
                break

        if connection != None:
            connection.close()

    def signal_recvMsg(self, dic):
        self.signal[int, dict].emit(2, dic)

    def slot_clear(self):
        self.historyNum = 0
        self.messageLine.setText('')
        self.historyWidget.deleteLater()
        self.historyWidget = QWidget(self)
        self.historyWidget.setStyleSheet('background-color:#ffffff;')
        self.historyWidget.setGeometry(80, 100, 436, 0)
        self.scroll.setWidget(self.historyWidget)

    def slot_connect(self):
        if self.state == 'stopped':
            remoteIP = self.remoteIPLine.text()
            valid = re.match(
                r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$",
                remoteIP)

            if valid == None:
                QMessageBox.warning(self, 'Error', 'remote ip is invalid!')
                return

            if self.remotePortLine.text().isdigit() == False:
                QMessageBox.warning(self, 'Error',
                                    'remote port is invalid!\n(1025~65535)')
                return

            remotePort = int(self.remotePortLine.text())
            if remotePort <= 1024 or remotePort > 65535:
                QMessageBox.warning(
                    self, 'Error',
                    'please use the free remote port!\n(1025~65535)')
                return

            self.state = 'connecting'
            tcp = threading.Thread(target=self.tcp_setup,
                                   args=(remoteIP, remotePort),
                                   daemon=True)
            tcp.start()

        elif self.state == 'connecting' or self.state == 'listening':
            self.state = 'stopped'
            if self.connection != None:
                self.connection.close()
                if self.server != None:
                    self.server.close()
            self.tcpLabel.setVisible(False)
            self.tcpBindBt.setVisible(True)
            self.connectBt.setVisible(True)
            self.remoteIPLine.setText('')
            self.remotePortLine.setText('')

    def slot_send(self):
        player = self.playerLine.text()
        message = self.messageLine.text()
        time_ = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

        package = {'player': player, 'message': message, 'time': time_}

        if self.type == 'udp':
            remoteIP = self.remoteIPLine.text()
            valid = re.match(
                r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$",
                remoteIP)

            if valid == None:
                QMessageBox.warning(self, 'Error', 'remote ip is invalid!')
                return

            if self.remotePortLine.text().isdigit() == False:
                QMessageBox.warning(self, 'Error',
                                    'remote port is invalid!\n(1025~65535)')
                return

            remotePort = int(self.remotePortLine.text())
            if remotePort <= 1024 or remotePort > 65535:
                QMessageBox.warning(
                    self, 'Error',
                    'please use the free remote port!\n(1025~65535)')
                return

            send = threading.Thread(target=self.udp_send,
                                    args=(remoteIP, remotePort, package))
            send.start()

        elif self.type == 'tcp':
            if self.state != 'listening' and self.state != 'connecting':
                QMessageBox.warning(self, 'Error', 'No connection yet!')
                return
            send = threading.Thread(target=self.tcp_send, args=(package, ))
            send.start()

        self.messageLine.setText('')

    def udp_send(self, ip, port, dic):
        data = json.dumps(dic)
        try:
            udp = socket(AF_INET, SOCK_DGRAM)
            udp.sendto(data.encode('utf-8'), (ip, port))
        except:
            print('can\'t send the message!')
        else:
            udp.close()
            self.signal[int, dict].emit(3, dic)

    def tcp_send(self, dic):
        data = json.dumps(dic)
        try:
            self.connection.send(data.encode('utf-8'))
        except:
            print('can\'t send the message!')
            self.signal[int, dict].emit(5, {})
        else:
            self.signal[int, dict].emit(3, dic)

    def slot_signalHandler(self, type, dic):
        if type == 1:
            QMessageBox.warning(self, 'Error',
                                'setup a ' + self.type + ' server failed!')

        elif type == 2:
            player = dic['player']
            time_ = dic['time']
            message = dic['message']
            if (player == ''):
                player = 'someone'

            self.historyWidget.setGeometry(0, 0, 436,
                                           self.historyNum * 50 + 50)
            self.recvName = QLabel(self.historyWidget)
            self.recvName.setText(player + ' says:')
            self.recvName.setGeometry(10, self.historyNum * 50 + 6, 120, 16)
            self.recvName.setVisible(True)
            self.recvMsg = QLabel(self.historyWidget)
            self.recvMsg.setText(message)
            self.recvMsg.setGeometry(10, self.historyNum * 50 + 28, 200, 16)
            self.recvMsg.setVisible(True)
            self.historyNum = self.historyNum + 1

            if self.udpBt.isChecked() == True:
                self.type = 'udp'
            elif self.tcpBt.isChecked() == True:
                self.type = 'tcp'

        elif type == 3:
            player = dic['player']
            time_ = dic['time']
            message = dic['message']
            if (player == ''):
                player = 'you'

            self.historyWidget.setGeometry(0, 0, 436,
                                           self.historyNum * 50 + 50)
            self.recvName = QLabel(self.historyWidget)
            self.recvName.setText(player + ' says:')
            self.recvName.setGeometry(300, self.historyNum * 50 + 6, 120, 16)
            self.recvName.setVisible(True)
            self.recvMsg = QLabel(self.historyWidget)
            self.recvMsg.setText(message)
            self.recvMsg.setGeometry(300, self.historyNum * 50 + 28, 200, 16)
            self.recvMsg.setVisible(True)
            self.historyNum = self.historyNum + 1

            if self.udpBt.isChecked() == True:
                self.type = 'udp'
            elif self.tcpBt.isChecked() == True:
                self.type = 'tcp'

        elif type == 4:
            self.tcpBindBt.setVisible(False)
            self.tcpLabel.setText('success')
            self.tcpLabel.setGeometry(455, 65, 60, 16)
            self.tcpLabel.setVisible(True)
            self.connectBt.setText('cancle')

        elif type == 5:
            QMessageBox.warning(self, 'Error', 'the connection is close!')
            self.state = 'stopped'
            self.tcpLabel.setVisible(False)
            self.tcpBindBt.setVisible(True)
            self.connectBt.setVisible(True)
            self.remoteIPLine.setText('')
            self.remotePortLine.setText('')

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.close()

        elif event.key() == Qt.Key_Return:
            self.slot_send()
Ejemplo n.º 19
0
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(537, 428)
        font = QFont()
        font.setFamily("Old Antic Bold")  #font family
        font.setStrikeOut(False)
        Form.setFont(font)
        self.label = QLabel(Form)
        self.label.setGeometry(QRect(20, 100, 101, 31))  #x,y,widht,height
        font = QFont()
        font.setPointSize(13)
        font.setBold(False)
        font.setWeight(50)
        self.label.setFont(font)
        self.label.setTextFormat(Qt.AutoText)
        self.label.setObjectName("label")
        self.label_3 = QLabel(Form)
        self.label_3.setGeometry(QRect(20, 150, 91, 21))
        font = QFont()
        font.setPointSize(13)
        font.setBold(False)
        font.setWeight(50)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_2")
        self.label_2 = QLabel(Form)
        self.label_2.setGeometry(QRect(20, 190, 91, 20))
        font = QFont()
        font.setPointSize(13)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_3")
        self.comboBox_platform = QComboBox(Form)  #combobox --> dropdown menu
        self.comboBox_platform.setGeometry(QRect(130, 100, 181, 31))
        font = QFont()
        font.setStrikeOut(False)
        self.comboBox_platform.setFont(font)
        self.comboBox_platform.setMouseTracking(False)
        self.comboBox_platform.setAutoFillBackground(True)
        self.comboBox_platform.setObjectName("comboBox_platform")
        self.comboBox_platform.addItem("")
        self.comboBox_platform.addItem("")
        self.comboBox_platform.addItem("")
        self.comboBox_platform.addItem("")
        self.pushButton = QPushButton(Form)
        self.pushButton.setGeometry(QRect(90, 400, 151, 41))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QPushButton(Form)
        self.pushButton_2.setGeometry(QRect(410, 400, 151, 41))
        self.pushButton_2.setObjectName("pushButton_2")
        self.label_4 = QLabel(Form)
        self.label_4.setGeometry(QRect(150, 20, 250, 51))
        font = QFont()
        font.setFamily("Old Antic Bold")
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.comboBox_payload = QComboBox(Form)
        self.comboBox_payload.setGeometry(QRect(130, 190, 271, 31))
        self.comboBox_payload.setObjectName("comboBox_payload")
        self.radioButton_86 = QRadioButton(Form)
        self.radioButton_86.setGeometry(QRect(130, 150, 119, 25))
        self.radioButton_86.setObjectName(
            "radioButton_86")  #architecture radio button
        self.radioButton_64 = QRadioButton(Form)
        self.radioButton_64.setGeometry(QRect(250, 150, 119, 25))
        self.radioButton_64.setChecked(True)
        self.radioButton_64.setObjectName("radioButton_64")
        self.label_5 = QLabel(Form)
        self.label_5.setGeometry(QRect(20, 235, 91, 31))
        font = QFont()
        font.setPointSize(13)
        self.label_5.setFont(font)
        self.label_5.setObjectName("label_5")
        self.label_6 = QLabel(Form)
        self.label_6.setGeometry(QRect(290, 280, 71, 21))
        self.label_6.setObjectName("label_6")
        self.label_7 = QLabel(Form)
        self.label_7.setGeometry(QRect(290, 325, 71, 20))
        self.label_7.setObjectName("label_7")
        self.label_8 = QLabel(Form)
        self.label_8.setGeometry(QRect(60, 280, 71, 20))
        self.label_8.setObjectName("label_8")
        self.label_9 = QLabel(Form)
        self.label_9.setGeometry(QRect(60, 325, 71, 20))
        self.label_9.setObjectName("label_9")
        self.lineEdit_lhost = QLineEdit(Form)
        self.lineEdit_lhost.setGeometry(QRect(130, 280, 131, 21))
        self.lineEdit_lhost.setObjectName("lineEdit_lhost")
        self.lineEdit_lport = QLineEdit(Form)
        self.lineEdit_lport.setGeometry(QRect(130, 325, 131, 21))
        self.lineEdit_lport.setObjectName("lineEdit_lport")
        self.lineEdit_rhost = QLineEdit(Form)
        self.lineEdit_rhost.setGeometry(QRect(360, 280, 141, 21))
        self.lineEdit_rhost.setObjectName("lineEdit_rhost")
        self.lineEdit_rport = QLineEdit(Form)
        self.lineEdit_rport.setGeometry(QRect(360, 325, 141, 21))
        self.lineEdit_rport.setObjectName("lineEdit_rport")
        self.pushButton_3 = QPushButton(Form)
        self.pushButton_3.setGeometry(QRect(250, 400, 151, 41))
        self.pushButton_3.setObjectName("pushButton_3")

        #Fixed image on screen
        #self.label_10 = QLabel(Form)
        #self.label_10.setGeometry(QtCore.QRect(400, 25, 250, 250))
        #self.label_10.setText("")
        #self.label_10.setPixmap(QtGui.QPixmap("logo2.png"))
        #self.label_10.setScaledContents(True)

        #Animated GIF on screen
        self.label_10 = QtWidgets.QLabel(Form)
        self.label_10.setGeometry(QtCore.QRect(400, 25, 250, 250))
        self.label_10.setObjectName("label_10")
        #self.retranslateUi(Form)

        self.retranslateUi(Form)
        self.comboBox_platform.currentIndexChanged['int'].connect(
            Form.setPlatform)
        self.pushButton_2.clicked.connect(Form.ExitTool)
        self.radioButton_86.clicked.connect(Form.setArch)
        self.radioButton_64.clicked.connect(Form.setArch)
        self.pushButton.clicked.connect(Form.GeneratePayload)
        self.pushButton_3.clicked.connect(Form.pythonServer)
        #QMetaObject.connectSlotsByName(Form)               #commented out for animated gif
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        #translating labels to text
        _translate = QtCore.QCoreApplication.translate
        #_translate = QCoreApplication.translate            #commented out for animated gif
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "OS"))
        self.label_2.setText(_translate("Form", "Payload"))
        self.label_3.setText(_translate("Form", "Arch"))
        self.comboBox_platform.setItemText(0, _translate("Form", "Windows"))
        self.comboBox_platform.setItemText(1, _translate("Form", "Linux"))
        self.comboBox_platform.setItemText(
            2, _translate("Form", "Web_Reverse_Shell"))
        self.comboBox_platform.setItemText(
            3, _translate("Form", "Script_Reverse_Shell"))
        self.pushButton.setText(_translate("Form", "Generate"))
        self.pushButton_2.setText(_translate("Form", "Exit"))
        self.label_4.setText(_translate("Form", "TaiPan v1.0"))
        self.radioButton_86.setText(_translate("Form", "x86"))
        self.radioButton_64.setText(_translate("Form", "x64"))
        self.label_5.setText(_translate("Form", "Parameters"))
        self.label_6.setText(_translate("Form", "RHOST"))
        self.label_7.setText(_translate("Form", "RPORT"))
        self.label_8.setText(_translate("Form", "LHOST"))
        self.label_9.setText(_translate("Form", "LPORT"))
        self.pushButton_3.setText(_translate("Form", "Serve Payload"))
Ejemplo n.º 20
0
class replaceDialog(QDialog):
    def __init__(self, mainWindow, editor):
        super().__init__(mainWindow)
        self.resize(409, 367)
        self.editor = editor
        self.setWindowTitle("Replace")
        self.initUI()
        self.show()

    def initUI(self):
        lblFind = QLabel(self)
        lblFind.setGeometry(QRect(10, 10, 47, 21))
        defaultFont = QFont()
        defaultFont.setPointSize(10)
        lblFind.setFont(defaultFont)
        lblFind.setText("Find")

        lblReplace = QLabel(self)
        lblReplace.setGeometry(QRect(10, 53, 61, 20))
        lblReplace.setFont(defaultFont)
        lblReplace.setText("Replace")

        self.txtFind = QLineEdit(self)
        self.txtFind.setGeometry(QRect(80, 10, 261, 20))
        self.txtFind.setFont(defaultFont)

        self.txtReplace = QLineEdit(self)
        self.txtReplace.setGeometry(QRect(80, 50, 261, 21))
        self.txtReplace.setFont(defaultFont)

        self.chkRE = QCheckBox(self)
        self.chkRE.setGeometry(QRect(10, 110, 261, 17))
        self.chkRE.setFont(defaultFont)
        self.chkRE.setText("Regular Expression")

        self.chkCS = QCheckBox(self)
        self.chkCS.setGeometry(QRect(10, 140, 261, 17))
        self.chkCS.setFont(defaultFont)
        self.chkCS.setText("Case sensitive")

        self.chkWord = QCheckBox(self)
        self.chkWord.setGeometry(QRect(10, 170, 261, 17))
        self.chkWord.setFont(defaultFont)
        self.chkWord.setText("Whole word")

        self.chkWrap = QCheckBox(self)
        self.chkWrap.setGeometry(QRect(10, 200, 261, 17))
        self.chkWrap.setFont(defaultFont)
        self.chkWrap.setText("Wrap around")

        defaultDialogButtons = QDialogButtonBox(self)
        defaultDialogButtons.setGeometry(QRect(250, 340, 156, 23))
        defaultDialogButtons.setFont(defaultFont)
        defaultDialogButtons.setStandardButtons(QDialogButtonBox.Cancel
                                                | QDialogButtonBox.Ok)

        btnReplace = QPushButton(self)
        btnReplace.setGeometry(QRect(150, 340, 91, 23))
        btnReplace.setFont(defaultFont)
        btnReplace.setText("Replace...")

        directionBox = QGroupBox(self)
        directionBox.setGeometry(QRect(20, 240, 120, 80))
        directionBox.setFont(defaultFont)
        directionBox.setTitle("Direction")

        self.rbFwd = QRadioButton(directionBox)
        self.rbFwd.setGeometry(QRect(10, 20, 82, 17))
        self.rbFwd.setFont(defaultFont)
        self.rbFwd.setText("Forward")
        self.rbFwd.setChecked(True)

        self.rbBwd = QRadioButton(directionBox)
        self.rbBwd.setGeometry(QRect(10, 50, 82, 17))
        self.rbBwd.setFont(defaultFont)
        self.rbBwd.setText("Backward")

        btnReplace.clicked.connect(self.ReplaceText)
        defaultDialogButtons.accepted.connect(self.accept)
        defaultDialogButtons.rejected.connect(self.reject)

    def ReplaceText(self):
        if self.rbFwd.isChecked():
            forward = True
        if self.rbBwd.isChecked():
            forward = False
        if self.txtFind.text() == "":
            self.txtFind.setFocus()
        elif self.txtReplace.text() == "":
            self.txtFind.setFocus()
        else:
            returnVal = self.editor.findFirst(self.txtFind.text(),
                                              self.chkRE.isChecked(),
                                              self.chkCS.isChecked(),
                                              self.chkWord.isChecked(),
                                              self.chkWrap.isChecked(), 0, 0)
            self.editor.replace(self.txtReplace.text())
Ejemplo n.º 21
0
class DatabaseWindow(QWidget):
    ALL_LABEL = "Все"
    canvas = None
    plotWidget = None
    importDbButton = None
    exportDbButton = None
    specInput = None
    axisLabel = None
    b1, b2, b3, selected_btn = None, None, None, None
    distIndex = 0
    kindsShown = 5

    def __init__(self, databaseConnector, parent=None):
        super().__init__()
        self.parent = parent
        self.databaseConnector = databaseConnector
        self.nKinds = len(self.databaseConnector.getSpecies())
        self.title = 'Statistics/management'
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(10, 10, 800, 600)
        self.plotWidget = MplWidget(self, width=5, height=4, dpi=100)
        self.plotWidget.setGeometry(0, 0, 800, 550)

        species = self.databaseConnector.getSpecies()
        species.append(self.ALL_LABEL)
        species.reverse()  # ALL_LABEL comes first
        self.specInput = QHintCombo(items=species, parent=self)
        self.specInput.setGeometry(10, 550, 180, 25)
        self.specInput.currentIndexChanged.connect(
            lambda: self.draw_statistics(self.selected_btn))

        self.axisLabel = QLabel("Axis 'X':", parent=self)
        self.axisLabel.setGeometry(200, 550, 50, 25)

        self.lftBtn = QPushButton(text='<', parent=self)
        self.lftBtn.setGeometry(20, 510, 25, 25)
        self.rghtBtn = QPushButton(text='>', parent=self)
        self.rghtBtn.setGeometry(760, 510, 25, 25)
        self.lftBtn.setVisible(False)
        self.rghtBtn.setVisible(False)
        self.lftBtn.clicked.connect(self.goLeft)
        self.rghtBtn.clicked.connect(self.goRight)

        self.b1 = QRadioButton("Latitude", parent=self)
        self.b1.setGeometry(260, 550, 100, 25)
        self.b2 = QRadioButton("Longitude", parent=self)
        self.b2.setGeometry(260, 575, 100, 25)
        self.b3 = QRadioButton("Kinds", parent=self)
        self.b3.setGeometry(370, 550, 100, 25)
        self.b1.toggled.connect(lambda: self.btnstate(self.b1))
        self.b1.setChecked(True)
        self.selected_btn = self.b1

        self.b2.toggled.connect(lambda: self.btnstate(self.b2))
        self.b3.toggled.connect(lambda: self.btnstate(self.b3))

        self.importDbButton = QtWidgets.QPushButton(text="Import DB",
                                                    parent=self)
        self.importDbButton.setGeometry(580, 550, 100, 25)
        self.importDbButton.clicked.connect(self.importDatabase)

        self.exportDbButton = QtWidgets.QPushButton(text="Export DB",
                                                    parent=self)
        self.exportDbButton.setGeometry(690, 550, 100, 25)
        self.exportDbButton.clicked.connect(self.exportDatabase)

    def btnstate(self, b):
        if b.isChecked():
            self.selected_btn = b
            self.draw_statistics(b)
            print("nkinds={};showing {}".format(self.nKinds, self.kindsShown))
            cond = b == self.b3 and self.kindsShown < self.nKinds
            self.lftBtn.setVisible(cond)
            self.rghtBtn.setVisible(cond)

    def draw_statistics(self, b):
        self.nKinds = len(self.databaseConnector.getSpecies())
        bird_kind = self.specInput.currentText()
        geo_coord = b.text()
        bounds_shift = 0
        range_shift = 0
        x_axis = []
        y_axis = []

        specCountStats = self.b3 == self.selected_btn
        if specCountStats:
            kinds = self.databaseConnector.getSpecies()
            self.distIndex = max(self.distIndex, 0)
            while self.distIndex >= len(kinds):
                self.distIndex -= self.kindsShown
            lBound = self.distIndex
            # self.distIndex = min(self.distIndex, len(kinds))
            rBound = min(self.distIndex + self.kindsShown, len(kinds))
            x_axis = kinds[lBound:rBound]
            freq = [self.databaseConnector.countBirdsByKind(k) for k in x_axis]
            y_axis = freq

        if bird_kind == self.ALL_LABEL:
            a = self.databaseConnector.get_all_birds_area()
        else:
            a = self.databaseConnector.get_birds_area(bird_kind)

        if geo_coord == 'Longitude':
            bounds_shift = 90
            range_shift = 5

        self.plotWidget.canvas.axes.clear()
        if not specCountStats:
            x_axis = ([a[i][geo_coord.lower()] for i in range(len(a))])
            y_axis = [
                self.count_range_in_list(x_axis, i - 5, i + 5)
                for i in np.arange(0, 90 + bounds_shift, 10)
            ]
            self.plotWidget.canvas.axes.bar(np.arange(0, 90 + bounds_shift,
                                                      10),
                                            y_axis,
                                            width=10)
            self.plotWidget.canvas.axes.set_xlabel(geo_coord)
            self.plotWidget.canvas.axes.set_ylabel(bird_kind)
            self.plotWidget.canvas.axes.set_xlim(0)
            self.plotWidget.canvas.axes.set_xticks(
                np.arange(0, 90 + bounds_shift, 5 + range_shift))
            self.plotWidget.canvas.axes.set_yticks(
                np.arange(0,
                          max(y_axis) + 1,
                          max(y_axis) // 10 + 1))

        else:
            self.plotWidget.canvas.axes.bar(x_axis, y_axis)
            self.plotWidget.canvas.axes.set_yticks(
                np.arange(0,
                          max(y_axis) + 1,
                          max(y_axis) // 10 + 1))

        # self.plotWidget.canvas.axes.bar(['a', 'b'], ['c', 'd'], width=10)

        self.plotWidget.canvas.draw()
        self.plotWidget.canvas.flush_events()
        return

    def count_range_in_list(self, lst, min, max):
        ctr = 0
        for x in lst:
            if min <= x <= max:
                ctr += 1
        return ctr

    def importDatabase(self):
        fname, err = QFileDialog.getOpenFileName(self,
                                                 'Save file',
                                                 filter="CSV (*.csv)")
        try:
            self.databaseConnector.importData(fname)
            msg = QMessageBox()
            msg.setText("Database loaded!")
            msg.setWindowTitle("Success!")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
        except:
            msg = QMessageBox()
            msg.setText("Database not loaded! Very bad!")
            msg.setWindowTitle("Failure!")
            msg.setStandardButtons(QMessageBox.Discard)
            msg.exec_()
        self.parent.refresh()
        if self.parent.secondWindow:
            self.parent.secondWindow.specInput.setItems(
                self.databaseConnector.getSpecies())
        self.refresh()
        self.draw_statistics(self.selected_btn)

    def exportDatabase(self):
        fname, err = QFileDialog.getSaveFileName(self,
                                                 'Save file',
                                                 filter="CSV (*.csv)")
        try:
            self.databaseConnector.exportData(fname)
            msg = QMessageBox()
            msg.setText("Database saved!")
            msg.setWindowTitle("Success!")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
        except:
            msg = QMessageBox()
            msg.setText("Database not saved! Very bad!")
            msg.setWindowTitle("Failure!")
            msg.setStandardButtons(QMessageBox.Discard)
            msg.exec_()

    def goLeft(self):
        print('going west')
        self.distIndex -= self.kindsShown
        self.draw_statistics(self.selected_btn)

    def goRight(self):
        print('going east')
        self.distIndex += self.kindsShown
        self.draw_statistics(self.selected_btn)

    def refresh(self):
        species = self.databaseConnector.getSpecies()
        species.append(self.ALL_LABEL)
        species.reverse()  # ALL_LABEL comes first
        self.specInput.setItems(species)
Ejemplo n.º 22
0
class Ui_MainWindow(object):
    nameFileWave = ''
    overlap = 0.4
    nperseg = 512
    window = 'hamming'
    pause = False
    regionPause = False
    deletePlotFragment = True

    def setupUi(self, MainWindow):

        MainWindow.setGeometry(450, 50, 1000, 785)
        MainWindow.setWindowTitle("CFS")

        self.mainMenu = QMenuBar(MainWindow)
        self.mainMenu.setGeometry(QRect(0, 0, 1000, 21))
        self.fileMenu = QMenu('&Dzwiek', self.mainMenu)
        MainWindow.setMenuBar(self.mainMenu)
        self.actionOpenFile = QAction('&Wczytaj', MainWindow)
        self.actionOpenFile.setShortcut('Ctrl+W')
        self.actionOpenFile.setStatusTip('Wczytaj dzwięk')
        self.actionOpenFile.triggered.connect(self.fileName)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.actionOpenFile)
        self.mainMenu.addAction(self.fileMenu.menuAction())

        self.centralwidget = QWidget(MainWindow)
        self.groupBoxOdtwarzacz = QGroupBox(self.centralwidget)
        self.groupBoxOdtwarzacz.setTitle("Odtwarzacz:")
        self.groupBoxOdtwarzacz.setGeometry(QRect(10, 20, 171, 111))
        self.pushButtonPlay = QPushButton(self.groupBoxOdtwarzacz)
        self.pushButtonPlay.setGeometry(QRect(20, 80, 31, 23))
        self.pushButtonPlay.setText("Play")
        self.pushButtonPlay.clicked.connect(self.filePlay)
        self.pushButtonStop = QPushButton(self.groupBoxOdtwarzacz)
        self.pushButtonStop.setGeometry(QRect(110, 80, 31, 23))
        self.pushButtonStop.setText("Stop")
        self.pushButtonStop.clicked.connect(self.fileStop)
        self.pushButtonPause = QPushButton(self.groupBoxOdtwarzacz)
        self.pushButtonPause.setGeometry(QRect(60, 80, 41, 23))
        self.pushButtonPause.setText("Pause")
        self.pushButtonPause.clicked.connect(self.filePause)
        self.radioButtonCalosc = QRadioButton(self.groupBoxOdtwarzacz)
        self.radioButtonCalosc.setGeometry(QRect(10, 20, 91, 20))
        self.radioButtonCalosc.setText("całe nagranie")
        self.radioButtonCalosc.setChecked(True)
        self.radioButtonFragment = QRadioButton(self.groupBoxOdtwarzacz)
        self.radioButtonFragment.setGeometry(QRect(10, 40, 161, 17))
        self.radioButtonFragment.setText("wybrany przedział nagrania")

        self.groupBoxDlugoscZakladki = QGroupBox(self.centralwidget)
        self.groupBoxDlugoscZakladki.setEnabled(True)
        self.groupBoxDlugoscZakladki.setGeometry(QRect(210, 20, 131, 111))
        self.groupBoxDlugoscZakladki.setTitle("Długość zakładki:")
        self.comboBoxDlugoscZakladki = QComboBox(self.groupBoxDlugoscZakladki)
        self.comboBoxDlugoscZakladki.setGeometry(QRect(10, 30, 70, 25))
        self.comboBoxDlugoscZakladki.addItem("10%")
        self.comboBoxDlugoscZakladki.addItem("20%")
        self.comboBoxDlugoscZakladki.addItem("30%")
        self.comboBoxDlugoscZakladki.addItem("40%")
        self.comboBoxDlugoscZakladki.addItem("50%")
        self.comboBoxDlugoscZakladki.addItem("60%")
        self.comboBoxDlugoscZakladki.addItem("70%")
        self.comboBoxDlugoscZakladki.addItem("80%")
        self.comboBoxDlugoscZakladki.addItem("90%")
        self.comboBoxDlugoscZakladki.setCurrentIndex(3)
        self.comboBoxDlugoscZakladki.currentIndexChanged.connect(
            self.updateSpectrum)

        self.groupBoxOkno = QGroupBox(self.centralwidget)
        self.groupBoxOkno.setEnabled(True)
        self.groupBoxOkno.setGeometry(QRect(530, 20, 131, 111))
        self.groupBoxOkno.setTitle("Okna:")
        self.comboBoxOkno = QComboBox(self.groupBoxOkno)
        self.comboBoxOkno.setEnabled(True)
        self.comboBoxOkno.setGeometry(QRect(10, 30, 81, 25))
        self.comboBoxOkno.addItem("HAMMING")
        self.comboBoxOkno.addItem("BLACKMAN")
        self.comboBoxOkno.addItem("HANN")
        self.comboBoxOkno.addItem("BARTLETT")
        self.comboBoxOkno.addItem("TRIANG")
        self.comboBoxOkno.currentIndexChanged.connect(self.updateSpectrum)

        self.groupBoxDlugoscProbki = QGroupBox(self.centralwidget)
        self.groupBoxDlugoscProbki.setGeometry(QRect(370, 20, 131, 111))
        self.groupBoxDlugoscProbki.setTitle("Dlugość próbki:")
        self.comboBoxDlugoscProbki = QComboBox(self.groupBoxDlugoscProbki)
        self.comboBoxDlugoscProbki.setGeometry(QRect(10, 30, 70, 25))
        self.comboBoxDlugoscProbki.addItem("16")
        self.comboBoxDlugoscProbki.addItem("32")
        self.comboBoxDlugoscProbki.addItem("64")
        self.comboBoxDlugoscProbki.addItem("128")
        self.comboBoxDlugoscProbki.addItem("256")
        self.comboBoxDlugoscProbki.addItem("512")
        self.comboBoxDlugoscProbki.addItem("1024")
        self.comboBoxDlugoscProbki.addItem("2048")
        self.comboBoxDlugoscProbki.addItem("4096")
        self.comboBoxDlugoscProbki.setCurrentIndex(5)
        self.comboBoxDlugoscProbki.currentIndexChanged.connect(
            self.updateSpectrum)
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')

        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setContentsMargins(12, 130, 10, 10)
        self.plotCalosc = pg.PlotWidget()
        self.plotCalosc.setTitle("FALA SYGNAŁU")
        self.plotCalosc.setLabel('bottom', "Czas", units='s')
        self.plotCalosc.setLabel('left', "Amplituda", units='')
        self.verticalLayout.addWidget(self.plotCalosc)

        self.plotFragment = pg.PlotWidget()
        self.plotFragment.setTitle("POWIEKSZONY FRAGMENT FALI SYGNAŁU")
        self.plotFragment.setLabel('bottom', "Czas", units='s')
        self.plotFragment.setLabel('left', "Amplituda", units='')
        self.verticalLayout.addWidget(self.plotFragment)

        self.plotSonogram = pg.PlotWidget()
        self.plotSonogram.setTitle("SPEKTOGRAM")
        self.plotSonogram.setLabel('bottom', "Czas", units='s')
        self.plotSonogram.setLabel('left', "Czestotliwosc", units='')
        self.verticalLayout.addWidget(self.plotSonogram)

        MainWindow.setCentralWidget(self.centralwidget)

        app.aboutToQuit.connect(self.closeEvent)

    def fileName(self):
        wave = QFileDialog.getOpenFileName(
            caption='Wczytaj dzwiek',
            filter="Music(*.wav)",
            options=QFileDialog.DontUseNativeDialog)

        if wave == ('', ''):
            QMessageBox.information(None, 'Informacja',
                                    "Nie wczytales dzwieku.", QMessageBox.Ok)
        else:
            self.nameFileWave = ""
            self.nameFileWave = wave[0]
            self.fileReadSound()

    def filePlay(self):

        print("Play")
        try:
            if self.nameFileWave == "":
                QMessageBox.information(None, 'Informacja',
                                        'Nie został wczytany żaden dźwięk.',
                                        QMessageBox.Ok)
            else:
                if self.radioButtonCalosc.isChecked():

                    if self.pause == False:
                        pygame.mixer.music.load(self.nameFileWave)
                        pygame.mixer.music.play()

                    else:
                        pygame.mixer.music.unpause()
                        self.pause = False

                else:
                    if self.regionPause == False:

                        try:
                            pygame.mixer.music.load(self.nameFileWave)
                            wavfile.write('fragment.wav', self.tempRegionRate,
                                          self.tempRegionData)

                        except:
                            pass

                        pygame.mixer.music.load('fragment.wav')
                        pygame.mixer.music.play()

                    else:
                        pygame.mixer.music.unpause()
                        self.regionPause = False

        except:
            QMessageBox.information(
                None, 'Informacja',
                'Program nie moze otworzyc dzwieku, ale przeanalizował sygnal.',
                QMessageBox.Ok)

    def filePause(self):

        print("Pause")
        try:
            if self.nameFileWave == "":
                QMessageBox.information(None, 'Informacja',
                                        'Nie został wczytany żaden dźwięk.',
                                        QMessageBox.Ok)
            else:
                pygame.mixer.music.pause()

                if pygame.mixer.music.get_busy() == 0:
                    self.pause = False
                    self.regionPause = False
                else:
                    self.pause = True
                    self.regionPause = True
        except:
            pass

    def fileStop(self):
        print("Stop")
        try:
            if self.nameFileWave == "":
                QMessageBox.information(None, 'Informacja',
                                        'Nie został wczytany żaden dźwięk.',
                                        QMessageBox.Ok)
            else:
                pygame.mixer.music.stop()
                self.pause = False
                self.regionPause = False
        except:
            pass

    def fileReadSound(self):

        try:
            self.pause = False
            self.regionPause = False

            rate, data = wavfile.read(self.nameFileWave)

            if len(data.shape) == 2:
                data = data[:, 1]

            try:
                pygame.mixer.music.load(self.nameFileWave)
                wavfile.write('fragment.wav', rate, data)
            except:
                QMessageBox.information(
                    None, 'Informacja',
                    'Pliki wav nie moga miec polskich znakow.', QMessageBox.Ok)

            self.tempRegionRate = rate
            self.tempRegionData = data
            times = np.arange(len(data)) / float(rate)
            self.x = times
            self.y = data
            self.tempx = times
            self.tempy = data
            self.makePlot()

        except ValueError:
            self.nameFileWave = ''
            QMessageBox.information(
                None, 'Błąd',
                'Nie można wczytać tego pliku,\n Proszę wybrać inny.',
                QMessageBox.Ok)

    def makePlot(self):

        if self.deletePlotFragment:
            self.plotFragment.close()

        self.plotCalosc.plot(x=self.x, y=self.y, clear=True)
        tempMinX = min(self.x)
        tempMaxX = max(self.x)
        tempMinY = min(self.y)
        tempMaxY = max(self.y)

        tempDistanceX = 0.02
        if tempMaxX <= 10.0:
            pass
        else:
            if tempMaxX <= 100.0:
                tempDistanceX = 0.2
            else:
                tempDistanceX = 2.0

        if tempMinY > 0:
            tempDistanceMinY = tempMinY - tempMinY / 2
        else:
            if tempMinY < 0:
                tempDistanceMinY = tempMinY + tempMinY / 2
            else:
                tempDistanceMinY = -10

        if tempMaxY < 0:
            tempDistanceMaxY = tempMaxX - tempMaxX / 2
        else:
            if tempMaxY > 0:
                tempDistanceMaxY = tempMaxY + tempMaxY / 2
            else:
                tempDistanceMaxY = +10

        self.plotCalosc.setRange(
            xRange=[tempMinX - tempDistanceX, tempMaxX + tempDistanceX],
            yRange=[tempDistanceMinY, tempDistanceMaxY])
        self.plotCalosc.setLimits(xMin=tempMinX - tempDistanceX,
                                  xMax=tempMaxX + tempDistanceX,
                                  yMin=tempDistanceMinY,
                                  yMax=tempDistanceMaxY)

        if (max(self.x) < 90.0):
            self.region = pg.LinearRegionItem([0, self.x[-1]],
                                              bounds=[0, self.x[-1]])
            self.region.setZValue(100)
            self.plotCalosc.addItem(self.region)

            self.region.sigRegionChanged.connect(self.updateRegion)

            self.plotFragment = pg.PlotWidget(x=self.tempx, y=self.tempy)
            self.plotFragment.setRange(
                xRange=[tempMinX - tempDistanceX, tempMaxX + tempDistanceX],
                yRange=[tempDistanceMinY, tempDistanceMaxY])
            self.plotFragment.setLimits(xMin=tempMinX - tempDistanceX,
                                        xMax=tempMaxX + tempDistanceX,
                                        yMin=tempDistanceMinY,
                                        yMax=tempDistanceMaxY)
            self.plotFragment.setTitle("POWIEKSZONY FRAGMENT FALI SYGNAŁU")
            self.plotFragment.setLabel('bottom', "Czas", units='s')
            self.plotFragment.setLabel('left', "Amplituda", units='')
            self.verticalLayout.addWidget(self.plotFragment)
            self.deletePlotFragment = True
        else:
            self.deletePlotFragment = False

        self.makeSpectrum()

    def updateRegion(self):

        temp = (self.x > self.region.getRegion()[0] - 0.000000001) & (
            self.x < self.region.getRegion()[1] + 0.000000001)

        self.tempx = self.x[temp]
        self.tempy = self.y[temp]
        self.tempRegionData = self.tempy
        self.updatePlot()

    def updatePlot(self):

        self.regionPause = False
        tempMinX = min(self.tempx)
        tempMaxX = max(self.tempx)
        tempMinY = min(self.tempy)
        tempMaxY = max(self.tempy)

        if tempMinY > 0:
            tempDistanceMinY = tempMinY - tempMinY / 2
        else:
            if tempMinY < 0:
                tempDistanceMinY = tempMinY + tempMinY / 2
            else:
                tempDistanceMinY = -10

        if tempMaxY < 0:
            tempDistanceMaxY = tempMaxX - tempMaxX / 2
        else:
            if tempMaxY > 0:
                tempDistanceMaxY = tempMaxY + tempMaxY / 2
            else:
                tempDistanceMaxY = +10

        self.plotFragment.setRange(xRange=[tempMinX, tempMaxX],
                                   yRange=[tempDistanceMinY, tempDistanceMaxY])
        self.plotFragment.setLimits(xMin=tempMinX,
                                    xMax=tempMaxX,
                                    yMin=tempDistanceMinY,
                                    yMax=tempDistanceMaxY)
        self.plotFragment.plot(x=self.tempx, y=self.tempy, clear=True)
        self.updateSpectrum()

    def makeSpectrum(self):

        if self.nameFileWave == "":
            overlap = self.dlugoscZakladki(
                self.comboBoxDlugoscZakladki.currentText())
            window = self.comboBoxOkno.currentText().lower()
            nperseg = int(self.comboBoxDlugoscProbki.currentText())
        else:

            overlap = self.dlugoscZakladki(
                self.comboBoxDlugoscZakladki.currentText())
            window = self.comboBoxOkno.currentText().lower()
            nperseg = int(self.comboBoxDlugoscProbki.currentText())

            tempwindow = get_window(window, nperseg)
            tempoverlap = nperseg * overlap
            tempoverlap = int(round(tempoverlap))

            try:
                f, t, S = self.stft(self.tempy, self.tempRegionRate,
                                    tempwindow, nperseg, tempoverlap, window)
                S = 20 * np.log10(S)
                self.plotSonogram.close()
                self.plotSonogram = pg.PlotWidget()
                self.plotSonogram.setTitle("SPEKTOGRAM")
                self.plotSonogram.setLabel('bottom', "Czas", units='s')
                self.plotSonogram.setLabel('left', "Czestotliwosc", units='Hz')

                pg.setConfigOptions(imageAxisOrder='row-major')
                self.img = pg.ImageItem()
                self.plotSonogram.addItem(self.img)
                hist = pg.HistogramLUTItem()
                hist.setImageItem(self.img)
                hist.setLevels(np.min(S), np.max(S))
                hist.gradient.restoreState({
                    'mode':
                    'rgb',
                    'ticks': [(0.0, (0, 255, 255, 255)),
                              (0.25, (0, 0, 255, 255)), (0.5, (0, 0, 0, 255)),
                              (0.75, (255, 0, 0, 255)),
                              (1.0, (255, 255, 0, 255))]
                })
                self.img.setImage(S)
                self.img.scale(t[-1] / np.size(S, axis=1),
                               f[-1] / np.size(S, axis=0))
                self.plotSonogram.setLimits(xMin=0,
                                            xMax=t[-1],
                                            yMin=0,
                                            yMax=f[-1])
                self.verticalLayout.addWidget(self.plotSonogram)

            except:
                pass

    def updateSpectrum(self):

        overlap = self.dlugoscZakladki(
            self.comboBoxDlugoscZakladki.currentText())
        window = self.comboBoxOkno.currentText().lower()
        nperseg = int(self.comboBoxDlugoscProbki.currentText())

        tempwindow = get_window(window, nperseg)
        tempoverlap = nperseg * overlap
        tempoverlap = int(round(tempoverlap))

        try:
            f, t, S = self.stft(self.tempy, self.tempRegionRate, tempwindow,
                                nperseg, tempoverlap, window)

            S = 20 * np.log10(S)

            pg.setConfigOptions(imageAxisOrder='row-major')
            self.img = pg.ImageItem()
            self.plotSonogram.plot(clear=True)
            self.plotSonogram.addItem(self.img)
            hist = pg.HistogramLUTItem()
            hist.setImageItem(self.img)
            hist.setLevels(np.min(S), np.max(S))
            hist.gradient.restoreState({
                'mode':
                'rgb',
                'ticks': [(0.0, (0, 255, 255, 255)), (1.0, (255, 255, 0, 255)),
                          (0.5, (0, 0, 0, 255)), (0.25, (0, 0, 255, 255)),
                          (0.75, (255, 0, 0, 255))]
            })
            self.img.setImage(S)
            self.img.scale(t[-1] / np.size(S, axis=1),
                           f[-1] / np.size(S, axis=0))
            self.plotSonogram.setLimits(xMin=0, xMax=t[-1], yMin=0, yMax=f[-1])

        except:
            pass

    def stft(self, x, fs, window, nperseg, noverlap, nameWindow):

        x = np.asarray(x)
        outdtype = np.result_type(x, np.complex64)

        if x.size == 0:
            return np.empty(x.shape), np.empty(x.shape), np.empty(x.shape)

        if nperseg > x.shape[-1]:
            nperseg = x.shape[-1]
            win = get_window(nameWindow, nperseg)
        else:
            win = window

        if np.result_type(win, np.complex64) != outdtype:
            win = win.astype(outdtype)

        scale = 1.0 / win.sum()**2
        scale = np.sqrt(scale)

        if np.iscomplexobj(x):
            freqs = fftpack.fftfreq(nperseg, 1 / fs)
        else:
            freqs = np.fft.rfftfreq(nperseg, 1 / fs)

        result = self.fft(x, win, nperseg, noverlap)
        result *= scale
        time = np.arange(nperseg / 2, x.shape[-1] - nperseg / 2 + 1,
                         nperseg - noverlap) / float(fs)
        result = result.astype(outdtype)
        result = np.rollaxis(result, -1, -2)
        result = np.abs(result)
        tempResult = result[result != 0]
        result[result == 0] = np.min(tempResult)

        return freqs, time, result

    def fft(self, x, win, nperseg, noverlap):

        if nperseg == 1 and noverlap == 0:
            result = x[..., np.newaxis]
        else:
            step = nperseg - noverlap
            shape = x.shape[:-1] + ((x.shape[-1] - noverlap) // step, nperseg)
            strides = x.strides[:-1] + (step * x.strides[-1], x.strides[-1])
            result = np.lib.stride_tricks.as_strided(x,
                                                     shape=shape,
                                                     strides=strides)

        result = signaltools.detrend(result, type='constant', axis=-1)
        result = win * result

        if np.iscomplexobj(x):
            func = fftpack.fft
        else:
            result = result.real
            func = np.fft.rfft

        result = func(result, n=nperseg)

        return result

    def dlugoscZakladki(self, temp):

        if (temp == '10%'):
            overlap = 0.1
        else:
            if (temp == '20%'):
                overlap = 0.2
            else:
                if (temp == '30%'):
                    overlap = 0.3
                else:
                    if (temp == '40%'):
                        overlap = 0.4
                    else:
                        if (temp == '50%'):
                            overlap = 0.5
                        else:
                            if (temp == '60%'):
                                overlap = 0.6
                            else:
                                if (temp == '70%'):
                                    overlap = 0.7
                                else:
                                    if (temp == '80%'):
                                        overlap = 0.8
                                    else:
                                        overlap = 0.9

        return overlap

    def closeEvent(self):
        if os.path.isfile('fragment.wav'):
            pygame.mixer.quit()
            os.remove('fragment.wav')
Ejemplo n.º 23
0
class Ui_Form(object):
    def __init__(self, obj):
        super().__init__()
        self.setupUi(obj)
        self.retranslateUi(obj)
        self.graphicsView = QGraphicsView(obj)
        self.graphicsView.setGeometry(QtCore.QRect(10, 10, 791, 441))
        self.graphicsView.setObjectName("graphicsView")
        self.scene = QtWidgets.QGraphicsScene()
        self.graphicsView.setScene(self.scene)

        pen = QtGui.QPen(QtCore.Qt.GlobalColor.gray)
        for i in range(-1 * self.graphicsView.height() // 2 + 10,
                       self.graphicsView.height() // 2 - 10):
            r1 = QtCore.QRectF(QtCore.QPointF(0, i), QtCore.QSizeF(1, 1))
            self.scene.addRect(r1, pen)

        for i in range(-1 * self.graphicsView.width() // 2 + 10,
                       self.graphicsView.width() // 2 - 10):
            r2 = QtCore.QRectF(QtCore.QPointF(i, 0), QtCore.QSizeF(1, 1))
            self.scene.addRect(r2, pen)

        self.coordsContainer = []
        self.centersContainer = []
        self.clastersContainer = []
        self.distance = None

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(815, 678)

        self.startPushButton = QPushButton(Form)
        self.startPushButton.clicked.connect(
            self.startPushButton_button_clicked)
        self.startPushButton.setGeometry(QtCore.QRect(260, 620, 261, 41))
        self.startPushButton.setObjectName("startPushButton")

        self.coordsTextBox = QtWidgets.QPlainTextEdit(Form)
        self.coordsTextBox.setGeometry(QtCore.QRect(260, 470, 261, 81))
        self.coordsTextBox.setObjectName("coordsTextBox")

        self.CentersTextBox = QtWidgets.QPlainTextEdit(Form)
        self.CentersTextBox.setGeometry(QtCore.QRect(540, 470, 261, 81))
        self.CentersTextBox.setObjectName("CentersTextBox")

        self.addCordsPushButton = QPushButton(Form)
        self.addCordsPushButton.clicked.connect(
            self.addCordsPushButton_button_clicked)
        self.addCordsPushButton.setGeometry(QtCore.QRect(260, 570, 541, 31))
        self.addCordsPushButton.setObjectName("addCordsPushButton")

        self.groupBox = QtWidgets.QGroupBox(Form)
        self.groupBox.setGeometry(QtCore.QRect(10, 460, 241, 91))
        self.groupBox.setObjectName("groupBox")

        self.euclidRadioButton = QRadioButton(self.groupBox)
        self.euclidRadioButton.toggled.connect(self.euclidRadioButton_clicked)
        self.euclidRadioButton.setGeometry(QtCore.QRect(10, 20, 221, 31))
        self.euclidRadioButton.setObjectName("euclidRadioButton")

        self.chebishevRadioButton = QRadioButton(self.groupBox)
        self.chebishevRadioButton.toggled.connect(
            self.chebishevRadioButton_clicked)
        self.chebishevRadioButton.setGeometry(QtCore.QRect(10, 50, 221, 41))
        self.chebishevRadioButton.setObjectName("chebishevRadioButton")

        self.stepPushButton = QPushButton(Form)
        self.stepPushButton.clicked.connect(self.stepPushButton_button_clicked)
        self.stepPushButton.setGeometry(QtCore.QRect(540, 620, 261, 41))
        self.stepPushButton.setObjectName("stepPushButton")

        self.restartPushButton = QPushButton(Form)
        self.restartPushButton.clicked.connect(
            self.restartPushButton_button_clicked)
        self.restartPushButton.setGeometry(QtCore.QRect(10, 620, 241, 41))
        self.restartPushButton.setObjectName("restartPushButton")

        self.testPushButton = QPushButton(Form)
        self.testPushButton.clicked.connect(self.testPushButton_button_clicked)
        self.testPushButton.setGeometry(QtCore.QRect(10, 570, 241, 31))
        self.testPushButton.setObjectName("testPushButton")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.startPushButton.setText(_translate("Form", "START"))
        self.addCordsPushButton.setText(_translate("Form", "ADD COORDINATES"))
        self.groupBox.setTitle(_translate("Form", "Distance"))
        self.euclidRadioButton.setText(_translate("Form", "Euclid"))
        self.chebishevRadioButton.setText(_translate("Form", "Chebishev"))
        self.stepPushButton.setText(_translate("Form", "STEP"))
        self.restartPushButton.setText(_translate("Form", "RESTART"))
        self.testPushButton.setText(_translate("Form", "Set Test Dataset"))

    def drawLineToDot(self):
        pen = QtGui.QPen(QtCore.Qt.GlobalColor.blue)
        brush = QtGui.QBrush(QtCore.Qt.GlobalColor.blue)
        pen.setWidth(2)
        pen.setColor(QtCore.Qt.GlobalColor.blue)

        for i in range(len(self.clastersContainer)):
            for j in self.clastersContainer[i]:
                self.scene.addLine(
                    QtCore.QLineF(4 * j[0], -4 * j[1],
                                  4 * self.centersContainer[i][0],
                                  -4 * self.centersContainer[i][1]), pen)

    def stringParser(self, coords, centers):
        coords_l = None
        centers_l = None
        try:
            coords_string_array = coords.split(';')
            centers_string_array = centers.split(';')
            coords_l = []
            centers_l = []

            for i in coords_string_array:
                l = [float(k) for k in i.strip('()').split(',')]
                coords_l.append(l)

            for i in centers_string_array:
                l = [float(k) for k in i.strip('()').split(',')]
                centers_l.append(l)
        except:
            self.CentersTextBox.clear()
            self.coordsTextBox.clear()
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Format Error")
            msg.setInformativeText('Follow the format!')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            pass
        return coords_l, centers_l

    def add_coordinates_to_GraphView(self):
        pen = QtGui.QPen(QtCore.Qt.GlobalColor.black)
        brush = QtGui.QBrush(QtCore.Qt.GlobalColor.black)
        side = 4
        for i in self.coordsContainer:
            self.scene.addEllipse(i[0] * side - 3, -1 * i[1] * side - 3, 7, 7,
                                  pen, brush)

        pen = QtGui.QPen(QtCore.Qt.GlobalColor.red)
        brush = QtGui.QBrush(QtCore.Qt.GlobalColor.red)

        for i in self.centersContainer:
            self.scene.addEllipse(i[0] * side - 3, -1 * i[1] * side - 3, 7, 7,
                                  pen, brush)

    def addCordsPushButton_button_clicked(self):
        coordinates = self.coordsTextBox.toPlainText()
        centers = self.CentersTextBox.toPlainText()
        if coordinates == '' or centers == '':
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Data Empty")
            msg.setInformativeText('Please, enter coords')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            return

        coordinates_l, centers_l = self.stringParser(coordinates, centers)

        if coordinates_l is not None and centers_l is not None:
            co = self.coordsContainer.copy()
            ce = self.centersContainer.copy()

            co += coordinates_l.copy()
            ce += centers_l.copy()

            co.sort()
            ce.sort()

            co_new = list(num for num, _ in itertools.groupby(co))
            ce_new = list(num for num, _ in itertools.groupby(ce))

            self.centersContainer = ce_new.copy()
            self.coordsContainer = co_new.copy()

            print(self.centersContainer)
            print(self.coordsContainer)

            self.add_coordinates_to_GraphView()

    def startPushButton_button_clicked(self):
        if self.coordsContainer == [] or self.centersContainer == []:
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Data Empty")
            msg.setInformativeText('Please, enter coords')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            return
        self.chebishevRadioButton.setEnabled(False)
        self.euclidRadioButton.setEnabled(False)
        self.addCordsPushButton.setEnabled(False)
        self.coordsTextBox.setEnabled(False)
        self.CentersTextBox.setEnabled(False)
        self.startPushButton.setEnabled(False)
        self.testPushButton.setEnabled(False)

        if self.distance == 'E':

            for _ in range(len(self.centersContainer)):
                self.clastersContainer.append([])

            for i in self.coordsContainer:
                range_l = []
                for c in self.centersContainer:
                    range_l.append(
                        math.sqrt((i[0] - c[0])**2 + (i[1] - c[1])**2))

                minindex = range_l.index(min(range_l))
                self.clastersContainer[minindex].append(i)
            self.drawLineToDot()
        elif self.distance == 'H':
            for _ in range(len(self.centersContainer)):
                self.clastersContainer.append([])

            for i in self.coordsContainer:
                range_l = []
                for c in self.centersContainer:
                    range_l.append(max(abs(i[0] - c[0]), abs(i[1] - c[1])))

                minindex = range_l.index(min(range_l))
                self.clastersContainer[minindex].append(i)
            self.drawLineToDot()

    def stepPushButton_button_clicked(self):
        if self.centersContainer is None or self.coordsContainer is None:
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Empty Error")
            msg.setInformativeText('Not enough dots!')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            return

        claster_backup = self.clastersContainer.copy()
        new_centers = []
        for i in self.clastersContainer:
            new_x, new_y = 0, 0
            for k in i:
                new_x += k[0]
                new_y += k[1]
            new_x /= len(i)
            new_y /= len(i)
            new_centers.append([new_x, new_y])

        self.centersContainer = new_centers.copy()
        self.redrow(False)
        self.add_coordinates_to_GraphView()
        self.clastersContainer.clear()
        for _ in range(len(self.centersContainer)):
            self.clastersContainer.append([])

        for i in self.coordsContainer:
            range_l = []
            for c in new_centers:
                range_l.append(math.sqrt((i[0] - c[0])**2 + (i[1] - c[1])**2))

            minindex = range_l.index(min(range_l))
            self.clastersContainer[minindex].append(i)
        self.drawLineToDot()
        new_back_clasters = self.clastersContainer.copy()

        if claster_backup == new_back_clasters:
            self.stepPushButton.setEnabled(False)

    def redrow(self, full):
        self.scene.clear()
        pen = QtGui.QPen(QtCore.Qt.GlobalColor.gray)
        for i in range(-1 * self.graphicsView.height() // 2 + 10,
                       self.graphicsView.height() // 2 - 10):
            r1 = QtCore.QRectF(QtCore.QPointF(0, i), QtCore.QSizeF(1, 1))
            self.scene.addRect(r1, pen)

        for i in range(-1 * self.graphicsView.width() // 2 + 10,
                       self.graphicsView.width() // 2 - 10):
            r2 = QtCore.QRectF(QtCore.QPointF(i, 0), QtCore.QSizeF(1, 1))
            self.scene.addRect(r2, pen)
        if not full:

            pen2 = QtGui.QPen(QtCore.Qt.GlobalColor.black)
            brush2 = QtGui.QBrush(QtCore.Qt.GlobalColor.black)

            side = 4
            for i in self.coordsContainer:
                self.scene.addEllipse(i[0] * side - 3, -1 * i[1] * side - 3, 7,
                                      7, pen2, brush2)

    def restartPushButton_button_clicked(self):
        self.chebishevRadioButton.setEnabled(True)
        self.euclidRadioButton.setEnabled(True)
        self.addCordsPushButton.setEnabled(True)
        self.coordsTextBox.setEnabled(True)
        self.CentersTextBox.setEnabled(True)
        self.testPushButton.setEnabled(True)
        self.startPushButton.setEnabled(True)
        self.stepPushButton.setEnabled(True)
        self.redrow(True)

        self.coordsContainer.clear()
        self.centersContainer.clear()
        self.clastersContainer.clear()

    def testPushButton_button_clicked(self):
        self.coordsTextBox.setPlainText(TEST_COORDS)
        if self.distance == 'E':
            self.CentersTextBox.setPlainText(EUCLID_TEST_CENTERS)
        elif self.distance == 'H':
            self.CentersTextBox.setPlainText(CHEBISHEV_TEST_CENTERS)
        else:
            self.coordsTextBox.clear()
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Distance not set")
            msg.setInformativeText('Please, pick the distance')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            pass

    def euclidRadioButton_clicked(self):
        if self.euclidRadioButton.isChecked():
            self.distance = 'E'

    def chebishevRadioButton_clicked(self):
        if self.chebishevRadioButton.isChecked():
            self.distance = 'H'
Ejemplo n.º 24
0
    def __init__(self):
        super().__init__()
        # variables iniciales de componentes
        self.started = False
        self.wave = 'sinusoidal'
        self.fs= 44100
        self.LFO = np.ones(44100)
        self.t = np.linspace(0,1,self.fs)
        self.noise = (np.random.rand(self.fs) * 2) - 1
        self.copy_noise = self.noise
        self.ftype = 'low'
        self.forder = 4
        self.delay = True

        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.black)
        self.setPalette(p)

        self.a_knob = 11025
        self.d_knob = 11025
        self.s_knob = 5000
        self.r_knob = 11025

        # inicializacion de objetos de la GUI
        self.myLabel1 = QLabel(self)
        self.myLabel1.setText('Attack: 0ms')
        self.myLabel1.setStyleSheet("color: white;")
        self.myLabel1.move(40, 10)

        self.mySlider1 = QSlider(Qt.Horizontal, self)
        self.mySlider1.setGeometry(30, 40, 200, 30)
        self.mySlider1.setMinimum(1)
        self.mySlider1.name = 'Attack'
        self.mySlider1.setMaximum(22050)
        self.mySlider1.setValue(self.a_knob)
        self.mySlider1.valueChanged[int].connect(self.change_knob)

        self.myLabel2 = QLabel(self)
        self.myLabel2.setText('Decay: 0ms')
        self.myLabel2.setStyleSheet("color: white;")
        self.myLabel2.move(40, 70)

        self.mySlider2 = QSlider(Qt.Horizontal, self)
        self.mySlider2.setGeometry(30, 100, 200, 30)
        self.mySlider2.setMinimum(1)
        self.mySlider2.name = 'Decay'
        self.mySlider2.setMaximum(11025)
        self.mySlider2.setValue(self.d_knob)
        self.mySlider2.valueChanged[int].connect(self.change_knob)

        self.myLabel3 = QLabel(self)
        self.myLabel3.setText('Sustain: 0ms')
        self.myLabel3.setStyleSheet("color: white;")
        self.myLabel3.move(40, 130)

        self.mySlider3 = QSlider(Qt.Horizontal, self)
        self.mySlider3.setGeometry(30, 160, 200, 30)
        self.mySlider3.setMinimum(1)
        self.mySlider3.name = 'Sustain'
        self.mySlider3.setMaximum(11025)
        self.mySlider3.setValue(self.s_knob)
        self.mySlider3.valueChanged[int].connect(self.change_knob)

        self.myLabelR = QLabel(self)
        self.myLabelR.setText('Release: 0ms')
        self.myLabelR.move(40, 190)

        self.mySliderR = QSlider(Qt.Horizontal, self)
        self.mySliderR.setGeometry(30, 220, 200, 30)
        self.mySliderR.setMinimum(1)
        self.mySliderR.name = 'Release'
        self.mySliderR.setMaximum(11025)
        self.mySliderR.setValue(self.r_knob)
        self.mySliderR.valueChanged[int].connect(self.change_knob)

        self.myLabel4 = QLabel(self)
        self.myLabel4.setText('LFO: 1Hz')
        self.myLabel4.setStyleSheet("color: white;")
        self.myLabel4.move(40, 310)

        self.mySlider4 = QSlider(Qt.Horizontal, self)
        self.mySlider4.setGeometry(30, 340, 200, 30)
        self.mySlider4.setMinimum(1)
        self.mySlider4.setMaximum(100)
        self.mySlider4.setValue(1)
        self.mySlider4.name = 'slider_lfo'
        self.mySlider4.valueChanged[int].connect(self.active_lfo)

        self.myLabel5 = QLabel(self)
        self.myLabel5.setText('LFO offset')
        self.myLabel5.setStyleSheet("color: white;")
        self.myLabel5.move(40, 370)

        self.mySlider5 = QSlider(Qt.Horizontal, self)
        self.mySlider5.setGeometry(30, 400, 200, 30)
        self.mySlider5.setMinimum(1)
        self.mySlider5.setMaximum(100)
        self.mySlider5.setValue(100)
        self.mySlider5.name = 'slider_lfo'
        self.mySlider5.valueChanged[int].connect(self.active_lfo)

        self.myLabel6 = QLabel(self)
        self.myLabel6.setText('Cutoff Frequency')
        self.myLabel6.setStyleSheet("color: white;")
        self.myLabel6.move(300, 230)

        self.mySlider6 = QSlider(Qt.Horizontal, self)
        self.mySlider6.setGeometry(300, 260, 200, 30)
        self.mySlider6.setMinimum(100)
        self.mySlider6.setMaximum(8000)
        self.mySlider6.setValue(100)
        self.mySlider6.name = 'slider_filter'
        self.mySlider6.valueChanged[int].connect(self.set_filter)

        self.myLabelQ = QLabel(self)
        self.myLabelQ.setText('Band Width')
        self.myLabelQ.move(300, 290)

        self.mySliderQ = QSlider(Qt.Horizontal, self)
        self.mySliderQ.setGeometry(300, 320, 200, 30)
        self.mySliderQ.setMinimum(10)
        self.mySliderQ.setMaximum(1000)
        self.mySliderQ.setValue(10)
        self.mySliderQ.name = 'slider_filter'
        self.mySliderQ.valueChanged[int].connect(self.set_filter)

        self.myLabel7 = QLabel(self)
        self.myLabel7.setText('Filter Order')
        self.myLabel7.setStyleSheet("color: white;")
        self.myLabel7.move(300, 350)

        self.mySlider7 = QSlider(Qt.Horizontal, self)
        self.mySlider7.setGeometry(300, 380, 200, 30)
        self.mySlider7.setMinimum(1)
        self.mySlider7.setMaximum(16)
        self.mySlider7.setValue(4)
        self.mySlider7.name = 'order_filter'
        self.mySlider7.valueChanged[int].connect(self.set_order)

        self.myLabel8 = QLabel(self)
        self.myLabel8.setText('Delay')
        self.myLabel8.setStyleSheet("color: white;")
        self.myLabel8.move(40, 490)

        self.mySlider8 = QSlider(Qt.Horizontal, self)
        self.mySlider8.setGeometry(40, 520, 200, 30)
        self.mySlider8.setMinimum(1)
        self.mySlider8.setMaximum(22050)
        self.mySlider8.setValue(11025)
        self.mySlider8.name = 'delay'
        self.mySlider8.valueChanged[int].connect(self.set_delay)

        radiobutton2 = QRadioButton("Highpass", self)
        radiobutton2.name = "highpass"
        radiobutton2.toggled.connect(self.onClickedF)
        radiobutton2.setStyleSheet("color: white;")
        radiobutton2.setGeometry(300, 420, 200, 32)

        radiobutton2 = QRadioButton("Lowpass", self)
        radiobutton2.name = "lowpass"
        radiobutton2.toggled.connect(self.onClickedF)
        radiobutton2.setStyleSheet("color: white;")
        radiobutton2.setGeometry(300, 460, 200, 32)

        radiobutton2 = QRadioButton("Bandpass", self)
        radiobutton2.name = "bandpass"
        radiobutton2.toggled.connect(self.onClickedF)
        radiobutton2.setStyleSheet("color: white;")
        radiobutton2.setGeometry(300, 500, 200, 32)
        
        radiobutton2 = QRadioButton("Bandstop", self)
        radiobutton2.name = "bandstop"
        radiobutton2.toggled.connect(self.onClickedF)
        radiobutton2.setStyleSheet("color: white;")
        radiobutton2.setGeometry(300, 540, 200, 32)

        self.graphWidget1 = pg.PlotWidget(self)
        self.graphWidget1.setGeometry(300,20,300,150)

        self.graphWidget2 = pg.PlotWidget(self)
        self.graphWidget2.setGeometry(650,20,300,150)

        self.graphWidget3 = pg.PlotWidget(self)
        self.graphWidget3.setGeometry(650,190,300,150)

        radiobutton = QRadioButton("Sine", self)
        radiobutton.setChecked(True)
        radiobutton.wave = "sinusoidal"
        radiobutton.toggled.connect(self.onClicked)
        radiobutton.setStyleSheet("color: white;")
        radiobutton.setGeometry(1000, 40, 200, 30)

        radiobutton = QRadioButton("Triangle", self)
        radiobutton.wave = "triangle"
        radiobutton.toggled.connect(self.onClicked)
        radiobutton.setStyleSheet("color: white;")
        radiobutton.setGeometry(1000, 100, 200, 31)

        radiobutton = QRadioButton("Sawtooth", self)
        radiobutton.wave = "sawtooth"
        radiobutton.toggled.connect(self.onClicked)
        radiobutton.setStyleSheet("color: white;")
        radiobutton.setGeometry(1000, 160, 200, 32)

        radiobutton = QRadioButton("Square", self)
        radiobutton.wave = "square"
        radiobutton.toggled.connect(self.onClicked)
        radiobutton.setStyleSheet("color: white;")
        radiobutton.setGeometry(1000, 220, 200, 32)

        radiobutton = QRadioButton("Noise", self)
        radiobutton.wave = "noise"
        radiobutton.toggled.connect(self.onClicked)
        radiobutton.setStyleSheet("color: white;")
        radiobutton.setGeometry(1000, 280, 200, 32)

        self.lfo = QCheckBox('LFO', self)
        self.lfo.name = 'lfo_box'
        self.lfo.toggled.connect(self.active_lfo)
        self.lfo.setStyleSheet("color: white;")
        self.lfo.setGeometry(40, 250, 100, 32)

        self.lowpass_check = QCheckBox('Filter', self)
        self.lowpass_check.name = 'lowpass'
        self.lowpass_check.setStyleSheet("color: white;")
        self.lowpass_check.setGeometry(300, 190, 100, 32)

        self.delay_box = QCheckBox('Delay', self)
        self.delay_box.name = 'delay_box'
        self.delay_box.toggled.connect(self.set_delay)
        self.delay_box.setStyleSheet("color: white;")
        self.delay_box.setGeometry(40, 430, 100, 32)

        self.calculate_ASDR(self.a_knob, self.d_knob, self.s_knob, self.r_knob)

        play_button = QPushButton('Play', self)
        play_button.name = 'play'
        play_button.clicked.connect(self.play_mode)
        play_button.setStyleSheet("color: white; border: 1px solid white; border-radius: 5px; background: black;")
        play_button.setGeometry(700, 380, 200, 32)

        play_button = QPushButton('Stop', self)
        play_button.name = 'stop'
        play_button.clicked.connect(self.play_mode)
        play_button.setStyleSheet("color: white; border: 1px solid white; border-radius: 5px; background: black;")
        play_button.setGeometry(700, 440, 200, 32)

        order = 12 #orden del filtro
        nyq = 0.5 * self.fs #máxima frecuencia
        normal_cutoff = 100 / nyq #calculo real de frecuencia de corte
        b, a = butter(order, normal_cutoff, btype='low', analog=False) #generacion de numerador y denominador del modelo matematico del filtro
        w, h = signal.freqs(b, a)
        self.graphWidget3.setLogMode(True, False)
        self.graphWidget3.setXRange(1,5)
        self.graphWidget3.setYRange(-100,100)
        self.data_filter = self.graphWidget3.plot(w, 20 * np.log10(abs(h)))

        # inicializar ventana de GUI
        self.setGeometry(50,50,1100,600)
        self.setWindowTitle("Synthesizer")
        self.show()
Ejemplo n.º 25
0
class MyInfoGui(QWidget):
    closeSignal = pyqtSignal()  # 界面关闭的时候发出的信号
    setMyInfoSignal = pyqtSignal(dict)  # 修改个人信息请求信号

    def __init__(self, my_info=UserInfo(0), parent=None):
        super().__init__(parent)

        self.myInfo = my_info  # 自己的用户信息

        # 界面基本设置
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        self.setAttribute(Qt.WA_QuitOnClose, False)

        # 设置标题
        self.setWindowTitle(self.tr("个人信息"))
        self.setFixedSize(743, 579)

        self.initUI()  # UI设置

        # 移动到屏幕中央
        self.resize(self.sizeHint())
        rect = self.frameGeometry()
        rect.moveCenter(QApplication.desktop().availableGeometry().center())
        self.move(rect.topLeft())

    def initUI(self):
        font = QFont("微软雅黑", 16, 20)

        # 控件
        self.lab=QLabel('背景图片',self)
        self.lab.setGeometry(0,0,1024,768)
        pixmap =QPixmap('image/background/register.jpg')
        self.lab.setPixmap(pixmap)

        nicknameLabel = QLabel(self)
        nicknameLabel.setGeometry(QRect(40, 20, 81, 31))
        nicknameLabel.setFont(font)
        nicknameLabel.setText(self.tr("昵称:"))

        self.nameLineEdit = QLineEdit(self)
        self.nameLineEdit.setValidator(
            QRegExpValidator(QRegExp(r"\S+"), self.nameLineEdit))
        self.nameLineEdit.setGeometry(QRect(120, 20, 220, 30))
        self.nameLineEdit.setFont(font)
        self.nameLineEdit.setText(self.myInfo.nick_name)
        self.nameLineEdit.setStyleSheet("border:2px groove gray;border-radius:10px;padding:2px 4px")

        phoneLabel = QLabel(self)
        phoneLabel.setGeometry(QRect(20, 70, 81, 31))
        phoneLabel.setFont(font)
        phoneLabel.setText(self.tr("手机号:"))

        self.phoneLineEdit = QLineEdit(self)
        self.phoneLineEdit.setValidator(
            QRegExpValidator(QRegExp(r"[0-9]{7,11}"), self.phoneLineEdit))
        self.phoneLineEdit.setGeometry(QRect(120, 70, 220, 30))
        self.phoneLineEdit.setFont(font)
        self.phoneLineEdit.setText(self.myInfo.phone)
        self.phoneLineEdit.setStyleSheet("border:2px groove gray;border-radius:10px;padding:2px 4px")

        mailLabel = QLabel(self)
        mailLabel.setGeometry(QRect(40, 120, 63, 22))
        mailLabel.setFont(font)
        mailLabel.setText(self.tr("邮箱:"))

        self.mailLineEdit = QLineEdit(self)
        self.mailLineEdit.setValidator(
            QRegExpValidator(QRegExp(r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"), self.mailLineEdit))
        self.mailLineEdit.setGeometry(QRect(120, 120, 220, 30))
        self.mailLineEdit.setFont(font)
        self.mailLineEdit.setText(self.myInfo.mail)
        self.mailLineEdit.setStyleSheet("border:2px groove gray;border-radius:10px;padding:2px 4px")


        signLabel = QLabel(self)
        signLabel.setGeometry(QRect(385, 10, 111, 51))
        signLabel.setFont(font)
        signLabel.setText(self.tr("个性签名:"))

        self.signTextEdit = QTextEdit(self)
        self.signTextEdit.setGeometry(QRect(390, 70, 321, 381))
        self.signTextEdit.setFont(font)
        self.signTextEdit.setText(self.myInfo.signature)
        self.signTextEdit.setStyleSheet("border:4px groove gray;border-radius:10px;padding:0px 0px")

        genderLabel = QLabel(self)
        genderLabel.setGeometry(QRect(40, 170, 63, 22))
        genderLabel.setFont(font)
        genderLabel.setText(self.tr("性别:"))

        self.manradioButton = QRadioButton(self)
        self.manradioButton.setGeometry(QRect(130, 170, 51, 28))
        # self.manradioButton.setCheckable(True)
        # self.manradioButton.setChecked(True)
        self.manradioButton.setFont(font)
        self.manradioButton.setText("男")

        self.femaleradioButton = QRadioButton(self)
        self.femaleradioButton.setGeometry(QRect(200, 170, 51, 28))
        self.femaleradioButton.setFont(font)
        self.femaleradioButton.setText("女")

        self.sradioButton = QRadioButton(self)
        self.sradioButton.setGeometry(QRect(270, 170, 70, 28))
        self.sradioButton.setFont(font)
        self.sradioButton.setText("保密")

        gender_id = self.myInfo.gender
        if gender_id == 1:
            self.manradioButton.setChecked(True)
        elif gender_id == 2:
            self.femaleradioButton.setChecked(True)
        elif gender_id == 3:
            self.sradioButton.setChecked(True)

        ageLabel = QLabel(self)
        ageLabel.setGeometry(QRect(40, 220, 63, 22))
        ageLabel.setFont(font)
        ageLabel.setText(self.tr("年龄:"))

        self.ageLineEdit = QLineEdit(self)
        self.ageLineEdit.setValidator(QRegExpValidator(QRegExp(r"\S+"), self.ageLineEdit))
        self.ageLineEdit.setGeometry(QRect(120, 220, 220, 30))
        self.ageLineEdit.setFont(font)
        self.ageLineEdit.setReadOnly(True)
        self.ageLineEdit.setText(str(self.myInfo.age))
        self.ageLineEdit.setStyleSheet("border:2px groove gray;border-radius:10px;padding:2px 4px")

        birthLabel = QLabel(self)
        birthLabel.setGeometry(QRect(40, 260, 61, 41))
        birthLabel.setFont(font)
        birthLabel.setText(self.tr("生日:"))

        self.birthLineEdit = QLineEdit(self)
        self.birthLineEdit.setValidator(QRegExpValidator(QRegExp(r"^\d{4}-\d{1,2}-\d{1,2}"), self.birthLineEdit))
        self.birthLineEdit.setGeometry(QRect(120, 270, 220, 30))
        self.birthLineEdit.setFont(font)
        self.birthLineEdit.setText(self.myInfo.birthday)
        self.birthLineEdit.setStyleSheet("border:2px groove gray;border-radius:10px;padding:2px 4px")

        vocationLabel = QLabel(self)
        vocationLabel.setGeometry(QRect(40, 320, 63, 22))
        vocationLabel.setFont(font)
        vocationLabel.setText(self.tr("职业:"))

        self.vocationLineEdit = QLineEdit(self)
        self.vocationLineEdit.setValidator(QRegExpValidator(QRegExp(r"\S+"), self.vocationLineEdit))
        self.vocationLineEdit.setGeometry(QRect(120, 320, 220, 30))
        self.vocationLineEdit.setFont(font)
        self.vocationLineEdit.setText(self.myInfo.vocation)
        self.vocationLineEdit.setStyleSheet("border:2px groove gray;border-radius:10px;padding:2px 4px")

        cityLabel = QLabel(self)
        cityLabel.setGeometry(QRect(40, 370, 63, 22))
        cityLabel.setFont(font)
        cityLabel.setText(self.tr("城市:"))

        self.cityLineEdit = QLineEdit(self)
        self.cityLineEdit.setValidator(QRegExpValidator(QRegExp(r"\S+"), self.cityLineEdit))
        self.cityLineEdit.setGeometry(QRect(120, 370, 220, 30))
        self.cityLineEdit.setFont(font)
        self.cityLineEdit.setText("北京")
        self.cityLineEdit.setReadOnly(True)
        self.cityLineEdit.setStyleSheet("border:2px groove gray;border-radius:10px;padding:2px 4px")

        timeLabel = QLabel(self)
        timeLabel.setGeometry(QRect(40, 420, 100, 22))
        timeLabel.setFont(font)
        timeLabel.setText(self.tr("注册时间:"))

        self.timeLineEdit = QLineEdit(self)
        self.timeLineEdit.setGeometry(QRect(160, 420, 180, 30))
        self.timeLineEdit.setFont(font)
        self.timeLineEdit.setReadOnly(True)
        self.timeLineEdit.setText(self.myInfo.register_time)
        self.timeLineEdit.setStyleSheet("border:2px groove gray;border-radius:10px;padding:2px 4px")

        setButton = QPushButton(self)
        setButton.setText(self.tr("保存"))
        setButton.setGeometry(QRect(300, 500, 140, 40))
        setButton.setFont(font)
        setButton.clicked.connect(self.setButtonClicked)
        setButton.setStyleSheet("border:2px groove gray;border-radius:10px;padding:2px 4px")

    # 关闭界面的时候
    def closeEvent(self, QCloseEvent):
        self.closeSignal.emit()
        return super().closeEvent(QCloseEvent)

    # 单击保存按钮
    def setButtonClicked(self):
        my_info_dict = dict()
        my_info_dict['nick_name'] = self.nameLineEdit.text()
        my_info_dict['signature'] = self.signTextEdit.toPlainText()
        if self.manradioButton.isChecked():
            my_info_dict['gender_id'] = 1
        elif self.femaleradioButton.isChecked():
            my_info_dict['gender_id'] = 2
        elif self.sradioButton.isChecked():
            my_info_dict['gender_id'] = 3
        else:
            my_info_dict['gender_id'] = 3
        my_info_dict['birthday'] = self.birthLineEdit.text()
        my_info_dict['age'] = int(self.ageLineEdit.text())
        my_info_dict['telephone'] = self.phoneLineEdit.text()
        my_info_dict['email'] = self.mailLineEdit.text()
        my_info_dict['vocation'] = self.vocationLineEdit.text()
        self.setMyInfoSignal.emit(my_info_dict)

    # 返回修改是否成功
    def updateMyInfoStatusSlot(self, status):
        if status == '0':
            QMessageBox.information(self, self.tr("成功"), self.tr("保存成功!"))
            self.close()
        else:
            QMessageBox.critical(self, self.tr("失败"), self.tr("保存失败!请检查信息是否有误!"))
Ejemplo n.º 26
0
class EMGApp(QWidget):
    def __init__(self, width, height):
        super().__init__()
        self.width = width
        self.height = height

        # connect worker thread slots
        self.loop = Loop(self)
        self.loop.finished.connect(self.stop)
        self.loop.update_button.connect(self.updateButton)
        self.loop.output.connect(self.getOutput)
        self.workerThread = QThread()
        self.loop.moveToThread(self.workerThread)
        self.workerThread.start()

        self.runLoop = False
        self.mode = 0  # mode variable, see keyPressEvent()
        self.output = 0  # used for drawing cursor from worker thread
        self.flex = 0
        self.ext = 0
        self.target = 0  # target value. -100=full extension, 0=neutral position, 100=full flexion
        self.levels = 4  # amount of discrete levels in feedback, default = 4
        self.numberOfTargets = 30  # number of individual targets in test suite
        self.testSuite = "audiovisual"
        self.test = False

        self.initUI()

        self.setFocusPolicy(Qt.StrongFocus)
        self.grabKeyboard()
        self.setEnabled(True)
        self.show()

    def initUI(self):
        btn = QPushButton("Run continuous pitch-modulated signal", self)
        btn.setStyleSheet(
            "QPushButton { background-color: green; color: white }"
            "QPushButton:disabled { background-color: red; color: white }")
        btn.setGeometry(self.width / 2 - 200, self.height / 2 - 300, 400, 75)
        btn.clicked.connect(self.run)
        self.btn = btn

        self.targetTextbox = QLineEdit(self)
        self.targetTextbox.setGeometry(self.width / 2 - 300,
                                       self.height / 2 - 275, 50, 25)
        self.targetTextbox.setPlaceholderText('0')
        l1 = QLabel(self)
        l1.setText("Set target level")
        l1.setGeometry(self.width / 2 - 320, self.height / 2 - 300, 100, 25)
        self.levelsTextbox = QLineEdit(self)
        self.levelsTextbox.setGeometry(self.width / 2 + 250,
                                       self.height / 2 - 275, 50, 25)
        self.levelsTextbox.setPlaceholderText('4')
        l2 = QLabel(self)
        l2.setText("Set number of feedback levels")
        l2.setGeometry(self.width / 2 + 210, self.height / 2 - 300, 150, 25)

        self.radiobuttonAudioVisual = QRadioButton(self)
        self.radiobuttonAudioVisual.setGeometry(self.width / 2 + 450,
                                                self.height / 2 - 310, 150, 25)
        self.radiobuttonAudioVisual.setText("Audio + visual feedback")
        self.radiobuttonAudioVisual.mode = "audiovisual"
        self.radiobuttonAudioVisual.toggled.connect(self.onClicked)
        self.radiobuttonAudio = QRadioButton(self)
        self.radiobuttonAudio.setGeometry(self.width / 2 + 450,
                                          self.height / 2 - 280, 150, 25)
        self.radiobuttonAudio.setText("Audio feedback only")
        self.radiobuttonAudio.mode = "audio"
        self.radiobuttonAudio.toggled.connect(self.onClicked)
        self.radiobuttonVisual = QRadioButton(self)
        self.radiobuttonVisual.setGeometry(self.width / 2 + 450,
                                           self.height / 2 - 250, 150, 25)
        self.radiobuttonVisual.setText("Visual feedback only")
        self.radiobuttonVisual.mode = "visual"
        self.radiobuttonVisual.toggled.connect(self.onClicked)

        self.checkboxMode = QCheckBox(self)
        self.checkboxMode.setGeometry(self.width / 2 - 650,
                                      self.height / 2 - 280, 250, 25)
        self.checkboxMode.setText(
            f"Run automated test sequence with {self.numberOfTargets} targets?"
        )
        self.checkboxMode.toggled.connect(self.checkboxToggle)

    def onClicked(self):
        radioButton = self.sender()
        if radioButton.isChecked():
            mode = radioButton.mode
            self.testSuite = mode

    def checkboxToggle(self):
        if self.test == False:
            self.test = True
        else:
            self.test = False

    def run(self):
        if self.runLoop == False:
            self.runLoop = True
            try:
                self.target = int(self.targetTextbox.text())
            except ValueError:
                ''' test mode, generates an evenly distributed array of _30_ different targets within level range '''
                self.target = 0
            try:
                self.levels = int(self.levelsTextbox.text())
            except ValueError:
                self.levels = 4
            self.loop.variables.emit([
                self.mode, self.target, self.levels, self.numberOfTargets,
                self.test, self.testSuite
            ])

        else:
            self.runLoop = False

    @pyqtSlot()
    def stop(self):
        self.runLoop = False

    @pyqtSlot(list)
    def getOutput(self, output):
        if self.runLoop == True:
            self.output = output[0]
            self.flex = output[1]
            self.ext = output[2]
            self.target = output[3]
            self.repaint()

    @pyqtSlot(list)
    def updateButton(self, ls):
        self.btn.setText(ls[0])
        self.btn.setEnabled(ls[1])

    def paintEvent(self, event):
        self.output = -self.output
        self.target = -self.target
        wCenter = self.width / 2
        hCenter = self.height / 2
        painter = QPainter(self)
        painter.begin(self)
        painter.drawText(
            wCenter - 50, hCenter - 100,
            f"Target: {-(self.target * 255/self.levels - 255/self.levels)/255*100:.1f} - {-(self.target * 255/self.levels)/255*100:.1f}%"
        )
        if self.testSuite == "audio":
            return
        cursorWPos = wCenter + 3 * (self.output)
        flex = -self.flex
        ext = -self.ext
        flexPos = wCenter + 3 * (flex)
        extPos = wCenter - 3 * (ext)

        target_higher = self.target * (256 / self.levels)
        if self.target == 0:
            targetWPosL = wCenter - 20
            targetWPosR = 40
        else:
            if self.target > 0:
                target_lower = target_higher - (256 / self.levels)
                targetWPosL = wCenter + 3 * target_higher - 3 * 256 / self.levels
                targetWPosR = 3 * 256 / self.levels
            elif self.target < 0:
                target_lower = target_higher * (256 / self.levels)
                targetWPosL = wCenter + 3 * target_higher
                targetWPosR = 3 * 256 / self.levels
        brush = QBrush(Qt.darkGray)
        # coloured cursor indicators
        if self.output >= 0:
            painter.setPen(QPen(QColor(255, 0, 0, 64)))
            brush.setColor(QColor(255, 0, 0, 128))
            painter.fillRect(wCenter, hCenter - 50, 3 * (self.output), 100,
                             brush)
        else:
            painter.setPen(QPen(QColor(0, 255, 0, 64)))
            brush.setColor(QColor(0, 255, 0, 128))
            painter.fillRect(cursorWPos, hCenter - 50, wCenter - cursorWPos,
                             100, brush)

        # target intensity area
        brush.setColor(QColor(0, 0, 0, 32))
        painter.setPen(QPen(Qt.black, 2))
        painter.fillRect(targetWPosL, hCenter - 50, targetWPosR, 100, brush)
        # line
        painter.setPen(QPen(Qt.black, 4))
        painter.drawLine(140, hCenter, self.width - 140, hCenter)
        painter.setPen(QPen(Qt.darkGray, 2))
        painter.drawLine(140, hCenter, self.width - 140, hCenter)
        # cursor
        painter.drawLine(cursorWPos, hCenter + 50, cursorWPos, hCenter - 50)
        # flexor and extensor indicators
        painter.setPen(QPen(QColor(0, 255, 0, 64)))
        brush.setColor(QColor(0, 255, 0, 128))
        painter.fillRect(wCenter, hCenter + 150, 3 * (flex), 100, brush)
        painter.setPen(QPen(QColor(255, 0, 0, 64)))
        brush.setColor(QColor(255, 0, 0, 128))
        painter.fillRect(extPos, hCenter + 150, wCenter - extPos, 100, brush)
        # line for flexor and extensor values
        painter.setPen(QPen(Qt.black, 4))
        painter.drawLine(140, hCenter + 200, self.width - 140, hCenter + 200)
        painter.setPen(QPen(Qt.darkGray, 2))
        painter.drawLine(140, hCenter + 200, self.width - 140, hCenter + 200)
        # cursor for flexor
        painter.drawLine(flexPos, hCenter + 150, flexPos, hCenter + 250)
        # cursor for extensor
        painter.drawLine(extPos, hCenter + 150, extPos, hCenter + 250)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Space:
            self.run()
        if key == Qt.Key_1:
            self.mode = 0
            self.btn.setText("Run continuous pitch-modulated signal")
        if key == Qt.Key_2:
            self.mode = 1
            self.btn.setText("Run discrete pitch-modulated signal")
        if key == Qt.Key_3:
            self.mode = 2
            self.btn.setText("Run temporal frequency modulated pulse signal")
        if key == Qt.Key_4:
            self.mode = 3
            self.btn.setText("Run temporal frequency modulated pattern signal")
Ejemplo n.º 27
0
class ImgScaleView(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.defaultView()
        self.reloadUI()
        self.funType = -1

    def defaultView(self):
        self.setWindowFlags(QtCore.Qt.WindowTitleHint
                            | QtCore.Qt.WindowCloseButtonHint)
        self.resize(viewWid, viewHei)
        self.setFixedSize(viewWid, viewHei)
        self.setStyleSheet('background-color:#fff')
        self.center()
        self.setWindowTitle(zfjTools.baseTitle)

    def initUI(self):
        font = QtGui.QFont()
        font.setPointSize(18)
        margin_top = margin_size
        titleLab = QLabel('图片压缩工具', self)
        titleLab.setStyleSheet('color:#d4237a;')
        titleLab.setAlignment(Qt.AlignCenter)
        titleLab.setGeometry(
            QtCore.QRect(margin_size, margin_top, viewWid - margin_size * 2,
                         40))
        titleLab.setFont(font)
        backMainViewBtn = QtWidgets.QPushButton(self)
        backMainViewBtn.setGeometry(
            QtCore.QRect(margin_size, margin_top + 7.5, 50, 25))
        backMainViewBtn.setObjectName('logInBtn')
        backMainViewBtn.setText(_translate('MainWindow', '返回'))
        backMainViewBtn.setStyleSheet(
            'color:#1667ea;background-color:#fff;border:1px solid #1667ea;')
        backMainViewBtn.clicked.connect(self.backMainViewBtnClick)
        font.setPointSize(14)
        backMainViewBtn.setFont(font)
        margin_top += 40 + margin_size
        oldImgLab = QLabel('请选择图片所在路径:', self)
        oldImgLab.setStyleSheet('color:#000000;')
        oldImgLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        oldImgLab.setGeometry(QtCore.QRect(margin_size, margin_top, 135, 30))
        font.setPointSize(14)
        oldImgLab.setFont(font)
        self.oldImgEdit = QtWidgets.QLineEdit(self)
        self.oldImgEdit.setGeometry(
            QtCore.QRect(135 + margin_size * 2, margin_top, 350, 30))
        font.setPointSize(14)
        self.oldImgEdit.setFont(font)
        self.oldImgEdit.setText('/Users/zhangfujie/Desktop/Obfuscated')
        oldImgPathBtn = QtWidgets.QPushButton(self)
        oldImgPathBtn.setGeometry(
            QtCore.QRect(margin_size * 3 + 135 + 350, margin_top, 100, 30))
        oldImgPathBtn.setText(_translate('MainWindow', '选择文件夹'))
        oldImgPathBtn.setStyleSheet(
            'color:#000000;background-color:#efeff3;border:1px solid #efeff3;')
        oldImgPathBtn.clicked.connect(self.oldImgPathBtnClick)
        oldImgPathBtn.setFont(font)
        margin_top += 30 + margin_size
        newImgLab = QLabel('请选择图片保存路径:', self)
        newImgLab.setStyleSheet('color:#000000;')
        newImgLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        newImgLab.setGeometry(QtCore.QRect(margin_size, margin_top, 135, 30))
        font.setPointSize(14)
        newImgLab.setFont(font)
        self.newImgEdit = QtWidgets.QLineEdit(self)
        self.newImgEdit.setGeometry(
            QtCore.QRect(135 + margin_size * 2, margin_top, 350, 30))
        font.setPointSize(14)
        self.newImgEdit.setFont(font)
        self.newImgEdit.setText('/Users/zhangfujie/Desktop/Obfuscated/NewImgs')
        newImgPathBtn = QtWidgets.QPushButton(self)
        newImgPathBtn.setGeometry(
            QtCore.QRect(margin_size * 3 + 135 + 350, margin_top, 100, 30))
        newImgPathBtn.setText(_translate('MainWindow', '选择文件夹'))
        newImgPathBtn.setStyleSheet(
            'color:#000000;background-color:#efeff3;border:1px solid #efeff3;')
        newImgPathBtn.clicked.connect(self.newImgPathBtnClick)
        newImgPathBtn.setFont(font)
        margin_top += 30 + margin_size
        line_lab = QLabel(self)
        line_lab.setStyleSheet('background-color:#dcdcdc')
        line_lab.setGeometry(QtCore.QRect(0, margin_top, viewWid, 1))
        margin_top += 1 + margin_size
        smlTitLab = QLabel('请选择图片压缩方式', self)
        smlTitLab.setStyleSheet('color:#d4237a;')
        smlTitLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        smlTitLab.setGeometry(QtCore.QRect(margin_size, margin_top, 135, 30))
        smlTitLab.setFont(font)
        textEditWid = (viewWid - margin_size * 3) / 2
        self.textEdit = QTextEdit(self)
        self.textEdit.setStyleSheet('background-color:#262626;color:#fff;')
        self.textEdit.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.textEdit.setGeometry(
            QtCore.QRect(textEditWid - margin_size * 5, margin_top,
                         textEditWid + margin_size * 6, 411 - margin_top))
        font.setPointSize(12)
        self.textEdit.setFont(font)
        margin_top += 30 + margin_size
        self.sysBtn = QRadioButton('自动生成@1x,@2x,@3x', self)
        self.sysBtn.setStyleSheet('color:#000;')
        self.sysBtn.setGeometry(
            QtCore.QRect(margin_size * 2, margin_top, 200, 30))
        self.sysBtn.setChecked(False)
        self.sysBtn.toggled.connect(lambda: self.radioBtnClick(self.sysBtn))
        margin_top += 30 + margin_size
        self.userBtn = QRadioButton('手动设置图片尺寸(格式:宽x高)', self)
        self.userBtn.setStyleSheet('color:#000;')
        self.userBtn.setGeometry(
            QtCore.QRect(margin_size * 2, margin_top, 200, 30))
        self.userBtn.setChecked(False)
        self.userBtn.toggled.connect(lambda: self.radioBtnClick(self.userBtn))
        titleArr = ['@1x尺寸:', '@2x尺寸:', '@3x尺寸:']
        self.checkBoxList = []
        self.checkBoxEditList = []
        for index in range(0, 3):
            margin_top += 30 + margin_size
            checkBox = QCheckBox(titleArr[index], self)
            checkBox.setStyleSheet('color:#000;')
            checkBox.stateChanged.connect(self.checkBoxClick)
            checkBox.setGeometry(
                QtCore.QRect(margin_size * 4, margin_top, 80, 30))
            self.checkBoxList.append(checkBox)
            checkBoxEdit = QtWidgets.QLineEdit(self)
            checkBoxEdit.setText('0x0')
            checkBoxEdit.setGeometry(
                QtCore.QRect(margin_size * 4 + 80, margin_top,
                             200 - (margin_size * 4 + 80) + margin_size * 2,
                             30))
            checkBoxEdit.setFont(font)
            checkBoxEdit.setStyleSheet(
                'color:#cc0066;background-color:#efeff3;')
            checkBoxEdit.textChanged.connect(
                lambda: self.checkBoxEditChanged(index))
            self.checkBoxEditList.append(checkBoxEdit)

        margin_top += 30 + margin_size
        self.alphaCheckBox = QCheckBox('移除PNG的alpha通道', self)
        self.alphaCheckBox.setStyleSheet('color:#000;')
        self.alphaCheckBox.stateChanged.connect(self.checkBoxClick)
        self.alphaCheckBox.setGeometry(
            QtCore.QRect(margin_size * 2, margin_top, 200, 30))
        margin_top += 30 + margin_size
        self.imgTypeBox = QCheckBox('webp', self)
        self.imgTypeBox.setStyleSheet('color:#000;')
        self.imgTypeBox.stateChanged.connect(self.checkBoxClick)
        self.imgTypeBox.setGeometry(
            QtCore.QRect(margin_size * 2, margin_top, 200, 30))
        margin_top += 30 + margin_size * 5
        startScaleBtn = QtWidgets.QPushButton(self)
        startScaleBtn.setGeometry(
            QtCore.QRect((viewWid - 160) / 2, margin_top, 160, 40))
        startScaleBtn.setText(_translate('MainWindow', '开始压缩'))
        startScaleBtn.setStyleSheet(
            'background-color:#fff;color:#cc0066;border:1px solid #cc0066;')
        startScaleBtn.clicked.connect(self.startScaleBtnClick)
        font.setPointSize(18)
        startScaleBtn.setFont(font)
        margin_top += 40 + margin_size * 2
        tipsTitLab = QLabel('使用须知', self)
        tipsTitLab.setStyleSheet('color:#d4237a;')
        tipsTitLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        tipsTitLab.setGeometry(
            QtCore.QRect(margin_size, margin_top, viewWid - margin_size * 2,
                         30))
        font.setPointSize(14)
        tipsTitLab.setFont(font)
        margin_top += 30
        tipsLabText = '1.选择自动生成@1x、@2x、@3x时,默认把原图作为@3x, @1x和@2x在此基础上向下压缩;\n2.选择手动设置图片尺寸时,为了保证图片的清晰质量,原图尺寸最好大于等于三倍尺寸;'
        tipsLab = QLabel(tipsLabText, self)
        tipsLab.setStyleSheet('color:#87b753;')
        tipsLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        tipsLab.setGeometry(
            QtCore.QRect(margin_size, margin_top, viewWid - margin_size * 2,
                         50))
        font.setPointSize(12)
        tipsLab.setFont(font)
        margin_top += 50 + margin_size
        line_lab_1 = QLabel(self)
        line_lab_1.setStyleSheet('background-color:#dcdcdc')
        line_lab_1.setGeometry(QtCore.QRect(0, margin_top, viewWid, 1))
        margin_top += 1 + margin_size
        downLab_wid = (viewWid - margin_size * 3) / 2
        self.accountLab = QLabel(':', self)
        self.accountLab.setStyleSheet('color:#000;')
        self.accountLab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.accountLab.setGeometry(
            QtCore.QRect(margin_size, margin_top, downLab_wid, 30))
        font.setPointSize(13)
        self.accountLab.setFont(font)
        self.timeLab = QLabel(':', self)
        self.timeLab.setStyleSheet('color:#000;')
        self.timeLab.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.timeLab.setGeometry(
            QtCore.QRect(margin_size * 2 + downLab_wid, margin_top,
                         downLab_wid, 30))
        font.setPointSize(13)
        self.timeLab.setFont(font)
        margin_top += 30 + margin_size

    def backMainViewBtnClick(self):
        personinfo = ZFJPersoninfo()
        if personinfo.mainRootView != None:
            personinfo.mainRootView.show()
            self.close()
        else:
            print('mainRootView')

    def oldImgPathBtnClick(self):
        file_dir = ''
        try:
            file_dir = QFileDialog.getExistingDirectory(
                self, 'open file', '/Users/')
        except Exception as e:
            try:
                file_dir = ','
            finally:
                e = None
                del e

        self.oldImgEdit.setText(file_dir)

    def newImgPathBtnClick(self):
        file_dir = ''
        try:
            file_dir = QFileDialog.getExistingDirectory(
                self, 'open file', '/Users/')
        except Exception as e:
            try:
                file_dir = ','
            finally:
                e = None
                del e

        self.newImgEdit.setText(file_dir)

    def radioBtnClick(self, btn):
        if self.sysBtn.isChecked() == True:
            self.funType = 0
            for checkBox in self.checkBoxList:
                checkBox.setCheckState(Qt.Unchecked)

            for checkBoxEdit in self.checkBoxEditList:
                checkBoxEdit.setText('')

        else:
            self.funType = 1
            for checkBox in self.checkBoxList:
                checkBox.setCheckState(Qt.Checked)

    def checkBoxClick(self):
        if self.sysBtn.isChecked() == True or self.funType == -1:
            for checkBox in self.checkBoxList:
                checkBox.setCheckState(Qt.Unchecked)

    def checkBoxEditChanged(self, index):
        if self.sysBtn.isChecked() == True or self.funType == -1:
            for checkBoxEdit in self.checkBoxEditList:
                checkBoxEdit.setText('0x0')

    def startScaleBtnClick(self):
        oldImgPath = self.oldImgEdit.text()
        if len(oldImgPath) == 0:
            self.megBoxInfor('')
            return
        if os.path.exists(oldImgPath) == False:
            self.megBoxInfor('')
            return
        newImgPath = self.newImgEdit.text()
        if len(newImgPath) == 0:
            self.megBoxInfor('')
            return
        if os.path.exists(newImgPath) == False:
            self.megBoxInfor('')
            return
        sizeTupList = None
        if self.funType == 1:
            checkCount = 0
            for checkBox in self.checkBoxList:
                if checkBox.checkState() == Qt.Checked:
                    checkCount += 1
                    continue

            if checkCount == 0:
                self.megBoxInfor('')
                return
            titleArr = ['@1x', '@2x', '@3x']
            for index in range(0, len(self.checkBoxEditList)):
                checkBox = self.checkBoxList[index]
                checkBoxEdit = self.checkBoxEditList[index]
                checkBoxEditText = checkBoxEdit.text().replace('X', 'x')
                if checkBox.checkState() == Qt.Checked:
                    if 'x' not in checkBoxEditText:
                        self.megBoxInfor('' + titleArr[index] + '(:100x100)')
                        return
                    if zfjTools.is_number(checkBoxEditText.replace(
                            'x', '')) == False:
                        self.megBoxInfor('' + titleArr[index] + '(:100x100)')
                        return
                    width = checkBoxEditText[:checkBoxEditText.find('x')]
                    if len(width) == 0:
                        width = '0'
                    height = checkBoxEditText[checkBoxEditText.find('x') + 1:]
                    if len(height) == 0:
                        height = '0'
                    if int(width) <= 0:
                        self.megBoxInfor(titleArr[index] + '<=0(:100x100)')
                        return
                    if int(height) <= 0:
                        self.megBoxInfor(titleArr[index] + '<=0(:100x100)')
                        return
                    sizeTup = (width, height)
                    sizeTupList.append(sizeTup)
                else:
                    sizeTup = (0, 0)
                    sizeTupList.append(sizeTup)

        else:
            if self.funType == 0:
                sizeTupList = []
            else:
                sizeTupList = None
            isCloseAlpha = False
            if self.alphaCheckBox.checkState() == Qt.Checked:
                isCloseAlpha = True
            isUpDateImgType = False
            if self.imgTypeBox.checkState() == Qt.Checked:
                isUpDateImgType = True
            self.textEdit.clear()
            imageScaleObj.startScaleImg(oldImgPath, newImgPath, sizeTupList,
                                        isCloseAlpha, isUpDateImgType)

    def reloadUI(self):
        personinfo = ZFJPersoninfo()
        self.accountLab.setText(':' + str(personinfo.account))
        self.timeLab.setText(':' + personinfo.expireDate.replace('"', ''))

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def megBoxInfor(self, infor):
        QMessageBox.information(self, '', infor, QMessageBox.Yes)
Ejemplo n.º 28
0
    def init_ui(self):
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setGeometry(-70, 260, 341, 32)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)

        self.gridLayoutWidget_2 = QWidget(self)
        self.gridLayoutWidget_2.setGeometry(130, 20, 121, 91)

        self.gridLayout_2 = QGridLayout(self.gridLayoutWidget_2)
        self.gridLayout_2.setContentsMargins(0, 0, 0, 0)

        for i, row in enumerate([('Высота', 'Ширина', 'Мины'), *self.modes.values()]):
            for j, col in enumerate(row):
                label = QLabel(self.gridLayoutWidget_2)
                label.setText(str(col))
                label.setAlignment(QtCore.Qt.AlignCenter)
                self.gridLayout_2.addWidget(label, i, j, 1, 1)

        mode_label = QLabel(self)
        mode_label.setGeometry(QtCore.QRect(65, 20, 61, 18))
        mode_label.setText('Режим')
        mode_label.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignCenter |
                                QtCore.Qt.AlignVCenter)

        self.buttonGroup = QButtonGroup(self)
        checkbutton_list = []
        for n, key in enumerate([*self.modes.keys(), 'Особый']):
            rb = QRadioButton(self)
            self.buttonGroup.addButton(rb)
            rb.setGeometry(60, 45 + 25 * n, 71, 17)
            rb.setText(key)
            checkbutton_list.append(rb)

        self.easy, self.normal, self.hard, self.special = checkbutton_list

        lcd_list, slider_list = [], []
        for n, (minimum, maximum) in enumerate([(9, 21), (9, 46), (9, 27)]):
            offset = 40 * n
            slider = QSlider(self)
            slider.setEnabled(False)
            slider.setGeometry(70, 150 + offset, 248, 22)
            slider.setMinimum(minimum)
            slider.setMaximum(maximum)
            slider.setOrientation(QtCore.Qt.Horizontal)
            slider_list.append(slider)

            label = QLabel(self)
            label.setGeometry(22, 147 + offset, 47, 13)
            label.setText(['Высота', 'Ширина', 'Бомбы'][n])

            sublabel = QLabel(self)
            sublabel.setGeometry(22, 157 + offset, 41, 16)
            sublabel.setText(f'[{minimum}-{maximum}]')

            lcd = QLCDNumber(self)
            lcd.setGeometry(327, 148 + offset, 41, 21)
            lcd.setDigitCount(3)
            lcd.setSegmentStyle(QLCDNumber.Flat)
            lcd.setProperty("intValue", 9)
            lcd_list.append(lcd)

        self.bombs_label = sublabel
        self.height_slider, self.width_slider, self.bombs_slider = slider_list
        self.height_lcd, self.width_lcd, self.bombs_lcd = lcd_list

        self.buttonGroup.buttonClicked.connect(self.checked)
        self.mode = (9, 9, 10)
        self.setWindowTitle("Сложность")
        self.easy.setChecked(True)
        self.okay_clicked = False
        for slider in [self.bombs_slider, self.width_slider, self.height_slider]:
            slider.valueChanged.connect(self.recalculate_sliders)

        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
Ejemplo n.º 29
0
class AlterMessage(QDialog):

    close_signal = pyqtSignal()

    def __init__(self, mess, connfd):
        super(AlterMessage, self).__init__()
        self.connfd = connfd
        self.mess = mess.split('#')
        self.timekey = False
        self.data = ''
        self.initUI()

    def initUI(self):
        # 创建固定窗口大小
        self.setFixedSize(535, 600)
        # 窗口标题
        self.setWindowTitle('注册')
        # 无边框
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowIcon(QIcon(':/logo.png'))

        window_pale = QPalette()
        window_pale.setBrush(self.backgroundRole(),\
                QBrush(QPixmap("UI/image/altermessage.jpg")))
        self.setPalette(window_pale)

        #设置字体颜色
        pe = QPalette()
        pe.setColor(QPalette.WindowText, Qt.white)
        # 程序名
        self.lbl_main = QLabel('修改货运信息', self)
        self.lbl_main.move(10, 10)
        self.lbl_main.setPalette(pe)

        # 创建发货地级联布局
        self.centralwidget = QWidget(self)
        self.centralwidget.setGeometry(90, 50, 400, 40)
        layout = QHBoxLayout(self.centralwidget)
        self.province_box = QComboBox(self, minimumWidth=30)  # 市级以上
        self.province_box.setMaxVisibleItems(35)
        self.city_box = QComboBox(self, minimumWidth=73)  # 市
        self.city_box.setMaxVisibleItems(35)
        self.county_box = QComboBox(self, minimumWidth=73)  # 市级以下
        self.county_box.setMaxVisibleItems(35)
        layout.addWidget(self.province_box)
        province = QLabel("省", self)
        province.setPalette(pe)
        layout.addWidget(province)
        layout.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        layout.addWidget(self.city_box)
        city = QLabel("市", self)
        city.setPalette(pe)
        layout.addWidget(city)
        layout.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        layout.addWidget(self.county_box)
        county = QLabel("区/县", self)
        county.setPalette(pe)
        layout.addWidget(county)

        # 创建目的地级联布局
        self.centralwidget2 = QWidget(self)
        self.centralwidget2.setGeometry(90, 96, 400, 40)
        layout2 = QHBoxLayout(self.centralwidget2)
        self.province_box2 = QComboBox(self, minimumWidth=30)  # 市级以上
        self.province_box2.setMaxVisibleItems(35)
        self.city_box2 = QComboBox(self, minimumWidth=73)  # 市
        self.city_box2.setMaxVisibleItems(35)
        self.county_box2 = QComboBox(self, minimumWidth=73)  # 市级以下
        self.county_box2.setMaxVisibleItems(35)
        layout2.addWidget(self.province_box2)
        province2 = QLabel("省", self)
        province2.setPalette(pe)
        layout2.addWidget(province2)
        layout2.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        layout2.addWidget(self.city_box2)
        city2 = QLabel("市", self)
        city2.setPalette(pe)
        layout2.addWidget(city2)
        layout2.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        layout2.addWidget(self.county_box2)
        county2 = QLabel("区/县", self)
        county2.setPalette(pe)
        layout2.addWidget(county2)
        self.initModel()
        self.initSignal()
        self.initData()

        for i in range(self.province_box.count()):
            if self.province_box.itemText(i) == self.mess[1]:
                self.province_box.setCurrentIndex(i)
                break
        for i in range(self.city_box.count()):
            if self.city_box.itemText(i) == self.mess[2]:
                self.city_box.setCurrentIndex(i)
                break
        for i in range(self.county_box.count()):
            if self.county_box.itemText(i) == self.mess[3]:
                self.county_box.setCurrentIndex(i)
                break
        for i in range(self.province_box2.count()):
            if self.province_box2.itemText(i) == self.mess[4]:
                self.province_box2.setCurrentIndex(i)
                break
        for i in range(self.city_box2.count()):
            if self.city_box2.itemText(i) == self.mess[5]:
                self.city_box2.setCurrentIndex(i)
                break
        for i in range(self.county_box2.count()):
            if self.county_box2.itemText(i) == self.mess[6]:
                self.county_box2.setCurrentIndex(i)
                break

        #设置字体颜色
        pe = QPalette()
        pe.setColor(QPalette.WindowText, Qt.darkGray)

        self.l = ['轻卡货车', '中型货车', '大型货车', '自卸货车', '半挂货车']
        x = 100
        self.bg1 = QButtonGroup(self)
        for i in range(len(self.l)):
            self.bu = QRadioButton(self.l[i], self)
            self.bu.setGeometry(x, 150, 75, 28)
            self.bu.setPalette(pe)
            self.bg1.addButton(self.bu, i)
            x += 80

        self.info1 = self.mess[7]
        self.bg1.buttonClicked.connect(self.rbclicked)
        self.bg1.buttons()[self.l.index(self.mess[7])].toggle()

        self.l2 = ['均货', '重货', '轻货', '整车', '零担']
        x = 100
        self.bg12 = QButtonGroup(self)
        for i in range(10, 10 + len(self.l2)):
            self.bu = QRadioButton(self.l2[i - 10], self)
            self.bu.setGeometry(x, 180, 75, 28)
            # self.bu.toggle()
            self.bu.setPalette(pe)
            self.bg12.addButton(self.bu, i)
            x += 80

        self.info12 = self.mess[8]
        self.bg12.buttonClicked.connect(self.rbclicked)
        self.bg12.buttons()[self.l2.index(self.mess[8])].toggle()

        self.l3 = ['普货', '鲜货', '冻货', '大件设备']
        x = 100
        self.bg13 = QButtonGroup(self)
        for i in range(20, 20 + len(self.l3)):
            self.bu = QRadioButton(self.l3[i - 20], self)
            self.bu.setGeometry(x, 210, 75, 28)
            self.bu.setPalette(pe)
            self.bg13.addButton(self.bu, i)
            x += 80

        self.info13 = self.mess[9]
        self.bg13.buttonClicked.connect(self.rbclicked)
        self.bg13.buttons()[self.l3.index(self.mess[9])].toggle()

        self.l4 = ['无要求','20-50万','50-100万',\
                                    '100-300万','300万以上']
        x = 100
        self.bg14 = QButtonGroup(self)
        for i in range(30, 30 + len(self.l4)):
            self.bu = QRadioButton(self.l4[i - 30], self)
            self.bu.setGeometry(x, 240, 75, 28)
            self.bu.setPalette(pe)
            self.bg14.addButton(self.bu, i)
            x += 80
        self.info14 = self.mess[10]
        self.bg14.buttonClicked.connect(self.rbclicked)
        self.bg14.buttons()[self.l4.index(self.mess[10])].toggle()

        conceal = "background:\
            transparent;border-width:0;border-style:outset"

        self.Edit_bulk = QLineEdit(self)
        self.Edit_bulk.setGeometry(100, 290, 100, 22)
        self.Edit_bulk.setPlaceholderText('方量')
        self.Edit_bulk.setStyleSheet(conceal)
        self.Edit_bulk.setValidator(QRegExpValidator\
                        (QRegExp(r"[0-9]+.?[0-9]?"),self))
        self.Edit_bulk.setMaxLength(6)
        self.Edit_bulk.setToolTip('方量最大长度6位')
        self.Edit_bulk.setText(self.mess[11])

        self.weight = QLineEdit(self)
        self.weight.setGeometry(245, 290, 100, 22)
        self.weight.setPlaceholderText('总吨位')
        self.weight.setStyleSheet(conceal)
        self.weight.setValidator(QRegExpValidator\
                    (QRegExp(r"[0-9]+.?[0-9]?"),self))
        self.weight.setMaxLength(6)
        self.weight.setToolTip('吨位最大长度6位')
        self.weight.setText(self.mess[12])

        self.Edit_total = QLineEdit(self)
        self.Edit_total.setGeometry(400, 290, 100, 22)
        self.Edit_total.setPlaceholderText('运费')
        self.Edit_total.setStyleSheet(conceal)
        self.Edit_total.setValidator(QRegExpValidator\
                                (QRegExp(r"[0-9]+"),self))
        self.Edit_total.setMaxLength(7)
        self.Edit_total.setToolTip('运费最大长度为6位的整数')
        self.Edit_total.setText(self.mess[13])

        self.text_describe = QTextEdit(self)
        self.text_describe.setGeometry(100, 340, 370, 150)
        self.text_describe.setToolTip('300字以内')
        self.text_describe.setStyleSheet(conceal)

        self.text_describe.setPlaceholderText('300字以内')
        self.text_describe.setPlainText(self.mess[15])

        self.Edit_phone = QLineEdit(self)
        self.Edit_phone.setGeometry(100, 518, 150, 22)
        self.Edit_phone.setPlaceholderText('手机号码')
        self.Edit_phone.setStyleSheet(conceal)
        self.Edit_phone.setValidator(QRegExpValidator\
                                (QRegExp(r"[0-9]+"),self))
        self.Edit_phone.setMaxLength(11)
        self.Edit_phone.setToolTip('联系电话11位')
        self.Edit_phone.setText(self.mess[14])

        l = ['请选择','12小时','24小时','3天内','5天内',\
                        '1周内','1月内','3月内','1年内','永久']
        self.combo = QComboBox(self)
        self.combo.addItems(l)
        self.combo.setGeometry(400, 518, 70, 20)
        validity = int(self.mess[17]) - int(self.mess[16])
        if validity == 43200:
            validity = '12小时'
        elif validity == 86400:
            validity = '24小时'
        elif validity == 259200:
            validity = '3天内'
        elif validity == 432000:
            validity = '5天内'
        elif validity == 604800:
            validity = '1周内'
        elif validity == 2592000:
            validity = '1月内'
        elif validity == 7776000:
            validity = '3月内'
        elif validity == 31536000:
            validity = '1年内'
        elif validity == 999999999:
            validity = '永久'
        for i in range(self.combo.count()):
            if self.combo.itemText(i) == validity:
                self.combo.setCurrentIndex(i)
                break

        color2 = "QPushButton{border:none;}"\
                "QPushButton:hover{border-image:url(%s);border:none;}"

        self.button_issue = QPushButton(' ', self)
        self.button_issue.setGeometry(100, 562, 230, 26)
        self.button_issue.setStyleSheet\
                            (color2 % 'UI/image/altermessage1.png')
        self.button_issue.clicked.connect(self.onissue)

        self.centralwidget = QWidget(self)
        self.centralwidget.setGeometry(350, 555, 150, 40)
        self.gridLayout = QGridLayout(self.centralwidget)
        # 定义获取焦点事件
        self.Edit_bulk.installEventFilter(self)
        self.Edit_total.installEventFilter(self)
        self.text_describe.installEventFilter(self)
        self.Edit_phone.installEventFilter(self)
        self.combo.installEventFilter(self)
        self.province_box.installEventFilter(self)
        self.city_box.installEventFilter(self)
        self.county_box.installEventFilter(self)
        self.province_box2.installEventFilter(self)
        self.city_box2.installEventFilter(self)
        self.county_box2.installEventFilter(self)

        self.button_little = QPushButton(' ', self)
        self.button_little.setGeometry(471, 0, 32, 25)
        self.button_little.setToolTip('最小化')
        self.button_little.setStyleSheet\
                            (color2 % 'UI/image/login3.png')

        self.button_close = QPushButton(' ', self)
        self.button_close.setGeometry(503, 0, 32, 25)
        self.button_close.setToolTip('关闭')
        self.button_close.setStyleSheet\
                            (color2 % 'UI/image/login2.png')

        self.button_little.clicked.connect(self.showMinimized)

    # 定义获取焦点事件
    def eventFilter(self, obj, event):
        if obj == self.Edit_bulk:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.Edit_total:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.text_describe:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.Edit_phone:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.combo:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.province_box:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.city_box:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.county_box:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.province_box2:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.city_box2:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.county_box2:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False

    def period_of_validity(self):
        now_time = round(time.time())
        if self.combo.currentText() == '12小时':
            endtime = str(now_time + 43200)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '24小时':
            endtime = str(now_time + 86400)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '3天内':
            endtime = str(now_time + 259200)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '5天内':
            endtime = str(now_time + 432000)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '1周内':
            endtime = str(now_time + 604800)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '1月内':
            endtime = str(now_time + 2592000)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '3月内':
            endtime = str(now_time + 7776000)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '1年内':
            endtime = str(now_time + 31536000)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '永久':
            endtime = str(now_time + 999999999)
            return str(now_time) + '#' + endtime

    def onissue(self):
        s_province = self.province_box.currentText()
        s_city = self.city_box.currentText()
        s_county = self.county_box.currentText()
        m_province = self.province_box2.currentText()
        m_city = self.city_box2.currentText()
        m_county = self.county_box2.currentText()

        if s_province == '请选择':
            self.issue_Error_hint('*没有选择起始位置')
            return
        elif m_province == '请选择':
            self.issue_Error_hint('*没有选择目的地')
            return
        elif not self.info1:
            self.issue_Error_hint('*没有选择要求车型')
            return
        elif not self.info12:
            self.issue_Error_hint('*没有选择货物类别')
            return
        elif not self.info13:
            self.issue_Error_hint('*没有选择货物性质')
            return
        elif not self.info14:
            self.issue_Error_hint('*没有选择要求保险')
            return
        elif not self.Edit_bulk.text():
            self.issue_Error_hint('*没有输入方量')
            return
        elif not self.weight.text():
            self.issue_Error_hint('*没有输入重量')
            return
        elif not self.Edit_total.text():
            self.issue_Error_hint('*没有输入总运费')
            return
        elif not self.text_describe.toPlainText():
            self.issue_Error_hint('*详细描述不能为空(没有请写无)')
            return
        elif self.combo.currentText() == '请选择':
            self.issue_Error_hint('*没有选择有效期')
            return
        for i in self.text_describe.toPlainText():
            if i in [' ', '#']:
                self.issue_Error_hint('*详细描述中不能有【空格】')
                return
            elif i in [' ', '#']:
                self.issue_Error_hint('*详细描述中不能有【#】')
                return

        data = 'UX ' + self.mess[0] + ' ' + s_province + '#' + s_city + '#' +\
            s_county + '#' + m_province + '#' + m_city + '#' + m_county\
             + '#' + self.info1 + '#' + self.info12 + '#' + self.info13\
             + '#' + self.info14 + '#' + self.Edit_bulk.text()\
             + '#' + self.weight.text() + '#' + self.Edit_total.text()\
             + '#' + self.Edit_phone.text() + '#' + \
            self.text_describe.toPlainText()
        if self.data == data:
            return self.issue_Error_hint('*不能发布重复信息')
        self.data = data
        data = data + '#' + self.period_of_validity()
        # 让这个变量为True
        self.timekey = True
        self.threadmess = MyThread(self.connfd, data)
        self.threadmess.messageSignal.connect(self.handle_return_message)
        self.threadmess.start()

    # 处理返回的情况处理
    def handle_return_message(self, mess):
        self.threadmess.deleteLater()
        if mess == 'UXNO NoData':
            self.issue_Error_hint('*修改失败')
        elif mess == 'UXOK ':
            self.issue_Error_hint('*修改成功')
        else:
            pass
        # 把按键检测变为False
        self.timekey = False

    def issue_Error_hint(self, show=' '):
        try:
            sip.delete(self.user_hint)
        except AttributeError:
            pass
        pe_red = QPalette()
        pe_red.setColor(QPalette.WindowText, Qt.red)
        self.user_hint = QLabel(show, self.centralwidget)
        self.user_hint.setPalette(pe_red)
        self.gridLayout.addWidget(self.user_hint, 0, 0, 1, 1)
        QApplication.processEvents()

    def rbclicked(self):
        sender = self.sender()
        if sender == self.bg1:
            if self.bg1.checkedId() == 0:
                self.info1 = self.l[0]
            elif self.bg1.checkedId() == 1:
                self.info1 = self.l[1]
            elif self.bg1.checkedId() == 2:
                self.info1 = self.l[2]
            elif self.bg1.checkedId() == 3:
                self.info1 = self.l[3]
            elif self.bg1.checkedId() == 4:
                self.info1 = self.l[4]
            else:
                self.info1 = ''
            self.issue_Error_hint()
        elif sender == self.bg12:
            if self.bg12.checkedId() == 10:
                self.info12 = self.l2[0]
            elif self.bg12.checkedId() == 11:
                self.info12 = self.l2[1]
            elif self.bg12.checkedId() == 12:
                self.info12 = self.l2[2]
            elif self.bg12.checkedId() == 13:
                self.info12 = self.l2[3]
            elif self.bg12.checkedId() == 14:
                self.info12 = self.l2[4]
            else:
                self.info12 = ''
            self.issue_Error_hint()
        elif sender == self.bg13:
            if self.bg13.checkedId() == 20:
                self.info13 = self.l3[0]
            elif self.bg13.checkedId() == 21:
                self.info13 = self.l3[1]
            elif self.bg13.checkedId() == 22:
                self.info13 = self.l3[2]
            elif self.bg13.checkedId() == 23:
                self.info13 = self.l3[3]
            else:
                self.info13 = ''
            self.issue_Error_hint()
        elif sender == self.bg14:
            if self.bg14.checkedId() == 30:
                self.info14 = self.l4[0]
            elif self.bg14.checkedId() == 31:
                self.info14 = self.l4[1]
            elif self.bg14.checkedId() == 32:
                self.info14 = self.l4[2]
            elif self.bg14.checkedId() == 33:
                self.info14 = self.l4[3]
            elif self.bg14.checkedId() == 34:
                self.info14 = self.l4[4]
            else:
                self.info14 = ''
            self.issue_Error_hint()

    def initSignal(self):
        # 初始化信号槽
        self.province_box.currentIndexChanged.connect\
                                (self.city_model.setFilter)
        self.city_box.currentIndexChanged.connect\
                                (self.county_model.setFilter)
        self.province_box2.currentIndexChanged.connect\
                                (self.city_model2.setFilter)
        self.city_box2.currentIndexChanged.connect\
                                (self.county_model2.setFilter)

    def initModel(self):
        # 初始化模型
        self.province_model = SortFilterProxyModel(self)
        self.city_model = SortFilterProxyModel(self)
        self.county_model = SortFilterProxyModel(self)
        # 设置模型
        self.province_box.setModel(self.province_model)
        self.city_box.setModel(self.city_model)
        self.county_box.setModel(self.county_model)

        # 初始化模型
        self.province_model2 = SortFilterProxyModel(self)
        self.city_model2 = SortFilterProxyModel(self)
        self.county_model2 = SortFilterProxyModel(self)
        # 设置模型
        self.province_box2.setModel(self.province_model2)
        self.city_box2.setModel(self.city_model2)
        self.county_box2.setModel(self.county_model2)

    def initData(self):
        # 初始化数据
        datas = open("UI/data.json", "rb").read()
        encoding = chardet.detect(datas) or {}
        datas = datas.decode(encoding.get("encoding", "utf-8"))
        datas = json.loads(datas)
        # 开始解析数据
        for data in datas:
            item_code = data.get("item_code")  # 编码
            item_name = data.get("item_name")  # 名字
            item = QStandardItem(item_name)
            item.setData(item_code, Qt.ToolTipRole)
            if item_code.endswith("0000"):  # 4个0结尾的是市级以上的
                self.province_model.appendRow(item)
            elif item_code.endswith("00"):  # 2个0结尾的是市
                self.city_model.appendRow(item)
            else:  # 市以下
                self.county_model.appendRow(item)

        # 开始解析数据
        for data in datas:
            item_code = data.get("item_code")  # 编码
            item_name = data.get("item_name")  # 名字
            item = QStandardItem(item_name)
            item.setData(item_code, Qt.ToolTipRole)
            if item_code.endswith("0000"):  # 4个0结尾的是市级以上的
                self.province_model2.appendRow(item)
            elif item_code.endswith("00"):  # 2个0结尾的是市
                self.city_model2.appendRow(item)
            else:  # 市以下
                self.county_model2.appendRow(item)

    def handle_size(self, left, top):
        screen = self.frameGeometry()  # 窗口显示位置
        wall = QDesktopWidget().availableGeometry().center()
        screen.moveCenter(wall)
        if left < 0:
            left = 0
        if top < 0:
            top = 0
        if left > screen.left() * 2:
            left = screen.left() * 2
        if top > screen.top() * 2:
            top = screen.top() * 2
        self.move(left, top)
        QApplication.processEvents()

    # 把隐藏的窗口显示出来
    def handle_click(self):
        if not self.isVisible():
            self.show()

    # 对ESC进行的重载  按ESC也有退出的功能
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.close()
            self.close_signal.emit()

    # 重写无边框拖动方法
    def mouseMoveEvent(self, e: QMouseEvent):
        try:
            self._endPos = e.pos() - self._startPos
            self.move(self.pos() + self._endPos)
        except TypeError:
            pass

    def mousePressEvent(self, e: QMouseEvent):
        if e.button() == Qt.LeftButton:
            self._isTracking = True
            self._startPos = QPoint(e.x(), e.y())

    def mouseReleaseEvent(self, e: QMouseEvent):
        if e.button() == Qt.LeftButton:
            self._isTracking = False
            self._startPos = None
            self._endPos = None
Ejemplo n.º 30
0
class MyWin(QMainWindow):
    def __init__(self, settings):
        super(MyWin, self).__init__()
        self.settings = settings
        self.is_processing = False
        self.initUi(settings)

    def initUi(self, settings):
        self.setWindowTitle("Pacoo")
        self.setWindowIcon(QIcon('logo.jpg'))
        if settings['window_height'] == "all":
            self.resize(580, 700)
        else:
            self.resize(580, 300)
        self.btn = QPushButton('识别公式', self)
        self.btn.setGeometry(40, 40, 200, 130)
        self.btn.setFont(QFont(QFont("FangSong", 20)))
        self.btn.clicked.connect(self.click_btn)
        # QShortcut(QKeySequence(self.tr("Shift+A")), self, self.click_btn) #快捷键

        label = QLabel(self)
        # label.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        label.setFont(QFont(QFont("FangSong", 20)))
        label.setGeometry(300, 40, 240, 40)
        label.setText("选择格式:")

        self.rb_word = QRadioButton("Word 2016+", self)
        self.rb_word.setFont(QFont(QFont("FangSong", 20)))
        self.rb_word.setGeometry(300, 90, 240, 40)
        self.rb_latex = QRadioButton("LaTex", self)
        self.rb_latex.setFont(QFont(QFont("FangSong", 20)))
        self.rb_latex.setGeometry(300, 130, 240, 40)
        if settings["result_format"] == "word":
            self.rb_word.setChecked(True)
        else:
            self.rb_latex.setChecked(True)

        line_label = QLabel(self)
        # line_label.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        line_label.setFont(QFont("FangSong", 20))
        line_label.setGeometry(40, 180, 200, 40)
        line_label.setText("剩余次数:")

        self.left_label = QLabel(self)
        # self.left_label.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.left_label.setGeometry(200, 180, 160, 40)
        self.left_label.setFont(QFont("Helvetica", 20, QFont.Bold))
        self.left_label.setText("???")

        self.dev_api_cb = QCheckBox("开发者账号", self)
        self.dev_api_cb.setGeometry(300, 180, 220, 40)
        self.dev_api_cb.setFont(QFont("FangSong", 20))
        if settings["use_dev_api"]:
            self.dev_api_cb.setChecked(True)

        lb0 = QLabel(self)
        lb0.setGeometry(40, 200, 500, 80)
        lb0.setFont(QFont('KaiTi', 9))
        lb0.setText("在公众号(Pacoo)回复“桌面版”,将获取的动态链接复制粘贴到下面:")
        self.link_le = QLineEdit(self)
        self.link_le.setGeometry(40, 250, 500, 40)
        self.link_le.setText(settings["link"])
        lb = QLabel(self)
        lb.setGeometry(40, 300, 500, 10)
        lb.setText(
            "----------------------------------------------------------------")

        self.account_le = QLineEdit(self)
        self.password_le = QLineEdit(self)
        account_label = QLabel(self)
        account_label.setGeometry(40, 320, 200, 40)
        account_label.setText("API_id:")
        account_label.setFont(QFont(QFont("FangSong", 16)))
        password_label = QLabel(self)
        password_label.setGeometry(40, 370, 200, 40)
        password_label.setText("API_key:")
        password_label.setFont(QFont(QFont("FangSong", 16)))
        self.account_le.setGeometry(170, 320, 370, 40)
        self.account_le.setText(settings["account"])
        self.password_le.setGeometry(170, 370, 370, 40)
        self.password_le.setText(settings["passwd"])

        bottom_info = QLabel(self)
        bottom_info.setGeometry(40, 400, 500, 80)
        bottom_info.setFont(QFont("KaiTi", 16))
        bottom_info.setText("遇到问题,联系客服。微信:pacoo1614")

        lb01 = QLabel(self)
        lb01.setGeometry(40, 470, 500, 40)
        lb01.setFont(QFont("KaiTi", 10))
        lb01.setText("* 感谢以以下参加内测版的同学 *")

        self.textBrowser_3 = QTextBrowser(self)
        self.textBrowser_3.setGeometry(40, 500, 500, 170)
        self.textBrowser_3.setHtml(
            "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
            "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
            "p, li { white-space: pre-wrap; }\n"
            "</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
            "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Avenir\'; font-size:14px; color:#606266; background-color:#ecf5ff;\">康婷    惘卿心    ꧁꫞꯭z꯭e꯭r꯭0꫞꧂    </span></p>\n"
            "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Avenir\'; font-size:14px; color:#606266; background-color:#ecf5ff;\">战神    海洋    LLLLLiang</span></p>\n"
            "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Avenir\'; font-size:14px; color:#606266; background-color:#ecf5ff;\">养一只猴子_陪我看夕阳    这个我不确定啊</span></p>\n"
            "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Avenir\'; font-size:14px; color:#606266; background-color:#ecf5ff;\">Sun    Erigeron    大舟</span></p>\n"
            "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Avenir\'; font-size:14px; color:#606266; background-color:#ecf5ff;\">淘气包马婷    🇼 🇭 🇭    刘心玉</span></p>\n"
            "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Avenir\'; font-size:14px; color:#606266; background-color:#ecf5ff;\">书华    </span><span style=\" font-family:\'Avenir\'; font-size:14px; color:#606266; background-color:#ffffff;\">葛江峡    </span><span style=\" font-family:\'Avenir\'; font-size:14px; color:#606266; background-color:#ecf5ff;\">好孩纸 kimi</span></p>\n"
            "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Avenir\'; font-size:14px; color:#606266; background-color:#ecf5ff;\">北凉    0.007    HG Deng</span></p>\n"
            "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Avenir\'; font-size:14px; color:#606266; background-color:#ecf5ff;\">嚼不断的浓痰</span></p></body></html>"
        )

    def set_process_status(self, status):
        self.is_processing = status

    def click_btn(self):
        print("is_processing", self.is_processing)
        if self.is_processing:
            op.play_sound("failed")
            QMessageBox.about(self, "Pacoo", "你有一个识别正在进行,请等待。")
            return None
        else:
            self.is_processing = True
        self.showMinimized()
        self.screenshot = ScreenShotsWin(self)

    def start_math_ocr(self):
        print("start_math_ocr")

    def start_math_ocr_wx(self):
        print("start_math_ocr_wx")

    def update_settings(self):
        '''
        保存设置
        :return:
        '''
        account = self.account_le.text()
        passwd = self.password_le.text()
        link = self.link_le.text()
        # print(account, passwd, link)
        if (account == "" or passwd == "") and (link == ""):
            self.settings['window_height'] = "all"
        else:
            self.settings['window_height'] = "half"
        self.settings['account'] = account
        self.settings['passwd'] = passwd
        self.settings['link'] = link
        self.settings['result_format'] = "word" if self.rb_word.isChecked(
        ) else "latex"
        self.settings['use_dev_api'] = True if self.dev_api_cb.isChecked(
        ) else False
        homeDir = os.path.expanduser("~")
        with open(homeDir + "\\pacoo.conf", "w") as f:
            json.dump(self.settings, f)

    def closeEvent(self, event):
        '''
        添加一个退出的提示事件,在退出时保存设置。
        :param event:
        :return:
        '''
        reply = QMessageBox.question(self, 'Message', "确定关闭程序?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        # 判断返回值,如果点击的是Yes按钮,我们就关闭组件和应用,否则就忽略关闭事件
        if reply == QMessageBox.Yes:
            event.accept()
            self.update_settings()
        else:
            event.ignore()