def main(): global app app = QApplication(sys.argv) global window2 global window3 global credits_window global prefs_window window = QMainWindow() window2 = QDialog() window3 = QDialog() credits_window = QDialog() prefs_window = QDialog() global ui global ui2 global ui3 global credits_ui global prefs_ui ui = MainUI() ui.setupUi(window) model = VideoTableModel(None, [], ["Video File Name", "Play Time", "Duration"]) ui.table_videos.setSelectionMode(QAbstractItemView.SingleSelection) ui.table_videos.setSelectionBehavior(QAbstractItemView.SelectRows) ui.table_videos.setModel(model) ui.table_videos.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) # ui.table_videos.clicked.connect(table_clicked) ui.table_videos.setContextMenuPolicy(Qt.CustomContextMenu) ui.table_videos.customContextMenuRequested.connect(table_right_clicked) ui.table_videos.doubleClicked.connect(table_double_clicked) ui.actionSettings.triggered.connect(prefs_window.show) ui2 = LoadVideoDialog() ui2.setupUi(window2) ui3 = NothingToInspectDialog() ui3.setupUi(window3) prefs_ui = prefs() prefs_ui.setupUi(prefs_window) bind() # ui.table_videos.setRowCount(0) # window.setWindowTitle("Video Scheduling Utility by KVK") window.show() open_vst() sys.exit(app.exec_())
class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.lstTags, QtCore.SIGNAL('currentItemChanged(QListWidgetItem*, QListWidgetItem*)'), self.update_filelist ) self.update_taglist() ##@QtCore.pyqtSignature("on_lstTags_clicked()") def update_filelist(self, item, previous): conn = connect( LOCALCACHE ) c = conn.cursor() tag = str(item.data(QtCore.Qt.UserRole).toString()) self.ui.lstFiles.clear() q = "SELECT file_name FROM file_tags WHERE tag=?" c.execute(q, [tag]) for row in c: item = QtGui.QListWidgetItem( "%s" % row[0], self.ui.lstFiles ) c.close() conn.close() def update_taglist(self, parent_tags=None): """ Update the list of tags in the UI. If parent_tags are specified only show tags that are attached to files also having all the parent tags """ conn = connect( LOCALCACHE ) self.ui.lstTags.clear() c = conn.cursor() if parent_tags: subselects = [ "SELECT file_name FROM file_tags WHERE tag=?" for x in parent_tags ] subq = " INTERSECT ".join( subselects ) q = "SELECT tag, COUNT(*) FROM file_tags WHERE file_name IN ("+subq+") GROUP BY tag ORDER BY COUNT(*) DESC" c.execute( q, parent_tags ) else: q = "SELECT tag, COUNT(*) FROM file_tags GROUP BY tag ORDER BY COUNT(*) DESC" c.execute( q ) for row in c: item = QtGui.QListWidgetItem( "%s (%d)" % row, self.ui.lstTags ) item.setData( QtCore.Qt.UserRole, QtCore.QVariant(row[0]) ) c.close()
class MainWindow(QtWidgets.QMainWindow): faItemChanged = pyqtSignal(FiniteAutomata) faImport = pyqtSignal(str) faSave = pyqtSignal(str) faTestWord = pyqtSignal(str) def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setTableItemFont() self.setupGrammarTable() def setTableItemFont(self): self.tableItemFont = QtGui.QFont() self.tableItemFont.setPointSize(18) self.tableItemFont.setWeight(50) def setupGrammarTable(self): self.ui.grammarTableWidget.setColumnCount(3) self.ui.grammarTableWidget.setRowCount(1) self.ui.grammarTableWidget.setHorizontalHeaderLabels(["α", "→", "ß"]) self.addArrowToRow(self.ui.grammarTableWidget.currentRow() + 1) def addRowToGrammarTable(self): itemAlpha = QtWidgets.QTableWidgetItem() itemBeta = QtWidgets.QTableWidgetItem() itemAlpha.setFont(self.tableItemFont) itemBeta.setFont(self.tableItemFont) row = self.ui.grammarTableWidget.rowCount() self.ui.grammarTableWidget.setRowCount(row + 1) self.ui.grammarTableWidget.setItem(row + 1, 0, itemAlpha) self.ui.grammarTableWidget.setItem(row + 1, 2, itemBeta) self.addArrowToRow(row) def addArrowToRow(self, row): arrowItem = QtWidgets.QTableWidgetItem(" →") arrowItem.setFlags(QtCore.Qt.NoItemFlags) arrowItem.setFlags(QtCore.Qt.ItemIsEnabled) arrowItem.setFont(self.tableItemFont) self.ui.grammarTableWidget.setItem(row, 1, arrowItem) def addGrammarToListBox(self, g): self.ui.grammarsWidgetList.addItem(QtWidgets.QListWidgetItem(g.name)) def clearGrammarFields(self): self.ui.initial_prod_textEdit.setText("") self.ui.symbols_textEdit.setText("") self.ui.terminals_textEdit.setText("") self.ui.grammar_name_textEdit.setText("") self.ui.grammarTableWidget.setRowCount(0) self.setupGrammarTable() def clearRegExField(self): self.ui.regExTextEdit.setText("") def add_listener(self, presenter): # Automatas self.ui.btn_create_fa.clicked.connect(self.onCreateFAClicked) self.ui.btn_import_fa.clicked.connect(self.onImportFAClicked) self.ui.btn_save_fa.clicked.connect(self.onSaveFAClicked) self.ui.btn_determinize_fa.clicked.connect(presenter.on_determinize_fa) self.ui.btn_minimize_fa.clicked.connect(presenter.on_minimize_fa) self.ui.btn_test_word.clicked.connect(self.on_test_word_clicked) self.faImport.connect(presenter.onImportFA) self.faSave.connect(presenter.on_save_fa) self.faItemChanged.connect(presenter.on_fa_item_changed) self.ui.convertFAtoRGBtn.clicked.connect( presenter.onConvertFAtoRGBtnClicked) self.ui.tableWidget.itemSelectionChanged.connect( self.on_fa_item_selected) self.ui.tableWidget.itemChanged.connect(self.on_fa_item_changed) # Grammars self.ui.btn_add_prod.clicked.connect(presenter.onAddProdClicked) self.ui.removeProductionBtn.clicked.connect( presenter.onRemoveProductionClicked) self.ui.btn_create_grammar.clicked.connect( presenter.onCreateGrammarClicked) self.ui.btn_remove_grammar.clicked.connect( presenter.on_remove_grammar_clicked) self.ui.exportGrammarBtn.clicked.connect( presenter.onExportGrammarBtnClicked) self.ui.importGrammarBtn.clicked.connect( presenter.onImportGrammarBtnClicked) self.ui.grammarToFABtn.clicked.connect( presenter.onGrammarToFABtnClicked) # Regular Expression self.ui.exportRegExBtn.clicked.connect( presenter.onExportRegExBtnClicked) self.ui.importRegExBtn.clicked.connect( presenter.onImportRegExBtnClicked) self.faTestWord.connect(presenter.on_test_word) def onCreateFAClicked(self): num_states, ok = QtWidgets.QInputDialog.getInt(self, "States", "Number of states:", 4, 1, 20, 1) if not ok: return num_sigma, okSigma = QtWidgets.QInputDialog.getInt( self, "Sigma", "Number of symbols:", 2, 1, 20, 1) if not okSigma: return sigma = [chr(i) for i in range(97, 97 + num_sigma)] table = {} for i in range(num_states): table['q' + str(i)] = {x: '-' for x in sigma} initial = 'q0' accepting = ['q' + str(num_states - 1)] self.current_fa = FiniteAutomata(sigma, table, initial, accepting) self.faItemChanged.emit(self.current_fa) def onImportFAClicked(self): path, _ = QtWidgets.QFileDialog.getOpenFileName(self) if path: self.faImport.emit(path) def onSaveFAClicked(self): if not self.current_fa: print("Error: No FA active") return path, _ = QtWidgets.QFileDialog.getSaveFileName(self) if path: self.faSave.emit(path) def showFA(self, fa: FiniteAutomata): self.ui.tableWidget.blockSignals(True) self.ui.tableWidget.clear() self.current_fa = fa sigma = {} for i, s in enumerate(sorted(fa.sigma), 1): sigma[i] = s states_label = {} for s in fa.states(): label = s if (s in fa.accepting): label = '* ' + label if (s == fa.initial): label = '> ' + label states_label[s] = label # +2 para headers e adição de novos simbolos/estados cols = len(sigma) + 2 rows = len(states_label) + 2 self.ui.tableWidget.setColumnCount(cols) self.ui.tableWidget.setRowCount(rows) for i, state in enumerate(fa.states(), 1): self.ui.tableWidget.setItem( i, 0, QtWidgets.QTableWidgetItem(states_label[state])) for j, symbol in sigma.items(): self.ui.tableWidget.setItem(0, j, QtWidgets.QTableWidgetItem(symbol)) if symbol in fa.table[state]: self.ui.tableWidget.setItem( i, j, QtWidgets.QTableWidgetItem( fa.transition_to_text(fa.table[state][symbol]))) item = QtWidgets.QTableWidgetItem('') item.setFlags(remove_flag(item.flags(), Qt.ItemIsEnabled)) self.ui.tableWidget.setItem(0, 0, item) item = QtWidgets.QTableWidgetItem('New Symbol') self.ui.tableWidget.setItem(0, cols - 1, item) item = QtWidgets.QTableWidgetItem('New State') self.ui.tableWidget.setItem(rows - 1, 0, item) for i in range(1, rows): item = QtWidgets.QTableWidgetItem('') item.setFlags(remove_flag(item.flags(), Qt.ItemIsEnabled)) self.ui.tableWidget.setItem(i, cols - 1, item) for j in range(1, cols): item = QtWidgets.QTableWidgetItem('') item.setFlags(remove_flag(item.flags(), Qt.ItemIsEnabled)) self.ui.tableWidget.setItem(rows - 1, j, item) self.ui.tableWidget.resizeColumnsToContents() self.ui.tableWidget.blockSignals(False) def showGrammar(self, g): self.ui.initial_prod_textEdit.setText(g.root) self.ui.symbols_textEdit.setText(",".join(list(g.symbols))) self.ui.terminals_textEdit.setText(",".join(list(g.sigma))) self.ui.grammar_name_textEdit.setText(g.name) self._showProductions(g.productions) def grammarToFA(): ... def showRegEx(self, re): self.ui.regExTextEdit.setText(str(re)) def _showProductions(self, productions): tableWidget = self.ui.grammarTableWidget tableWidget.setRowCount(0) row = 0 for p in productions: # b = ["a", "B"] -> b = "aB" joinedBetas = list(map(lambda b: "".join(b), p[1])) alpha, betas = p[0], "|".join(joinedBetas) # betas = b1|b2 alphaItem = QtWidgets.QTableWidgetItem(alpha) betasItem = QtWidgets.QTableWidgetItem(betas) self.addRowToGrammarTable() tableWidget.setItem(row, 0, alphaItem) tableWidget.setItem(row, 2, betasItem) row += 1 def column_to_symbol(self, column): return self.ui.tableWidget.item(0, column).text() def row_to_state(self, row): return self.ui.tableWidget.item(row, 0).text() def on_fa_item_selected(self): selected = self.ui.tableWidget.selectedItems() if selected: item = selected[0] self.fa_selected_item = item.text() def on_fa_item_changed(self, item): if item.row() == 0: # add or update sigma symbol symbol = item.text() if item.column() > len(self.current_fa.sigma): self.fa_selected_item = '' self.current_fa.update_sigma(self.fa_selected_item, symbol) elif item.column() == 0: # add or update state st = self.state_from_label(item.text()) if item.row() > len(self.current_fa.states()): self.fa_selected_item = '' self.current_fa.update_state( self.state_from_label(self.fa_selected_item), st) if '*' in item.text(): if st not in self.current_fa.accepting: self.current_fa.accepting.append(st) else: if st in self.current_fa.accepting: self.current_fa.accepting.remove(st) if '>' in item.text(): self.current_fa.initial = st else: # add or update transition tr = item.text() st = self.state_from_label(self.row_to_state(item.row())) symbol = self.column_to_symbol(item.column()) if tr == '': tr = '-' self.current_fa.table[st][ symbol] = self.current_fa.text_to_transition(tr) self.ui.tableWidget.resizeColumnsToContents() self.faItemChanged.emit(self.current_fa) def state_from_label(self, label: str): return label.replace('>', '').replace('*', '').strip() def on_view_fa_clicked(self): from subprocess import call from PyQt5 import QtGui dialog = QtWidgets.QDialog() fa_ui = Ui_Dialog() fa_ui.setupUi(dialog) name = self.current_fa.name call(['/usr/bin/dot', '-Tpng', f'{name}.gv', '-o', f'{name}.png']) pixmap = QtGui.QPixmap(f'{name}.png') fa_ui.label.setPixmap(pixmap) fa_ui.label.setFixedSize(pixmap.size()) fa_ui.label.show() dialog.exec_() def on_test_word_clicked(self): text = self.ui.edittext_test_word.text() self.faTestWord.emit(text) def show_test_word_msg(self, result): msgBox = QtWidgets.QMessageBox() msgBox.setWindowTitle('Sentence Recognition') msgBox.setFixedWidth(400) msgBox.setText(f'Sentence is {result}.') msgBox.exec_()
class MainWindow(QMainWindow): def __init__(self, db_path) -> None: super(MainWindow, self).__init__() self.db_path = db_path self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.action_exit.triggered.connect(self.close) self.ui.action_open_dir.triggered.connect(self.open_dir) self.ui.action_login.triggered.connect(self.login) self.ui.action_logout.triggered.connect(self.logout) self.ui.action_add_user.triggered.connect(self.add_user) self.ui.action_delete_user.triggered.connect(self.delete_user) self.ui.action_add_contractor.triggered.connect(self.add_contractor) self.refresh_actions() self.show() def refresh_actions(self) -> None: self.ui.action_login.setEnabled(not ctx.logged_in) self.ui.action_logout.setEnabled(ctx.logged_in) self.ui.action_add_user.setEnabled(ctx.admin) self.ui.action_delete_user.setEnabled(ctx.admin) self.ui.action_add_contractor.setEnabled(ctx.admin) self.ui.action_edit_contractor.setEnabled(ctx.admin) def main_window(self) -> None: self.setCentralWidget(MainWidget(self)) def open_dir(self) -> None: if os.name == "nt": cmd = f'explorer /select,"{self.db_path}"' subprocess.Popen(cmd) def add_user(self, first_time=False) -> None: if not ctx.admin and not first_time: return w = AddUser(self) if first_time: w.ui.combo_type.setDisabled(True) w.ui.combo_type.setCurrentIndex(1) w.ui.label_title.setText("Dodaj administratora") if ctx.logged_in: w.finished.connect(self.logged_in) elif not first_time: w.finished.connect(self.login) elif first_time: def slot(success: bool) -> None: if success: self.login() else: self.close() w.finished.connect(slot) w.ui.input_login.setFocus() self.setCentralWidget(w) def add_contractor(self) -> None: if not ctx.admin: return w = AddContractor(self) w.finished.connect(self.main_window) w.ui.input_first_name.setFocus() self.setCentralWidget(w) def delete_user(self) -> None: if not ctx.admin: return w = DeleteUser(self) w.ui.combo_users.setFocus() self.setCentralWidget(w) def login(self) -> None: if ctx.logged_in: return w = Login(self) w.finished.connect(self.logged_in) w.ui.input_login.setFocus() self.setCentralWidget(w) def logged_in(self) -> None: if not ctx.logged_in: return self.setWindowTitle("Bagel - " + ctx.login + " (Administrator)" if ctx.admin else "") self.refresh_actions() self.main_window() def logout(self, ask=True) -> None: if not ctx.login: return if ask: answer = QMessageBox.question( self, "Potwierdzenie wylogowania", "Czy na pewno chcesz się wylogować?") if answer == QMessageBox.No: return ctx.logged_in = False ctx.login = "" ctx.admin = False self.setWindowTitle("Bagel") self.refresh_actions() self.login()
class MyApplication(QtGui.QMainWindow): format_selected = 35 def __init__(self, parent=None): """Initializes""" QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.comboBoxFormats.activated[str].connect(self.combo_formats) self.ui.btnDownload.clicked.connect(self.download_button_pressed) def download_button_pressed(self): if self.ui.textEditDownload is not None: if self.check_url(self.ui.textEditDownload.toPlainText()): #subprocess.Popen(self.return_youtube_dl_cmd()) system(self.return_youtube_dl_cmd()) else: msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Critical) msgBox.setText("Error in URL") msgBox.setInformativeText("Please check the URL you provided.") msgBox.setStandardButtons(QMessageBox.Ok) msgBox.exec_() def check_url(self, url_tobe_checked): """ @param url_tobe_checked: @return: """ try: code = urlopen(url_tobe_checked).code except ValueError: return False except HTTPError: return False if (code / 100) >= 4: return False else: return True def return_youtube_dl_cmd(self): from os.path import expanduser home = expanduser("~") cmd = "gnome-terminal -e " cmd += '"youtube-dl -f{0} -c -o {1}/Downloads/%(title)s-%(id)s.%(ext)s {2}"'.format( self.format_selected, home, self.ui.textEditDownload.toPlainText() ) return cmd def combo_formats(self, text): """ checks the selected option @param text: the selected option's text """ if text == 'H264 MP4 1080p': self.format_selected = 37 if text == 'H264 MP4 720p': self.format_selected = 22 if text == 'WebM 720p': self.format_selected = 45 if text == 'WebM 480p': self.format_selected = 43 if text == 'H264 MP4 480p': self.format_selected = 18 if text == 'H264 FLV 480p': self.format_selected = 35 if text == 'H264 FLV 360p': self.format_selected = 34 if text == 'H263 240p': self.format_selected = 5 if text == '3GP video': self.format_selected = 17
class MainWindow(QtWidgets.QMainWindow): global msg_in global msg_out global aux_in global aux_out def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btn_list_usb.setText('List USB') self.ui.btn_list_usb.clicked.connect(self.list_usb) self.ui.btn_find_usb.setText('Find USB') self.ui.btn_find_usb.clicked.connect(self.find_specific_device) def list_usb(self): try: dev = usb.core.find(find_all=True) list_usb = list(dev) print("%s libusb device(s) found..." % len(list_usb)) for cfg in list_usb: print( '-------------------------------------------------------------------------------------' ) print('VendorID={}(0x{:04X}) & ProductID={}(0x{:04X})'.format( str(cfg.idVendor), cfg.idVendor, str(cfg.idProduct), cfg.idProduct)) except Exception as e: print(e) def find_specific_device(self): backend = usb.backend.libusb1.get_backend( find_library=lambda x: "C:\Windows\System32\libusb0.dll") print("backend: %s" % backend) # find our device dev = usb.core.find(idVendor=0x3231, idProduct=0x0100, backend=backend) # was it found? if dev is None: # raise ValueError('Device not found') QMessageBox.information(self, "Warning", "USB Device not found", QMessageBox.Close) # set the active configuration. With no arguments, the first # configuration will be the active one dev.set_configuration() # get an endpoint instance cfg = dev.get_active_configuration() intf = cfg[(0, 0)] # region [ENDPOINTS] msg_in = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_address( e.bEndpointAddress) == ENDPOINT_ADDRESS_MSG_IN) if msg_in is None: print('get USB ENDPOINT #1 msg_in fail !') else: print("\t[msg_in]\n%s" % msg_in) msg_out = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_address( e.bEndpointAddress) == ENDPOINT_ADDRESS_MSG_OUT) if msg_out is None: print('get USB ENDPOINT #2 msg_out fail !') else: print("\t[msg_out]\n%s" % msg_out) aux_in = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_address( e.bEndpointAddress) == ENDPOINT_ADDRESS_AUX_IN) if aux_in is None: print('get USB ENDPOINT #3 aux_in fail !') else: print("\t[aux_in]\n%s" % aux_in) aux_out = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_address( e.bEndpointAddress) == ENDPOINT_ADDRESS_AUX_OUT) if aux_out is None: print('get USB ENDPOINT #4 aux_out fail !') else: print("\t[aux_out]\n%s" % aux_out)
class Main(QtWidgets.QMainWindow): def __init__(self): super(Main, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # Init Canvas self.label_Canvas = Canvas(self.ui.frame_Canvas.geometry(), self.ui.centralwidget) # Init model and dataset self.model = build_model() self.ds_trn, self.ds_test = init_dataset() # Signals & Slots self.ui.pushButton_TrainReset.clicked.connect(self.reset_model) self.ui.pushButton_TrainStart.clicked.connect(self.start_train) self.ui.pushButton_ClearCanvas.clicked.connect(self.clear_canvas) self.ui.pushButton_Predict.clicked.connect(self.predict_canvas) self.ui.textBrowser_Console.textChanged.connect(self.refresh_console) @QtCore.pyqtSlot() def refresh_console(self): self.ui.textBrowser_Console.moveCursor(QtGui.QTextCursor.End, QtGui.QTextCursor.MoveAnchor) self.ui.textBrowser_Console.update() @QtCore.pyqtSlot() def predict_canvas(self): qim = self.label_Canvas.pixmap().toImage() qim = qim.convertToFormat(QtGui.QImage.Format_Grayscale8) ba = QtCore.QByteArray() buffer = QtCore.QBuffer(ba) buffer.open(QtCore.QIODevice.WriteOnly) qim.save(buffer, "PNG") buffer.close() tim = tf.image.decode_png(ba.data(), dtype=tf.uint8) tim = tf.cast(tim, tf.float32) / 255. tim = tf.ones_like(tim, dtype=tf.float32) - tim tim = tf.image.resize(tim, (28, 28)) pred = self.model.predict(tim[tf.newaxis, ...]) for i, v in enumerate(pred[0]): item = QtWidgets.QTableWidgetItem() item.setText(f'{v:.4f}') self.ui.tableWidget_PredPosibiity.setItem(0, i, item) @QtCore.pyqtSlot() def clear_canvas(self): self.label_Canvas.pixmap().fill(QtGui.QColor('#FFFFFF')) self.label_Canvas.update() @QtCore.pyqtSlot() def reset_model(self): tf.compat.v1.reset_default_graph() self.model = build_model() self.ds_trn, self.ds_test = init_dataset() @QtCore.pyqtSlot() def start_train(self): ds_trn = ( self.ds_trn.shuffle(10000).map(lambda x, y: data_augmentation( x, y, self.ui.checkBox_RandomBrightness.isChecked(), self.ui.checkBox_RandomContrast.isChecked(), self.ui.checkBox_RandomCrop.isChecked(), self.ui.checkBox_RandomShift.isChecked())).batch(128)) ds_test = self.ds_test.map(convert_dtype).batch(128) compile_model(self.model, self.ui.doubleSpinBox_LearningRate.value(), self.ui.comboBox_Optimizers.currentText().lower()) callbacks = [ tf.keras.callbacks.LambdaCallback( on_epoch_end=lambda epoch, logs: self.ui.textBrowser_Console. append(f"Epoch: {epoch+1}, logs: {logs}")) ] if self.ui.checkBox_EarlyStopping.isChecked(): callbacks.append( tf.keras.callbacks.EarlyStopping(patience=3, restore_best_weights=True)) thread = ModelThread(self.model, ds_trn, ds_test, self.ui.spinBox_Epochs.value(), callbacks, self) thread.setPriority(QtCore.QThread.LowPriority) thread.started.connect(self.toggle_buttons) thread.finished.connect(self.toggle_buttons) thread.start() @QtCore.pyqtSlot() def toggle_buttons(self): if self.sender().isRunning(): self.ui.pushButton_TrainReset.setEnabled(False) self.ui.pushButton_TrainStart.setEnabled(False) self.ui.pushButton_Predict.setEnabled(False) self.ui.textBrowser_Console.append("Start training.") elif self.sender().isFinished(): self.ui.pushButton_TrainReset.setEnabled(True) self.ui.pushButton_TrainStart.setEnabled(True) self.ui.pushButton_Predict.setEnabled(True) self.ui.textBrowser_Console.append("Finished training.")
class Main(QtWidgets.QMainWindow): def __init__(self): super(Main, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # Init Model and variables for training self.model = build_model() self.opt = tf.optimizers.Adam(learning_rate=0.02, beta_1=0.99, epsilon=1e-1) self.content_target = None self.style_target = None self.content_image_tensor = None self.model.trainable = False # Init Training timer self.apply_grad_timer = QtCore.QTimer() self.apply_grad_timer.setInterval( int(1000 / self.ui.spinBox_ExpectedFPS.value())) self.apply_grad_timer.timeout.connect(self.on_train_timer_timeout) # Init CV Camera self.camera = cv2.VideoCapture(0) self.camera_capture = None # Init Camera timer self.camera_timer = QtCore.QTimer() self.camera_timer.setInterval(int(1000 / 30)) self.camera_timer.timeout.connect(self.on_camera_timer_timeout) # Signals & Slots self.ui.spinBox_ExpectedFPS.valueChanged.connect(self.change_fps) self.ui.pushButton_ImportContentPicFile.clicked.connect( self.get_image_file) self.ui.pushButton_ImportStylePicFile.clicked.connect( self.get_image_file) self.ui.pushButton_TrainModel.clicked.connect(self.toggle_train) self.ui.pushButton_TrainTerminate.clicked.connect(self.toggle_train) self.ui.pushButton_CameraOpen.clicked.connect(self.toggle_camera) self.ui.pushButton_CameraCapture.clicked.connect(self.toggle_camera) self.ui.pushButton_DownloadResultPic.clicked.connect( self.download_result) self.ui.pushButton_Reset.clicked.connect(self.reset_model_clicked) def reset_model(self): tf.compat.v1.reset_default_graph() self.model = build_model() self.opt = tf.optimizers.Adam(learning_rate=0.02, beta_1=0.99, epsilon=1e-1) self.content_target = None self.style_target = None self.content_image_tensor = None self.model.trainable = False @QtCore.pyqtSlot() def reset_model_clicked(self): self.reset_model() self.ui.pushButton_DownloadResultPic.setEnabled(False) self.ui.pushButton_ImportContentPicFile.setEnabled(True) self.ui.pushButton_CameraOpen.setEnabled(True) self.ui.pushButton_ImportStylePicFile.setEnabled(True) self.ui.label_ResultPic.clear() self.ui.label_ContentPic.clear() self.ui.label_StylePic.clear() self.ui.plainTextEdit_Console.appendPlainText("All reset.") @QtCore.pyqtSlot() def download_result(self): file_name, _ = QtWidgets.QFileDialog.getSaveFileName( self, 'Save File', '.', 'Images (*.png)') if file_name: self.ui.label_ResultPic.pixmap().save(file_name, 'PNG') @QtCore.pyqtSlot() def toggle_camera(self): if self.sender() is self.ui.pushButton_CameraOpen: self.camera_timer.start() self.sender().setEnabled(False) self.ui.pushButton_CameraCapture.setEnabled(True) self.ui.pushButton_ImportContentPicFile.setEnabled(False) elif self.sender() is self.ui.pushButton_CameraCapture: self.camera_timer.stop() self.sender().setEnabled(False) self.ui.pushButton_CameraOpen.setEnabled(True) self.ui.pushButton_ImportContentPicFile.setEnabled(True) # Reset camera self.camera.release() self.camera = cv2.VideoCapture(0) # Assign variables for training self.content_image_tensor = tf.Variable( self.camera_capture[np.newaxis, :, :, ::-1] / 255.) self.content_target = self.model( self.camera_capture[np.newaxis, :, :, ::-1] / 255.)['content'] self.camera_capture = None @QtCore.pyqtSlot() def on_camera_timer_timeout(self): ret, frame = self.camera.read() if ret: ratio = get_img_ratio(frame) frame = cv2.resize(frame, (0, 0), fx=ratio, fy=ratio) self.camera_capture = frame[..., ::-1].copy() qim = array_uint8_to_qimage(frame, bgr=True) self.ui.label_ContentPic.setPixmap(QtGui.QPixmap.fromImage(qim)) else: self.ui.plainTextEdit_Console.appendPlainText( "Camera capture failed.") self.camera_timer.stop() self.ui.pushButton_CameraOpen.setEnabled(True) self.ui.pushButton_CameraCapture.setEnabled(False) self.ui.pushButton_ImportContentPicFile.setEnabled(True) @QtCore.pyqtSlot() def toggle_train(self): if self.sender() is self.ui.pushButton_TrainModel: self.apply_grad_timer.start() self.ui.pushButton_TrainTerminate.setEnabled(True) self.ui.pushButton_ImportContentPicFile.setEnabled(False) self.ui.pushButton_CameraOpen.setEnabled(False) self.ui.pushButton_ImportStylePicFile.setEnabled(False) self.ui.pushButton_Reset.setEnabled(False) self.sender().setEnabled(False) elif self.sender() is self.ui.pushButton_TrainTerminate: self.apply_grad_timer.stop() self.ui.pushButton_TrainModel.setEnabled(True) self.ui.pushButton_Reset.setEnabled(True) self.sender().setEnabled(False) @staticmethod def train_step(content_img_tensor, style_target, content_target, model, opt): with tf.GradientTape() as tape: outputs = model(content_img_tensor) loss = style_content_loss(outputs, style_target, content_target) grad = tape.gradient(loss, content_img_tensor) opt.apply_gradients([(grad, content_img_tensor)]) content_img_tensor.assign(clip_0_1(content_img_tensor)) @QtCore.pyqtSlot() def on_train_timer_timeout(self): condition = [ self.content_image_tensor is not None, self.style_target is not None, self.content_target is not None ] if all(condition): self.train_step(self.content_image_tensor, self.style_target, self.content_target, self.model, self.opt) result_image_array = tensor_to_array(self.content_image_tensor)[0] qim = array_uint8_to_qimage(result_image_array) self.ui.label_ResultPic.setPixmap(QtGui.QPixmap.fromImage(qim)) self.ui.pushButton_DownloadResultPic.setEnabled(True) else: self.ui.plainTextEdit_Console.appendPlainText( f"Has style image: {condition[1]}, " f"has content image: {condition[2]}.") self.apply_grad_timer.stop() @QtCore.pyqtSlot() def get_image_file(self): file_name, _ = QtWidgets.QFileDialog.getOpenFileName( self, 'Open File', '.', "Images (*.png *.jpg)") if file_name: img: Image.Image = Image.open(file_name) ratio = get_img_ratio(img) img = img.resize((int(img.width * ratio), int(img.height * ratio))) img = np.asarray(img) qimg = array_uint8_to_qimage(img, bgr=False) if self.sender() is self.ui.pushButton_ImportContentPicFile: self.ui.label_ContentPic.setPixmap( QtGui.QPixmap.fromImage(qimg)) self.content_image_tensor = tf.Variable( img[np.newaxis, :, :, :] / 255.) self.content_target = self.model(img[np.newaxis, :, :, :] / 255.)['content'] self.ui.plainTextEdit_Console.appendPlainText( f"Loaded Content Pic " f"from {file_name}") elif self.sender() is self.ui.pushButton_ImportStylePicFile: self.ui.label_StylePic.setPixmap(QtGui.QPixmap.fromImage(qimg)) self.style_target = self.model(img[np.newaxis, :, :, :] / 255.)['style'] self.ui.plainTextEdit_Console.appendPlainText( f"Loaded Style Pic " f"from {file_name}") @QtCore.pyqtSlot() def change_fps(self): self.apply_grad_timer.setInterval( int(1000 / self.ui.spinBox_ExpectedFPS.value())) self.ui.plainTextEdit_Console.appendPlainText( f"Expect FPS changed to {self.ui.spinBox_ExpectedFPS.value()}.")
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # init ui self.ui = Ui_MainWindow() self.ui.setupUi(self) # init comboBox self.coal_sorts = [] self.init_coal_sorts_from_db() self.ticket_sorts = [] self.init_ticket_sorts_from_db() # init param table # self.excelOps = ExcelOps() # self.excelOps.generate_param_table() # init input self.select_date = None self.beginDate = None self.endDate = None self.price = None self.coal_sorts_selected = None def test_cursor_1(self): print("!!!!!!!!!!!!!!!!!!!!11") def refresh_coal_sorts_combox(self): self.ui.coal_sorts.clear() self.ui.coal_sorts.addItems(self.coal_sorts) def init_coal_sorts_from_db(self): self.ui.coal_sorts.clear() utils = SqlUtils() try: coal_list = utils.query_all_coal_names() except: logging.warning("there is no coal in db") coal_list = [] for coal in coal_list: self.coal_sorts.append(coal[0]) self.ui.coal_sorts.addItems(self.coal_sorts) def refresh_ticket_sorts_combox(self): self.ui.ticket_sorts.clear() self.ui.ticket_sorts.addItems(self.ticket_sorts) def init_ticket_sorts_from_db(self): self.ui.ticket_sorts.clear() utils = SqlUtils() try: ticket_list = utils.query_all_tickets_name() except: logging.warning("there is no ticket sort in db") ticket_list = [] for ticket in ticket_list: self.ticket_sorts.append(ticket[0]) self.ui.ticket_sorts.addItems(self.ticket_sorts) def onCoalSortSelected(self, item): # 获得条目 coalSorts = self.coal_sorts[item] self.coal_sorts_selected = coalSorts def on_ticket_selected(self, item): ticket_name = self.ticket_sorts[item] self.ticket_selected = ticket_name # 添加记录“逐车明细” def on_record_add(self): logging.info("ready to add record to db") # 校验输入是否完整 # 数据库存一份,excel 存一份 SqlUtils().add_record_by_car_detail(self.select_date, self.person_name, self.car_id, self.coal_sorts_selected, self.weight_value, self.ticket_selected) QMessageBox.information(self, 'add finished', '添加成功!', QMessageBox.Yes) def on_date_selected(self): calendarDialog = CalendarDialog() calendarDialog.show() if calendarDialog.exec_(): date = calendarDialog.date_time print("value get from calendar window is:" + date.strftime('%Y/%m/%d')) self.ui.date_value_content.setText(date.strftime('%Y/%m/%d')) self.select_date = date.strftime('%Y/%m/%d') calendarDialog.destroy() def on_name_input(self): print("input name is", self.ui.usernmae_content.text()) self.person_name = self.ui.usernmae_content.text() def on_input_car_id(self): print("input car id is", self.ui.car_id_content.text()) self.car_id = self.ui.car_id_content.text() def on_weight_value_input(self): print("input weight value is", self.ui.weight_value.text()) self.weight_value = self.ui.weight_value.text() def exit(self): sys.exit(0) # menu actions below def on_compute_account(self): accountDialog = AccountDialog() accountDialog.show() accountDialog.exec_() def invokeHelp(self): QMessageBox.information(self, 'invoke help', '帮助内容', QMessageBox.Yes) def on_add_new_ticket(self): ticketDialog = TicketDialog() ticketDialog.set_main_window_handler(self) ticketDialog.show() ticketDialog.exec_() def on_add_new_coal(self): coalDialog = CoalDialog() coalDialog.set_main_window_handler(self) coalDialog.show() coalDialog.exec_() def exportTable(self, beginDate, endDate, price): # 导出每一次添加 with open('添加备份.txt', 'a') as file: addtime = time.strftime('%Y-%m-%d-%H:%M', time.localtime(time.time())) content = str(self.beginDate) + '~' + str( self.endDate) + ',' + self.coal_sorts_selected + ',' + self.price + '\n' file.write(str(addtime) + '添加了:' + content)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent: QObject = None): super().__init__(parent=parent) self.is_maximize = False self.drag_pos = 0 self.aug_list_model = AugModel() self.init_ui() self.connect() self.main_ui.aug_list_view.setModel(self.aug_list_model) def init_ui(self): self.main_ui = Ui_MainWindow() self.main_ui.setupUi(self) self.setting_widget = SettingWidget() self.resize(MainWindowConfig.width, MainWindowConfig.height) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) def move_window(event: QEvent): if event.buttons() == QtCore.Qt.LeftButton: self.move(self.pos() + event.globalPos() - self.drag_pos) self.drag_pos = event.globalPos() event.accept() self.main_ui.title_frame.mouseMoveEvent = move_window pix = QPixmap(MainWindowConfig.Img.input_label_path) self.main_ui.label_input_img.org_pix = pix self.main_ui.label_input_img.setPixmap(pix) self.main_ui.label_input_img.installEventFilter( DragDropImgWatcher(parent=self.main_ui.label_input_img)) set_button_icon( self, self.main_ui.btn_edit, MainWindowConfig.Img.l_edit_icon_path, MainWindowConfig.Img.h_edit_icon_path, ) set_button_icon( self, self.main_ui.btn_aug_add, MainWindowConfig.Img.l_plus_icon_path, MainWindowConfig.Img.h_plus_icon_path, ) set_button_icon( self, self.main_ui.btn_aug_minus, MainWindowConfig.Img.l_minus_icon_path, MainWindowConfig.Img.h_minus_icon_path, ) set_button_icon( self, self.main_ui.btn_aug_run, MainWindowConfig.Img.l_run_icon_path, MainWindowConfig.Img.h_run_icon_path, ) def connect(self): self.main_ui.btn_minimize.clicked.connect(lambda: self.showMinimized()) self.main_ui.btn_maximize.clicked.connect( lambda: self.maximize_restore()) self.main_ui.btn_close.clicked.connect(lambda: self.close()) self.main_ui.btn_aug_add.clicked.connect( lambda: self.setting_widget.show()) self.main_ui.btn_aug_minus.clicked.connect( lambda: self.aug_list_model.removeRows( self.main_ui.aug_list_view.currentIndex().row(), 1, self.main_ui.aug_list_view.currentIndex(), )) def maximize_restore(self): if self.is_maximize: self.showNormal() self.is_maximize = False else: self.showMaximized() self.is_maximize = True def mousePressEvent(self, event: QEvent): self.drag_pos = event.globalPos()
class MainWindow(Logger, QtGui.QMainWindow): progress = 0 BUTTONS = ["searchButton", "refreshButton", "saveButton", "cancelButton", "nextButton", "sortButton", "prevButton", "pageBox"] def __init__(self, app): super(MainWindow, self).__init__() self.app = app self.button_lock = False self.ui = Ui_MainWindow() self.ui.setupUi(self) # TODO Move this shit into the ui setup method for button in self.BUTTONS: button = getattr(self.ui, button) button.locks = {} self.ui.flowLayout = FlowLayout(self.ui.scrollAreaWidgetContents) self.ui.searchButton.clicked.connect(self.search) self.ui.refreshButton.clicked.connect(self.refresh_button_handler) self.ui.saveButton.clicked.connect(self.app.update_config) self.ui.cancelButton.clicked.connect(self.app.load_config) self.ui.nextButton.clicked.connect(self.next_page) self.ui.prevButton.clicked.connect(self.prev_page) self.ui.directories.clicked.connect(self.browse) self.ui.sortButton.clicked.connect(self.app.sort) self.ui.searchButton.setText("") self.ui.searchButton.setIcon(qta.icon("fa.search", color="#F1F1F1", scale_factor=.9)) self.ui.nextButton.setText("") self.ui.nextButton.setIcon(qta.icon("fa.forward", color="#F1F1F1", scale_factor=.9)) self.ui.prevButton.setText("") self.ui.prevButton.setIcon(qta.icon("fa.backward", color="#F1F1F1", scale_factor=.9)) self.configure_combo_box() self.update_completer() self.status_messenger = CQSpinner(self.ui.scrollArea) position = self.frameGeometry() position.moveCenter( QtGui.QDesktopWidget().availableGeometry().center()) self.show() self.raise_() def closeEvent(self, event=None): self.app.close() def update_completer(self): self.completer = CQCompleter(self.app.tags) self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive) self.completer.setCompletionRole(QtCore.Qt.DisplayRole) self.ui.searchLine.setCompleter(self.completer) def refresh_button_handler(self): if self.ui.galleryBox.isChecked(): self.app.find_galleries() if self.ui.metaBox.isChecked(): self.app.get_metadata() def next_page(self): next_page = self.page_number + 1 if next_page == self.max_page: return self.page_number = next_page def prev_page(self): prev_page = self.page_number - 1 if prev_page == -1: return self.page_number = prev_page def reset_scrollbar(self): scrollbar = self.ui.scrollArea.verticalScrollBar() scrollbar.setValue(scrollbar.minimum()) @property def page_number(self): return self.ui.pageBox.currentIndex() @page_number.setter def page_number(self, val): self.ui.pageBox.setCurrentIndex(val) @property def max_page(self): return self.ui.pageBox.count() @property def member_id(self): return self.ui.memberId.text() @member_id.setter def member_id(self, val): self.ui.memberId.setText(val) @property def pass_hash(self): return self.ui.passHash.text() @pass_hash.setter def pass_hash(self, val): self.ui.passHash.setText(val) @property def search_text(self): return self.ui.searchLine.text() @property def dirs(self): return self.ui.directories.toPlainText().splitlines() @dirs.setter def dirs(self, val): self.ui.directories.clear() [self.ui.directories.append(v) for v in val] @property def sort_type(self): return self.ui.sortBox.currentIndex() @property def sort_is_descending(self): return self.ui.descendingButton.isChecked() def set_button_status(self, button, status): getattr(getattr(self.ui, button), "setEnabled")(status) def disable_buttons(self, buttons): [self.set_button_status(b, False) for b in buttons] def enable_buttons(self, buttons): if self.button_lock: return [self.set_button_status(b, True) for b in buttons] def disable_all_buttons(self): self.disable_buttons(self.BUTTONS) def enable_all_buttons(self): self.enable_buttons(self.BUTTONS) def show_galleries(self, galleries): for gallery in galleries: assert gallery in self.app.current_page self.ui.flowLayout.addWidget(gallery.C_QGallery) gallery.C_QGallery.show() self.ui.flowLayout.update() def hide_galleries(self, galleries): for gallery in galleries: assert gallery in self.app.current_page self.ui.flowLayout.removeWidget(gallery.C_QGallery) try: gallery.C_QGallery.hide() except AttributeError: pass self.ui.flowLayout.update() def search(self): self.disable_all_buttons() self.app.search() self.enable_all_buttons() def inc_progress(self, val): self.ui.statusFrame.show() self.progress += val self.ui.progressBar.setValue(self.progress) def clear_progress_bar(self): self.ui.statusFrame.hide() self.progress = 0 self.ui.progressBar.setValue(self.progress) def browse(self): self.logger.debug("Browsing for files.") browser = CQFileDialog() browser.exec_() if browser.open_clicked: self.directories = browser.selectedFiles for directory in browser.selectedFiles: self.ui.directories.append(directory) def configure_combo_box(self): self.ui.pageBox.currentIndexChanged.connect(lambda x: None) self.ui.pageBox.clear() self.ui.pageBox.addItems(list(map(lambda x: "Page %s of %s" % (str(x), self.app.page_count), range(1, self.app.page_count + 1)))) self.ui.pageBox.currentIndexChanged.connect(self.app.switch_page)
class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.load_packs() self.ui.pushButton_apply.clicked.connect(self.apply_clicked) def load_packs(self): """Here we load the diferent blacklist packs into the tree view widget so that the user can check the ones he wants. """ # Dictionary containing the differen blacklists, within are touples of pack names mixed # with their respective URL. blacklists = { "Energized Protection": [("Spark", "https://block.energized.pro/spark/formats/domains.txt", "True Lite Protection Pack."), ("Blu", "https://block.energized.pro/blu/formats/domains.txt", "A Mid Ranger Flagship Protection Pack."), ("Blu GO", "https://block.energized.pro/bluGo/formats/domains.txt", "A Lightweight Mid Ranger Protection Pack."), ("Basic", "https://block.energized.pro/basic/formats/domains.txt", "An All-Rounder Balanced Protection Pack."), ("P**n", "https://block.energized.pro/p**n/formats/domains.txt", "Blocks Access to most of the Pornware."), ("Ultimate", "https://block.energized.pro/ultimate/formats/domains.txt", "Flagship Protection Pack from Energized Protection."), ("Unified", "https://block.energized.pro/unified/formats/domains.txt", "Flagship Full Protection Pack from Energized Protection."), ("Xtreme", "https://block.energized.pro/extensions/xtreme/formats/domains.txt", "(extension) An Extreme Solution for Ultimate Protection."), ("Regional", "https://block.energized.pro/extensions/regional/formats/domains.txt", "(extension) An Extension to Block Regional Annoyances."), ("Social", "https://block.energized.pro/extensions/social/formats/domains.txt", "(extension) Social Sites and Apps Blocking."), ("P**n Lite", "https://block.energized.pro/extensions/p**n-lite/formats/domains.txt", "(extension) Lite Extension P**n Pack.")], "Steven Black Hosts": [("Unified Hosts", "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts", "This hosts file is a merged collection of hosts from reputable sources, with a dash of crowd sourcing via GitHub" ), ("Fake News", "https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews/hosts", "(extension)"), ("P**n", "https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/p**n/hosts", "(extension)"), ("Social", "https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/social/hosts", "(extension)"), ("Gambling", "https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/gambling/hosts", "(extension)")], "OISD": [("Basic", "https://dbl.oisd.nl/basic/", "primarily blocks Ads, (Mobile) App Ads."), ("Full", "https://dbl.oisd.nl/", "Ads, (Mobile) App Ads, Phishing, Malvertising, Malware, Spyware, Ransomware, CryptoJacking, Scam... Telemetry, Analytics, Tracking (Where not needed for proper functionality)" )], "WindowsSpyBlocker": [("Spy", "https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/spy.txt", "Spy rules block Windows telemetry"), ("Updates", "https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/update.txt", "Update rules block Windows Update"), ("Extra", "https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/extra.txt", "Block third party applications like Skype, Bing, Live, Outlook, NCSI, Microsoft Office" )], } for blacklist in blacklists: parent = QtWidgets.QTreeWidgetItem(self.ui.treeWidget_packs) parent.setText(0, blacklist) # parent.setFlags(parent.flags( # ) | QtCore.Qt.ItemFlags.ItemIsAutoTristate | QtCore.Qt.ItemFlags.ItemIsUserCheckable) for pack, url, description in blacklists[blacklist]: child = QtWidgets.QTreeWidgetItem(parent) child.setFlags(child.flags() | QtCore.Qt.ItemFlags.ItemIsUserCheckable) child.setText(0, pack) child.setText(1, url) child.setText(2, description) child.setCheckState(0, QtCore.Qt.CheckState.Unchecked) def apply_clicked(self): """This will execute the domain merger script when the user presses the apply button. It extract the values from the tree widget and pass them as arguments to the script. """ selected_packs = [] # Iterating through selected items in the tree widget iterator = QtWidgets.QTreeWidgetItemIterator( self.ui.treeWidget_packs, QtWidgets.QTreeWidgetItemIterator.IteratorFlags.Checked) while iterator.value(): item = iterator.value() # 1 is the column of the link to the pack itself print(item.text(1)) selected_packs.append(item.text(1)) iterator += 1 try: _thread.start_new_thread( domain_merger, (selected_packs, self.ui.checkBox_hosts.isChecked())) except: print("Unable to start thread.")
class MainWindow(QMainWindow): class PidDialog(QDialog): values_changed = pyqtSignal(float, float, float) def __init__(self, parent=None): super().__init__(parent=parent) self.setWindowTitle("PID settings") self.setMinimumWidth(150) # self.setWindowFlags(Qt.WindowStaysOnTopHint) layout = QGridLayout() p_label = QLabel("P") layout.addWidget(p_label, 0, 0) self.p_spinbox = QDoubleSpinBox() self.p_spinbox.setSingleStep(0.1) self.p_spinbox.valueChanged.connect(self._emit_new_values) layout.addWidget(self.p_spinbox, 0, 1) i_label = QLabel("I") layout.addWidget(i_label, 1, 0) self.i_spinbox = QDoubleSpinBox() self.i_spinbox.setSingleStep(0.1) self.i_spinbox.valueChanged.connect(self._emit_new_values) layout.addWidget(self.i_spinbox, 1, 1) d_label = QLabel("D") layout.addWidget(d_label, 2, 0) self.d_spinbox = QDoubleSpinBox() self.d_spinbox.setSingleStep(0.1) self.d_spinbox.valueChanged.connect(self._emit_new_values) layout.addWidget(self.d_spinbox, 2, 1) self.setLayout(layout) def _emit_new_values(self): p = self.p_spinbox.value() i = self.i_spinbox.value() d = self.d_spinbox.value() self.values_changed.emit(p, i, d) def set_values(self, p, i, d): self.p_spinbox.setValue(p) self.i_spinbox.setValue(i) self.d_spinbox.setValue(d) def closeEvent(self, event): event.accept() self.deleteLater() def __init__(self, **kwargs): super().__init__(**kwargs) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.graphicsView.setBackground(pg.mkColor(0.3)) self.plot_box = self.ui.graphicsView.addViewBox(row=1, col=1, lockAspect=True, enableMouse=True, invertY=True) self.image_item = pg.ImageItem() self.image_item.setOpts(axisOrder='row-major') self.plot_box.addItem(self.image_item) self.roi = None self.ui.selectDataButton.toggled.connect(self.show_roi) self.ui.resetSelectDataButton.clicked.connect(self.reset_roi) self.settings_layout = QHBoxLayout() self.settings_widget = QWidget() self.settings_layout.addWidget(self.settings_widget) self.ui.camSettingsWidget.setLayout(self.settings_layout) self.data_handler = DataHandler() for plugin in self.data_handler.plugins: self.add_plugin(plugin.get_widget(), plugin.name) self.data_handler.ndarray_available.connect(self.show_ndarray) self.data_handler.camera_controls_changed.connect( self.set_camera_controls) self.ui.actionSave_image.triggered.connect(self.data_handler.save_file) self.data_handler.enable_saturation_widget.connect( self.enable_saturation_bar) self.data_handler.saturation_changed.connect( self.ui.progressBar.setValue) self.data_handler.message.connect(self.show_message) self.camera_dialog = CameraDialog() self.ui.actionChoose_camera.triggered.connect( self.camera_dialog.choose_camera) self.camera_dialog.camera_changed.connect( self.data_handler.change_camera) self.camera_dialog.choose_first_camera() self.ui.actionTune_camera_parameters.triggered.connect(self.tune_pid) self.ui.actionShow_Settings.toggled.connect(self.show_settings) self.ui.actionDraw_lines.toggled.connect(self.draw_lines) self.hline = None self.vline = None @pyqtSlot(np.ndarray) def show_ndarray(self, array): self.image_item.setImage(array) @pyqtSlot(QWidget) def set_camera_controls(self, controls): self.settings_layout.removeWidget(self.settings_widget) self.settings_widget.setParent(None) self.settings_widget.deleteLater() self.settings_widget = controls self.settings_layout.addWidget(controls) @pyqtSlot(bool) def enable_saturation_bar(self, enable): self.ui.progressBar.setEnabled(enable) if not enable: self.ui.progressBar.setValue(0) @pyqtSlot(int) def set_saturation_percentage(self, value): self.ui.progressBar.setValue(value) @pyqtSlot(bool) def show_settings(self, show): self.ui.bottom_settings_widget.setVisible(show) @pyqtSlot(QWidget, str) def add_plugin(self, widget: QWidget, name: str): self.ui.tabWidget.addTab(widget, name) @pyqtSlot(str) def show_message(self, message): self.ui.statusbar.showMessage(message, 5000) @pyqtSlot(bool) def show_roi(self, show): if show: rect = self.data_handler.clip_size if rect is not None: self.roi = pg.ROI([rect.left(), rect.top()], [rect.width(), rect.height()], pen=pg.mkPen(color='r')) self.roi.addScaleHandle([0.5, 1], [0.5, 0.5]) self.roi.addScaleHandle([0, 0.5], [0.5, 0.5]) self.plot_box.addItem(self.roi) self.roi.setZValue(10) self.roi.sigRegionChangeFinished.connect(self.on_roi_changed) else: if self.roi is not None: self.plot_box.removeItem(self.roi) self.roi = None @pyqtSlot() def reset_roi(self): self.ui.selectDataButton.setChecked(False) self.show_roi(False) self.data_handler.clip_size = None @pyqtSlot() def on_roi_changed(self): if self.roi is not None: pos = self.roi.pos() size = self.roi.size() rect = QRect(pos.x(), pos.y(), size.x(), size.y()) self.data_handler.set_clip_size(rect) @pyqtSlot(bool) def draw_lines(self, draw): if draw: x_range, y_range = self.plot_box.viewRange() self.hline = pg.InfiniteLine(pos=np.mean(y_range), angle=0, pen=pg.mkPen('r')) self.vline = pg.InfiniteLine(pos=np.mean(x_range), angle=90, pen=pg.mkPen('r')) self.hline.setZValue(10) self.vline.setZValue(10) self.plot_box.addItem(self.hline) self.plot_box.addItem(self.vline) else: if self.hline is not None: self.plot_box.removeItem(self.hline) self.hline = None if self.vline is not None: self.plot_box.removeItem(self.vline) self.vline = None def tune_pid(self): try: dialog = self.PidDialog(parent=self) cam = self.data_handler.camera dialog.set_values(*cam.get_pid()) dialog.values_changed.connect(self.set_pid_values) dialog.show() dialog.raise_() dialog.activateWindow() except Exception as err: print(str(err)) def set_pid_values(self, p, i, d): try: cam = self.data_handler.camera cam.set_pid(p, i, d) except: pass
class Main(QtWidgets.QMainWindow): def __init__(self): super(Main, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # Init models self.gen_model = build_generator() self.disc_model = build_discriminator() self.gen_opt = tf.keras.optimizers.Adam(learning_rate=1e-4) self.disc_opt = tf.keras.optimizers.Adam(learning_rate=1e-4) self.target_tensor = None # Init camera self.camera = cv2.VideoCapture(0) self.camera_frame = None # Train Timer self.trn_timer = QtCore.QTimer() self.trn_timer.setInterval( int(1000 / self.ui.spinBox_ExpectedFPS.value())) self.trn_timer.timeout.connect(self.do_train_step) # Camera Timer self.camera_timer = QtCore.QTimer() self.camera_timer.setInterval(int(1000 / 24)) self.camera_timer.timeout.connect(self.read_camera) # Signals & Slots self.ui.pushButton_Reset.clicked.connect(self.reset_models) self.ui.spinBox_ExpectedFPS.valueChanged.connect(self.change_interval) self.ui.pushButton_OpenCamera.clicked.connect(self.toggle_camera) self.ui.pushButton_CameraCapture.clicked.connect(self.toggle_camera) self.ui.pushButton_TrainStart.clicked.connect(self.toggle_train) self.ui.pushButton_TrainStop.clicked.connect(self.toggle_train) self.ui.pushButton_SaveResult.clicked.connect(self.save_result_img) @QtCore.pyqtSlot() def save_result_img(self): file_path, selected_filter = QtWidgets.QFileDialog.getSaveFileName( self, caption="Save File", directory=".", filter="Image (*.png)") if file_path: self.ui.label_Generated.pixmap().save(file_path, format="PNG") @QtCore.pyqtSlot() def do_train_step(self): if self.target_tensor is not None: generated_img, disc_output = train_step( self.target_tensor[tf.newaxis, ...], self.gen_model, self.disc_model, self.gen_opt, self.disc_opt) img_array = tensor_to_array(generated_img)[0] qim = array_uint8_to_qimage(img_array, bgr=False) pix = QtGui.QPixmap.fromImage(qim) self.ui.label_Generated.setPixmap(pix) self.ui.pushButton_SaveResult.setEnabled(True) disc_pred = ("<p style='color: red;'>Fake</p>" if (disc_output[0, 0] < 0).numpy() else "<p style='color: blue;'>Real</p>") self.ui.textBrowser_Console.append(disc_pred) else: self.ui.textBrowser_Console.append( "Target Photo hasn't been taken yet.") self.ui.pushButton_TrainStop.click() @QtCore.pyqtSlot() def toggle_train(self): if self.sender() is self.ui.pushButton_TrainStart: self.trn_timer.start() self.ui.pushButton_TrainStop.setEnabled(True) self.ui.pushButton_Reset.setEnabled(False) self.ui.pushButton_OpenCamera.setEnabled(False) self.sender().setEnabled(False) elif self.sender() is self.ui.pushButton_TrainStop: self.trn_timer.stop() self.ui.pushButton_TrainStart.setEnabled(True) self.ui.pushButton_Reset.setEnabled(True) self.sender().setEnabled(False) @QtCore.pyqtSlot() def read_camera(self): ret, self.camera_frame = self.camera.read() if ret: # Take lr 208, 432, tb 128, 352 self.camera_frame = cv2.resize(self.camera_frame, (640, 480)) cv2.rectangle(self.camera_frame, (207, 127), (432, 352), (0, 0, 255)) qim = array_uint8_to_qimage(self.camera_frame, bgr=True) pix = QtGui.QPixmap.fromImage(qim) self.ui.label_Camera.setPixmap(pix) else: self.ui.textBrowser_Console.append("<p style='color: #FF0000'>" "Camera capture failed." "</p>") self.camera_timer.stop() @QtCore.pyqtSlot() def toggle_camera(self): if self.sender() is self.ui.pushButton_OpenCamera: self.camera_timer.start() self.ui.pushButton_CameraCapture.setEnabled(True) self.ui.pushButton_TrainStart.setEnabled(False) self.sender().setEnabled(False) elif self.sender() is self.ui.pushButton_CameraCapture: self.camera_timer.stop() captured_frame = self.camera_frame[128:352, 208:432, ::-1].copy() qim = array_uint8_to_qimage(captured_frame, bgr=False) pix = QtGui.QPixmap.fromImage(qim) self.ui.label_Target.setPixmap(pix) self.target_tensor = tf.constant( (captured_frame.astype('float32') - 127.5) / 127.5) self.ui.pushButton_OpenCamera.setEnabled(True) self.ui.pushButton_TrainStart.setEnabled(True) self.sender().setEnabled(False) @QtCore.pyqtSlot() def change_interval(self): if self.sender() is self.ui.spinBox_ExpectedFPS: self.trn_timer.setInterval(int(1000 / self.sender().value())) self.ui.textBrowser_Console.append( f"Expected FPS Changed to {self.sender().value()}") @QtCore.pyqtSlot() def reset_models(self): tf.compat.v1.reset_default_graph() self.gen_model = build_generator() self.disc_model = build_discriminator() self.ui.label_Camera.clear() self.ui.label_Target.clear() self.ui.label_Generated.clear() self.ui.pushButton_OpenCamera.setEnabled(True) self.ui.pushButton_SaveResult.setEnabled(False) self.ui.textBrowser_Console.append(f"Models have been reset.")
class Main(QtWidgets.QMainWindow): def __init__(self): super(Main, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.process = QtCore.QProcess() self.process.stateChanged.connect(self.onStateChanged) self.process.readyReadStandardError.connect(self.terminalAppendError) self.process.readyReadStandardOutput.connect(self.terminalAppendOutput) self.process.finished.connect(self.onFinished) self.ui.pushButton_MNIST.clicked.connect(self.openSubprocess) self.ui.pushButton_InsightFace.clicked.connect(self.openSubprocess) self.ui.pushButton_NeuralTransfer.clicked.connect(self.openSubprocess) self.ui.pushButton_DCGAN.clicked.connect(self.openSubprocess) self.ui.pushButton_Terminate.clicked.connect(self.terminateSubprocess) @QtCore.pyqtSlot() def onFinished(self): os.chdir(os.path.abspath(os.path.dirname(FILE))) self.ui.pushButton_Terminate.setEnabled(False) for w in self.ui.groupBox_Programs.findChildren(QtWidgets.QPushButton): w.setEnabled(True) @QtCore.pyqtSlot() def terminalAppendError(self): error = self.process.readAllStandardError().data().decode() self.ui.plainTextEdit_Terminal.appendPlainText(error) @QtCore.pyqtSlot() def terminalAppendOutput(self): output = self.process.readAllStandardOutput().data().decode() self.ui.plainTextEdit_Terminal.appendPlainText(output) @QtCore.pyqtSlot() def terminateSubprocess(self): self.process.kill() self.ui.plainTextEdit_Terminal.appendPlainText( "You terminated sub program.") @QtCore.pyqtSlot() def openSubprocess(self): if self.sender() is self.ui.pushButton_InsightFace: os.chdir('./subprocesses/InsightFace') self.process.start('python main.py') elif self.sender() is self.ui.pushButton_NeuralTransfer: os.chdir('./subprocesses/StyleTransfer') self.process.start('python main.py') elif self.sender() is self.ui.pushButton_MNIST: os.chdir('./subprocesses/MNIST') self.process.start('python main.py') elif self.sender() is self.ui.pushButton_DCGAN: os.chdir('./subprocesses/DCGAN') self.process.start('python main.py') self.ui.pushButton_Terminate.setEnabled(True) for w in self.ui.groupBox_Programs.findChildren(QtWidgets.QPushButton): w.setEnabled(False) @QtCore.pyqtSlot() def onStateChanged(self): if (self.process.state()) == 2: self.ui.plainTextEdit_Terminal.appendPlainText( f'Subprocess starting, PID: {self.process.processId()}.')