def getInputOutputWindow(titletext="Select File"): layout = [[sg.Text('Input File')], [sg.Input(), sg.FileBrowse(initial_folder=home)], [sg.Text('Output File')], [sg.Input(), sg.FileSaveAs(initial_folder=home)], [sg.OK(), sg.Cancel()]] window = sg.Window(titletext, layout) event, values = window.Read() return event, values
def getInputWindow(titletext="Inputfile"): layout = [[sg.Text("Select a file to convert:")], [sg.Input(), sg.FileBrowse("Select File", initial_folder=home)], [sg.OK(), sg.Cancel()]] window = sg.Window(titletext, layout) event, values = window.Read() window.Close() return event, values
def layout(self): # fmt: off self.img = psg.Image(filename=None) return [ [self.img], [ psg.Text(self.cfg.uie.eval_text), psg.Input(key=self.cfg.uie.eval_key), psg.FileBrowse(self.cfg.uie.browse_btn, file_types=self.cfg.uie.allowed_files) ], [ psg.Text(self.cfg.uie.gt_text), psg.Input(key=self.cfg.uie.gt_key), psg.FileBrowse(self.cfg.uie.browse_btn, file_types=self.cfg.uie.allowed_files) ], [psg.Button(cfg.uie.eval_btn)], ]
def gui_select_tracks(tracks: List[dict], start_time: int, config: dict) -> dict: chataigne_path_cfg = config.get("chataigneProjectPath") if not chataigne_path_cfg: chataigne_path_cfg = "" start_time_cfg = config.get("startTime") if not start_time_cfg: start_time_cfg = start_time tracks_cfg = config.get("tracks") if tracks_cfg is None: tracks_cfg = {} layout = [[sg.Text('Chataigne base project:')], [sg.Input(chataigne_path_cfg, key='-CH_PATH-'), sg.FileBrowse()], [sg.Text('Start time'), sg.Input(default_text=start_time_cfg, key='-START_TIME-')], [sg.Text('Select tracks, DMX channel')]] for i, track in enumerate(tracks): track_cfg = tracks_cfg.get(track["name"]) if track_cfg is None: include = False dmx = None else: include = track_cfg["include"] dmx = track_cfg["dmx"] if dmx is None: dmx = "" layout.append( [sg.Checkbox(track["name"], default=include, key=f"-TRACK_{i}-"), sg.Input(dmx, key=f"-DMX_{i}-")]) layout.append([sg.Submit("Convert selected tracks!", bind_return_key=True)]) window = sg.Window('Select DMX tracks', layout) event, values = window.read() window.close() if event == None: exit() start_time_cfg = re.sub('[^0-9]', '', values["-START_TIME-"]) start_time_cfg = int(start_time_cfg) if start_time_cfg else start_time config = {"chataigneProjectPath": values["-CH_PATH-"], "startTime": start_time_cfg, "tracks": {}} for i, track in enumerate(tracks): checked = values[f'-TRACK_{i}-'] dmx = re.sub('[^0-9]', '', values[f'-DMX_{i}-']) dmx = int(dmx) if dmx else None config["tracks"][track["name"]] = {"include": checked, "dmx": dmx} return config
def create_conf_window(parser): sg.theme(parser.get('gui_settings','theme')) def TextLabel(text): return sg.Text(text+':', justification='r', size=(25,1)) layout = [ [sg.Text('Choose Configuration', font = 'Any 20', justification='c')], [sg.Text('')], [TextLabel('Output Directory'), sg.Input(key='-OUTDIR-'), sg.FolderBrowse(target='-OUTDIR-')], [TextLabel('FASTQ Files Directory'), sg.Input(key='-FASTQ-'), sg.FolderBrowse(target='-FASTQ-')], [TextLabel('Spectra Files Directory'), sg.Input(key='-SPECTRA-'), sg.FolderBrowse(target='-SPECTRA-')], [sg.Text('')], [TextLabel('Trinity'), sg.Input(key='-TRINITY-'), sg.FileBrowse(target='-TRINITY-')], [TextLabel('hg19'), sg.Input(key='-HG19-'), sg.FileBrowse(target='-HG19-')], [TextLabel('SearchGUI'), sg.Input(key='-SEARCHGUI-'), sg.FileBrowse(target='-SEARCHGUI-')], [TextLabel('PeptideShaker'), sg.Input(key='-PEPTIDE-'), sg.FileBrowse(target='-PEPTIDE-')], [TextLabel('ACTG'), sg.Input(key='-ACTG-'), sg.FolderBrowse(target='-ACTG-')], [sg.Text('')], [TextLabel('Transcriptome GTF'), sg.Input(key='-GTF-'), sg.FolderBrowse(target='-GTF-')], [TextLabel('Reference genome'), sg.Input(key='-REF-'), sg.FolderBrowse(target='-REF-')], [TextLabel('Mapping Method'), sg.Combo(['PV','PS','VO','SO'],key='-MAP-')], [TextLabel('Protein Database'), sg.Input(key='-DB-'), sg.FileBrowse(target='-DB-')], [TextLabel('Serialization File'), sg.Input(key='-SER-'), sg.FileBrowse(target='-SER-')], [sg.Text('')], [TextLabel('Bamstats'), sg.Input(key='-BAMSTATS-'), sg.FileBrowse(target='-BAMSTATS-')], [TextLabel('BAM Files'), sg.Input(key='-BAM-'), sg.FolderBrowse(target='-BAM-')], [TextLabel('BED File'), sg.Input(key='-BED-'), sg.FileBrowse(target='-BED-')], [sg.Text('')], [TextLabel('DeNoPro Location'), sg.Input(key='-DENOPRO-'), sg.FolderBrowse(target='-DENOPRO-')], [sg.Text('')], [TextLabel('Theme'), sg.Combo(sg.theme_list(), size=(17, 0.8), key='-THEME-')], [sg.Text('')], [sg.Text('')], [sg.Button('Save'), sg.InputText('', do_not_clear=False, visible=False, key='-filename-',enable_events=True), sg.FileSaveAs('Save As'),sg.Button('Exit')] ] window = sg.Window("Config", keep_on_top=True).Layout([[sg.Column(layout,size = (680,720),scrollable=True)]]).Finalize() for k,v in conf_keys.items(): try: window[conf_keys[k][2]].update(value=parser.get(v[0],k)) except Exception as e: print(f'Problem updating GUI window from config. Key = {k}') return window
def gui_ltp_path(last_ltp_path): layout = [[sg.Text('Lighttoys project:')], [sg.Input(last_ltp_path, key='-PATH-'), sg.FileBrowse()], [sg.Submit('Next', bind_return_key=True)]] window = sg.Window('Select project', layout) event, values = window.read() window.close() if event == None: exit() path = values['-PATH-'] return path
def get_layout(styles: Any, sg: PySimpleGUIQt) -> list: """ Função que retorna o layout utilizado na janela da aplicação. Argurments: styles (Any): módulo/arquivo com os atributos de estilo sg (PySimpleGUIQt): módulo PySimpleGUIQt Return: list: matriz com o layout do PySimpleGUI """ return [ [ sg.Text(' Selecione o arquivo de planilha do Excel para análise', **styles.text_style) ], [ sg.InputText('C:\\', enable_events=True, **styles.file_name_input_style), sg.FileBrowse(**styles.file_browse_style) ], [sg.Text('')], [ sg.Text(' Selecione o lugar onde o novo arquivo será salvo', **styles.text_style) ], [ sg.InputText('C:\\planilha-final.xlsx', enable_events=True, **styles.file_name_output_style), sg.FileSaveAs(**styles.file_save_style) ], [ sg.Text(''), sg.Text(''), sg.Button('Gerar planilha', **styles.generate_button_style) ], [sg.Text('')], [sg.Output()], [sg.Text('')], [ sg.Text( 'gerador-planilha-desktop © 2021, desenvolvido por João Paulo Carvalho' ) ] ]
def mainScreen(): p.SetOptions(background_color='white', button_color=('white', '#4286f4')) layout = [ [ p.Image(data_base64=Images.logo, background_color='white', size=(450, 100), click_submits=True, key='_IMAGE_') ], [p.T('Required:', font=('Arial', 13, 'bold'), justification='center')], [p.T('▬' * 35, justification='center')], [ p.T('Choose IPSW Filepath: ', font=('Arial', 10, 'italic'), justification='left') ], [ p.Input('', key='_IPSW_'), p.FileBrowse(button_color=('white', '#4286f4')) ], [ p.T('Choose Blobs Filepath: ', font=('Arial', 10, 'italic'), justification='left') ], [ p.Input('', key='_BLOBS_'), p.FilesBrowse(button_color=('white', '#4286f4')) ], [ p.T('Choose SEP Filepath: ', font=('Arial', 10, 'italic'), justification='left') ], [ p.Input('', key='_SEP_'), p.FileBrowse(button_color=('white', '#4286f4')) ], [ p.Checkbox( 'Use Latest SEP \n(Do Not Set SEP Filepath If Using This!)', key='_LATESTSEP_') ], [ p.T('Choose Baseband Filepath: ', font=('Arial', 10, 'italic'), justification='left') ], [ p.Input('', key='_BASE_'), p.FileBrowse(button_color=('white', '#4286f4')) ], [ p.Checkbox( 'Use Latest Baseband \n(Do Not Set Baseband Filepath If Using This!)', key="_LATESTBASE_") ], [ p.T('Optional: ', font=('Arial', 13, 'bold'), justification='center') ], [p.T('▬' * 35, justification='center')], [ p.T('SEP Manifest: ', font=('Arial', 10, 'italic'), justification='left') ], [ p.Input('', key='_SEPMANI_'), p.FileBrowse(button_color=('white', '#4286f4')) ], [ p.T('Baseband Build Manifest: ', font=('Arial', 10, 'italic'), justification='left') ], [ p.Input('', key='_BASEMANI_'), p.FileBrowse(button_color=('white', '#4286f4')) ], [ p.T('Optional Flags:', justification='center', font=('Arial', 13, 'bold')) ], [p.T('▬' * 35, justification='center')], [ p.Checkbox('Debug', key='_DEBUG_'), p.Checkbox('No Baseband', key='_NOBASEBAND_') ], [ p.Checkbox('Update', key='_UPDATE_'), p.Checkbox('Wait', key="_WAIT_") ], [p.T('▬' * 35, justification='center')], [ p.Button('Exit Recovery', size=(23, 1)), p.Button('Start', size=(23, 1)) ], [p.Button('Exit', size=(23, 1)), p.Button('Donate', size=(23, 1))], [ p.Button('Open TSSSaver', size=(23, 1)), p.Button('Open ipsw.me', size=(23, 1)) ], [ p. T('\nVersion: 1.0.6 | Licensed Under GNU GPLv3 | Click Here For GitHub', click_submits=True, key='_FOOTER_', font=('Arial', 8, 'italic'), justification='center') ] ] window = p.Window('EGTR', no_titlebar=True, keep_on_top=True, grab_anywhere=True).Layout(layout) while True: event, values = window.Read() if event == 'Exit': window.Close() break elif event == 'Exit Recovery': if getTypeFutureRestore() == 1: futurerestore = getRealPath(DOWNLOAD_DIRECTORY + '/futurerestore') elif getTypeFutureRestore() == 2: futurerestore = getRealPath(DOWNLOAD_DIRECTORY + '/futurerestore.exe') os.system(futurerestore + '--exit-recovery') p.Window('Logs:', no_titlebar=True, keep_on_top=True, grab_anywhere=True, auto_close=True, auto_close_duration=5).Layout( [[p.T('Refer To The Terminal For Output ')]]).Read() elif event == 'Donate': webbrowser.open_new_tab('https://paypal.me/m4csdev') elif event == 'Open TSSSaver': webbrowser.open_new_tab('https://tsssaver.1conan.com/') elif event == 'Open ipsw.me': webbrowser.open_new_tab('https://ipsw.me') elif event == '_FOOTER_': webbrowser.open_new_tab( 'https://github.com/M4cs/EGTR-Futurerestore') elif event == 'Start': if values['_LATESTSEP_'] == True: latestsep = ' --latest-sep' sep_path = '' elif values['_LATESTSEP_'] == False: latestsep = '' if values['_LATESTBASE_'] == True: latestbase = ' --latest-baseband' base_path = '' elif values['_LATESTBASE_'] == False: latestbase = '' if values['_IPSW_'] == '': p.Window('Error', auto_close=True, auto_close_duration=3, keep_on_top=True, no_titlebar=True, grab_anywhere=True).Layout([[ p.T('Error: You must enter an IPSW! ') ]]).Read() elif values['_IPSW_'] != '': ipsw_path = " " + getRealPath(values['_IPSW_']) if values['_SEP_'] == '': if values['_LATESTSEP_'] == True: latestsep = '--latest-sep' sep_path = '' elif values['_LATESTSEP_'] == False: p.Window( 'Error', auto_close=True, auto_close_duration=3, keep_on_top=True, no_titlebar=True, grab_anywhere=True ).Layout([[ p. T('Error: You must enter an SEP path or choose Use Latest! ' ) ]]).Read() elif values['_SEP_'] != '': if values['_LATESTSEP_'] == True: sep_path = '' latestsep = ' --latest-sep' elif values['_LATESTSEP_'] == False: sep_path = ' -s ' + getRealPath(values['_SEP_']) latestsep = '' if values['_BASE_'] == '': if values['_LATESTBASE_'] == True: base_path = '' latestbase = ' --latest-base' elif values['_LATESTBASE_'] == False: p.Window( 'Error', auto_close=True, auto_close_duration=3, keep_on_top=True, no_titlebar=True, grab_anywhere=True ).Layout([[ p. T('Error: You must enter an Base path or choose Use Latest! ' ) ]]).Read() elif values['_BASE_'] != '': if values['_LATESTBASE_'] == True: base_path = '' latestbase = ' --latest-base' elif values['_LATESTBASE_'] == False: base_path = ' -b ' + getRealPath(values['_BASE_']) latestbase = '' if values['_BLOBS_'] == '': p.Window('Error', auto_close=True, auto_close_duration=3, keep_on_top=True, no_titlebar=True, grab_anywhere=True).Layout([[ p.T('Error: You must choose SHSH2 Blobs! ') ]]).Read() elif values['_BLOBS_'] != '': blobs_path = ' -t' + getRealPath(values['_BLOBS_']) if values['_DEBUG_'] == True: debug = ' -d' elif values['_DEBUG_'] == False: debug = '' if values['_BASEMANI_'] == '': basemani = '' elif values['_BASEMANI_'] != '': basemani = ' -p' + values['_BASEMANI_'] if values['_SEPMANI_'] == '': sepmani = '' elif values['_SEPMANI_'] != '': sepmani = ' -m ' + values['_SEPMANI_'] if values['_NOBASEBAND_'] == True: nobaseband = ' --no-baseband' base_path = '' basemani = '' elif values['_NOBASEBAND_'] == False: nobaseband = '' if values['_UPDATE_'] == True: update = ' -u' elif values['_UPDATE_'] == False: update = '' if values['_WAIT_'] == True: wait = ' -w' elif values['_WAIT_'] == False: wait = '' if getTypeFutureRestore() == 1: futurerestore = getRealPath(DOWNLOAD_DIRECTORY + '/futurerestore') elif getTypeFutureRestore() == 2: futurerestore = getRealPath(DOWNLOAD_DIRECTORY + '/futurerestore.exe') query = futurerestore + blobs_path + base_path + sep_path + latestbase + latestsep + debug + basemani + sepmani + update + nobaseband + wait + ipsw_path print(query) outputscreen = p.Window( 'Logs:', no_titlebar=True, keep_on_top=True, grab_anywhere=True ).Layout([[ p. T('Are You Sure? You may risk bootlooping or bricking your device! ' ) ], [p.Button('Cancel'), p.Button('Continue')]]) while True: event, values = outputscreen.Read() if event == 'Continue': p.Window('Logs:', no_titlebar=True, keep_on_top=True, grab_anywhere=True, auto_close=True, auto_close_duration=5).Layout([[ p.T('Refer To The Terminal For Output ') ]]).Read() outputscreen.Close() os.system(query) break elif event == 'Cancel': outputscreen.Close() break window.Close()
def get_settings(min_df_val, max_df_val, label_words_val, folder_val, stopwords_path): layout2 = [[sg.Text('Parameter Settings', font=("Ariel", 12))], [ sg.Text('min_df', size=(15, 1), font=("Ariel", 12)), sg.InputText(str(min_df_val), font=("Ariel", 12), key='min_df_val') ], [ sg.Text('max_df', size=(15, 1), font=("Ariel", 12)), sg.InputText(str(max_df_val), font=("Ariel", 12), key='max_df_val') ], [ sg.Text('Number of Label Words', size=(15, 1), font=("Ariel", 12)), sg.InputText(str(label_words_val), font=("Ariel", 12), key='label_words_val') ], [ sg.Txt('Output Folder:', size=(10, 1), font=("Ariel", 12)), sg.InputText(str(folder_val), size=(30, 1), font=("Ariel", 12), key='folder_val'), sg.FolderBrowse(font=("Ariel", 12)) ], [ sg.Txt('Stopwords file:', size=(10, 1), font=("Ariel", 12)), sg.InputText(str(stopwords_path), size=(30, 1), font=("Ariel", 12), key='stopwords_path'), sg.FileBrowse(font=("Ariel", 12)) ], [sg.Submit(font=("Ariel", 12)), sg.Cancel(font=("Ariel", 12))]] settingswdw = sg.Window('Settings', grab_anywhere=False, resizable=False).Layout(layout2) #settingswdw.Refresh() while True: # Event Loop event, values = settingswdw.Read() print(event, values) if event is None or event == 'Cancel': print('None or Exit event') break elif event == 'Submit': if not RepresentsInt(values['min_df_val']) or not RepresentsInt( values['max_df_val']) or not RepresentsInt( values['label_words_val']): sg.PopupError('Values must be integers, please correct.') elif not os.path.exists(folder_val) or not os.path.isdir( folder_val): sg.PopupError('Folder not valid, please correct.') elif not os.path.exists(stopwords_path) or not os.path.isfile( stopwords_path): sg.PopupError('Stopwords file not valid, please correct.') else: min_df_val = values['min_df_val'] max_df_val = values['max_df_val'] label_words_val = values['label_words_val'] folder_val = values['folder_val'] stopwords_path = values['stopwords_path'] #print('min_df_val: ' + min_df_val + ' max_df_val:' + max_df_val + ' label_words_val:' + label_words_val + ' output_folder_val: ' + folder_val) break print('min_df_val: ' + min_df_val + ' max_df_val:' + max_df_val + ' label_words_val:' + label_words_val + ' output_folder_val: ' + folder_val + ' stopwords_path: ' + stopwords_path) settingswdw.Close() return min_df_val, max_df_val, label_words_val, folder_val, stopwords_path
return sg.Frame(title, [layout]) behavior_frame = sg.Frame('Behavior profile', [ [ sg.Text('Profile path: '), sg.InputText(key='behavior_save'), sg.Button('Save profile', size=BUTTON_SIZE, key='save_behavior') ], [ sg.Button('Load profile', size=BUTTON_SIZE, key='load_behavior', enable_events=True), sg.InputText(key='behavior'), sg.FileBrowse(key='behavior_browse', size=BUTTON_SIZE) ], ], size=(300, 50)) behavior_tree_tabs = [] all_behavior = {} for behavior_type in BEHAVIOR_TYPES: behavior_entry = {} behavior_entry['counter'] = Counter() behavior_entry['storage'] = BehaviorStorage() tree = sg.TreeData() behavior_tree = sg.Tree(data=tree, headings=["st", "gg"], auto_size_columns=True,
def main(): sg.theme('SystemDefaultForReal') main_window = None command_to_run = 'denopro ' layout = [ [sg.Text('DeNoPro : de novo Proteogenomics Pipeline', justification='c', font=('Any',22))], [sg.Text('')], [sg.Text('Mode : ', size=(10,1), justification='r'), sg.Combo(['assemble','searchdb','identify','novelorf', 'quantify'],key='mode'), sg.Text('CPU:', justification='r'), sg.Input(key='cpu',font = 'Any 10', size=(5,0.8)), sg.Text('Max mem:', size=(10,1), justification='r'), sg.Input(key='max_mem', font = 'Any 10', size=(5,0.8))], [sg.Text('Config : ', size=(9,1), justification='r'), sg.Input(key='-config-', enable_events=True), sg.FileBrowse('Select',target='-config-',size = (10,0.8),file_types=(('Config Files','*.conf'),('INI files','*.ini'))), sg.Button('Change Configuration', size=(22,0.8))], [sg.Text('')], #output [sg.Text('Final Command:')], [sg.Text(size=(90,3),key='command_line', text_color='red',font='Courier 8')], [sg.Output(size=(90,16), font='Courier 10', key='-ML-')], [sg.Button('Start', button_color=('white','green')), sg.Button('Exit', button_color=('white','#8a2815'))] ] main_window = sg.Window('DeNoGUI', layout, font = 'Helvetica 12', finalize=True) while True: event,values = main_window.read() # define exit if event in (sg.WIN_CLOSED, 'Exit'): break # Config Loop if event == 'Change Configuration': # set the main config (if called) if values['-config-']: chosenConfig = values['-config-'] parser = load_parser(chosenConfig) event,values = create_conf_window(parser).read(close=True) if event == 'Save': save_config(chosenConfig,parser,values) elif event == '-filename-': filename = values['-filename-'] save_config(filename,parser,values) else: sg.popup('No config file selected, will create one for you...') createdParser = create_parser(default_conf) createdParser.set('gui_settings','theme','SystemDefaultForReal') event,values = create_conf_window(createdParser).read(close=True) if event == 'Save': sg.popup('Please Save As a new file.') elif event == '-filename-': filename = values['-filename-'] save_config(filename,createdParser,values) # Main Loop if event == 'Start': params = '' params += f"{values['mode']} -c {values['-config-']}" if values['mode'] == 'assemble': params += f" --cpu {values['cpu']} --max_mem {values['max_mem']}G" command = command_to_run + params main_window['command_line'].update(command) runCommand(cmd = command, window=main_window) main_window.close()
old usage: yolo_video.py [-h] -i INPUT -o OUTPUT -y YOLO [-c CONFIDENCE] [-t THRESHOLD] """ # import the necessary packages import numpy as np import argparse import time import cv2 import os import PySimpleGUIQt as sg layout = [ [sg.Text('YOLO')], [sg.Text('Path to image'), sg.In(r'C:/Python/PycharmProjects/YoloObjectDetection/images/baggage_claim.jpg',size=(40,1), key='image'), sg.FileBrowse()], [sg.Text('Yolo base path'), sg.In(r'yolo-coco',size=(40,1), key='yolo'), sg.FolderBrowse()], [sg.Text('Confidence'), sg.Slider(range=(0,10),orientation='h', resolution=1, default_value=5, size=(15,15), key='confidence')], [sg.Text('Threshold'), sg.Slider(range=(0,10), orientation='h', resolution=1, default_value=3, size=(15,15), key='threshold')], [sg.OK(), sg.Cancel(), sg.Stretch()] ] win = sg.Window('YOLO', default_element_size=(14,1), text_justification='right', auto_size_text=False).Layout(layout) event, values = win.Read() args = values win.Close() # construct the argument parse and parse the arguments # ap = argparse.ArgumentParser()
self.matched.titles += [titles[url_index]] if(update_index and url_index < self.current_index): count+=1 if (update_index): self.current_index = count LISTBOX_SMALL = 3 LISTBOX_BIG = 5 first_session = session_manager(session(loaded)) second_session = session_manager(None) search_info = search_manager() layout = [[sg.Text('Session to add from')], [sg.In(default_text=get_session(), size=(80, 1), key='Session2'), sg.FileBrowse(), sg.Button('Choose', key="Choose Second")], [sg.Listbox(values=[], size=(30, LISTBOX_SMALL), select_mode=sg.LISTBOX_SELECT_MODE_EXTENDED, key='_WIN2', enable_events=True), sg.Listbox(values=[], size=(60, LISTBOX_SMALL), select_mode=sg.LISTBOX_SELECT_MODE_EXTENDED, key='_TAB2', enable_events=True), sg.Listbox(values=[], size=(30, LISTBOX_SMALL), select_mode=sg.LISTBOX_SELECT_MODE_EXTENDED, key='_HIS2', enable_events=True)], [sg.Button('Add Window(s)'), sg.Button( 'Add Tab(s)'), sg.Button('Add History')], [sg.Text('Session to add to')], [sg.In(default_text=get_session(), size=(80, 1), key='Session1'), sg.FileBrowse(), sg.Button('Choose')], [sg.Listbox(values=first_session.m_session.window_listbox, size=(30, LISTBOX_BIG), select_mode=sg.LISTBOX_SELECT_MODE_EXTENDED, key='_WIN', enable_events=True), sg.Listbox(values=[], size=(60, LISTBOX_BIG), select_mode=sg.LISTBOX_SELECT_MODE_EXTENDED, key='_TAB', enable_events=True),
i_vid = r'videos\car_chase_01.mp4' o_vid = r'output\car_chase_01_out.mp4' y_path = r'yolo-coco' sg.ChangeLookAndFeel('LightGreen') layout = [ [ sg.Text('YOLO Video Player', size=(22, 1), font=('Any', 18), text_color='#1c86ee', justification='left') ], [ sg.Text('Path to input video'), sg.In(i_vid, size=(40, 1), key='input'), sg.FileBrowse() ], [ sg.Text('Optional Path to output video'), sg.In(o_vid, size=(40, 1), key='output'), sg.FileSaveAs() ], [ sg.Text('Yolo base path'), sg.In(y_path, size=(40, 1), key='yolo'), sg.FolderBrowse() ], [ sg.Text('Confidence'), sg.Slider(range=(0, 10), orientation='h',
def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) return os.path.join(base_path, relative_path) prototext = resource_path("colorization_deploy_v2.prototxt") caffemodel = resource_path("colorization_release_v2.caffemodel") npyfile = resource_path("pts_in_hull.npy") sg.ChangeLookAndFeel('Reddit') sg.set_options(button_color=("0079d3", "0079d3"), button_element_size=(10, 1), text_justification="center") col1 = [[sg.T("IMAGEM:", size=(44, 1)), sg.I(size=(0, 0), visible=False, key="img", enable_events=True), sg.FileBrowse("SELECIONAR", file_types=(("Imagem", "*.png; *.jpg; *.jpeg"),), target="img")], [sg.Image(filename=resource_path("placeholder.png"), key="img_display")]] col2 = [[sg.T('RESULTADO:', size=(44, 1)), sg.I(size=(0, 0), visible=False, key="savefile", enable_events=True), sg.B("COLORIR", key="processar")], [sg.Image(filename=resource_path("placeholder.png"), key="img_display2", )]] tab1_layout = [[sg.Column(col1), sg.Column(col2)], [sg.Exit(key="EXIT"), sg.FileSaveAs("SALVAR", file_types=(("Imagem", "*.jpg"),), target='savefile', key="savefilebrowse", disabled=True, button_color=("black","grey"))]] tab2_layout = [[sg.T('PASTA:'), sg.I(key="pasta", size=(98,1)), sg.FolderBrowse()], [sg.B("COLORIR")], [sg.Exit(key="Exit")]] layout = [[sg.T("\t\t\t\t\tCOLORIZADOR DE FOTOS EM PRETO E BRANCO", font=("Arial 12 bold"))], [sg.TabGroup([[sg.Tab('COLORIR ARQUIVO ÚNICO', tab1_layout), sg.Tab('COLORIR LOTE', tab2_layout)]])]] window = sg.Window('Monografia do vértice genérica', layout, size=(1000, 700), auto_size_text=True, auto_size_buttons=False, resizable=False)
sg.Text("Listar todas as categorias:"), sg.Button("Listar", size=(10, 1), key="con_lista_cat"), ], [sg.Listbox([], key="con_ingredientes_listbox", enable_events=True), sg.Listbox([], key="con_cat_listbox", enable_events=True)], ] ABA1_COLS = [[sg.Column(ABA1_COL1), sg.Column(ABA1_COL2)]] ABA1 = sg.Tab(title="Consultar uma receita", layout=ABA1_COLS) ABA2_COL1 = [ [sg.Text("Nome:"), sg.Input(key="in_nome")], [ sg.Text("Foto: "), sg.Input(key="in_foto"), sg.FileBrowse( "Procurar", file_types=(("Imagem", "*.jpg;*.jpeg;*.png;*.JPG;*.JPEG;*.PNG"),), size=(10, 1), ), ], [sg.Text("Ingredientes separado por vírgula. Exemplo: cebola, alho, arroz...:")], [sg.Input(key="in_ingredientes")], [sg.Text("Categorias. Exemplo: assado, salgado, doce...:")], [sg.Input(key="in_cat")], [sg.Text("Modo de preparo:")], [sg.Multiline(key="in_preparo")], [sg.Stretch(), sg.Button("Salvar", size=(10, 1), key="in_salvar"), sg.Stretch()], ] ABA2_COL2 = [ [ sg.Text("Lista de ingredientes:"), sg.Button("Listar", size=(10, 1), key="in_list_ingred"),
import PySimpleGUIQt as sg import pandas as pd import sweetviz as sv from datetime import datetime sg.theme('dark teal 9') # sg.theme_previewer() # Black, DarkTeal9, DarkBlue2, DarkGrey6 ftypes = (('Excel', '*.xls'), ('Excel', '*.xlsx')) layout = [ [sg.I('Select File', key='-FILE-'), sg.FileBrowse('Browse', file_types=ftypes)], [sg.B('OK', bind_return_key=True), sg.B('Cancel')], ] window = sg.Window('ml4all', layout, font='Any 14', element_padding=(5, 5)) def on_ok(): print(values['-FILE-']) df = pd.read_excel(values['-FILE-']) c = df.select_dtypes(include=['object']).columns df[c] = df[c].fillna('NA').apply(str) # i = df.select_dtypes(include=['int']).columns # df[i] = df[i].fillna(0).apply(int) # f = df.select_dtypes(include=['float']) # df[f] = df[f].fillna(0.0).apply(float) # d = df.select_dtypes(include=['datetime'])
# https://www.raspberrypi.org/forums/viewtopic.php?t=219201 """ import PySimpleGUI27 as sg sg.Popup('Hello From PySimpleGUI!', 'This is the shortest GUI program ever!') """ #import PySimpleGUI as sg import PySimpleGUIQt as sg #import PySimpleGUIWeb as sg layout = [[sg.Text('Filename', text_color='red')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()]] #event, values = sg.Window('Get filename example').Layout(layout).Read() window = sg.Window('Get filename example').Layout(layout) # The Event Loop while True: event, values = window.Read() if event is None: break if event == 'OK': print(values[0])
import PySimpleGUIQt as sg sg.Popup('Hello From PySimpleGUI!', 'This is the shortest GUI program ever!') # event, values = sg.Window('Get filename example', [[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()] ]).Read() sg.theme('Dark Blue 3') # please make your creations colorful layout = [[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()]] window = sg.Window('Get filename example', layout) event, values = window.Read() window.close()
yoloModelPath = Path().parent.absolute() yoloModelPath = str(yoloModelPath) + "/yoloModel/" sg.ChangeLookAndFeel('LightGrey') layout1 = [ [ sg.Text('Perform YOLO Object Detection', size=(50, 1), font=('Any', 18), text_color='#1c86ee', justification='left') ], [ sg.Text('Path to input video'), sg.In(i_vid, size=(40, 1), key='input'), sg.FileBrowse(size=(75, 30)) ], [ sg.Text('Path to output video'), sg.In(o_vid, size=(40, 1), key='output'), sg.FileSaveAs(size=(75, 30)) ], [ sg.Text('Confidence'), sg.Slider(range=(0, 10), orientation='h', resolution=1, default_value=5, size=(15, 15), key='confidence'), sg.T(' ', key='_CONF_OUT_')
key='_LISTTYPE_', enable_events=True, default_values=None, select_mode='single') ], # [sg.Combo(values=char_list, default_value='Alif', key='_COMBOBOX_', # enable_events=True,)], # [sg.Input(key='_ADDTYPEINPUT_', enable_events=True, # background_color='brown', size=(10, 0.7), disabled=True), # sg.FileBrowse(file_types=(("image", "*png"), ('img', "*jpg")), # initial_folder=None, enable_events=True, button_text='Add Type', # size=(8, 0.8), key='_ADDTYPE_', disabled=True), [ sg.Input(key='_INPUT_', enable_events=True, background_color='white'), sg.FileBrowse(file_types=(("image", "*png"), ('img', "*jpg")), initial_folder=None, enable_events=True, size=(7, 0.8)) ], [ sg.Button('Delete', size=(7, 1), disabled=True, key='_DELBUTTON_', button_color=('gray', 'gray')), sg.Checkbox('', key='_LOCKDEL_', enable_events=True, background_color='Dark Grey'), # sg.Text('', justification='left'), sg.Image(key='_IMAGE_', filename=empty_image,
# ------ Column Definition ------ # column1 = [ [sg.Text('Column 1', background_color='lightblue', text_color='black', justification='center', size=(100, 22))], [sg.Spin((1, 10), size=(100, 22))], [sg.Spin((1, 10), size=(100, 22))], [sg.Spin((1, 10), size=(100, 22))], ] if os.path.isfile('full collection.xlsx'): filename = 'full collection.xlsx' else: filename = 'Default File' layout = [ [sg.Text('Select the file you want to format:')], [sg.Text('Your File'), sg.InputText(filename, size=(300, 50)), sg.FileBrowse(), sg.Stretch()], [sg.Submit(tooltip='Click to submit this form', ), sg.Cancel()]] window = sg.Window('Collection Manager', grab_anywhere=False, font=('Helvetica', 12), no_titlebar=False, alpha_channel=1, keep_on_top=False, element_padding=(2, 3), default_element_size=(100, 23), default_button_element_size=(120, 30), # background_image='colors.png', ).Layout(layout) event, values = window.Read() print(event, values)
def main(): sg.theme('Reddit') layout = [[sg.Text('', font=('Times', 12), key='timer')], [ sg.Text('Input Audio', size=(10, 1), font='Times 14'), sg.InputText(key="audioIN", size=(50, 1)), sg.FileBrowse(initial_folder="/home", target="audioIN") ], [ sg.Text('Input Data', size=(10, 1), font='Times 14'), sg.InputText(key="dataIN", size=(50, 1)), sg.FileBrowse(initial_folder="/home", target="dataIN") ], [ sg.Text('Encode To', size=(10, 1), font='Times 14'), sg.InputText(key="audioOUT", size=(50, 1)), sg.FolderBrowse(initial_folder="/home", target="audioOUT") ], [ sg.Submit('Encode', size=(10, 1)), sg.Submit('Datafy', size=(10, 1)), sg.Cancel('Quit', size=(10, 1)) ]] window = sg.Window('mrmp3', layout) ####### Main Event Loop ######## while True: event, values = window.read() if event == sg.WIN_CLOSED or event == "Quit": break ######### When User hits "Encode" button ######### if event == "Encode": ## Get time for timing encoding start_time = int(round(time.time() * 100)) ## Get variables for encodeMP3 call input_audio = values["audioIN"] input_data = values["dataIN"] output_audio = values["audioOUT"] output_data = get_file(input_data) ## Update window to prepare for processing window['timer'].Update('Processing...') window.Refresh() ## Call ffmpeg to encode to mp3 emp3.encodeMP3(input_audio, output_data, output_audio) ## Calculate and report encoding completion time final_time = int(round(time.time() * 100)) - start_time format_time = '{:02d}:{:02d}.{:02d}'.format( (final_time // 100) // 60, (final_time // 100) % 60, final_time % 100) window['timer'].update(f"Encoded in {format_time}.") ######### When User hits "Datafy" button ######### if event == "Datafy": ## Get time for timing encoding start_time = int(round(time.time() * 100)) ## Get variables for dataMP3 call input_audio = values["audioIN"] input_data = values["dataIN"] output_audio = values["audioOUT"] ## Update window to prepare for processing window['timer'].Update('Processing...') window.Refresh() if values["audioIN"] == values["audioOUT"]: window['timer'].update( "WARNING: Output file cannot be same as input.") window.Refresh() else: ## Make ffmpeg-readable data file output_data = get_file(input_data) ## Call ffmpeg to add data to mp3 emp3.dataMP3(input_audio, output_data, output_audio) ## Calculate and report encoding completion time final_time = int(round(time.time() * 100)) - start_time format_time = '{:02d}:{:02d}.{:02d}'.format( (final_time // 100) // 60, (final_time // 100) % 60, final_time % 100) window['timer'].update(f"Data added in {format_time}.") window.close()
# Check if there is already an existing Sessions XML File, if there is, Load it, if there isn't, Create one if path.isfile("sessions.xml") is False: print("Sessions File does not exist") saveSessions(sessionsList) else: print("Sessions File exists") sessionsList = loadSessions() sessionsListBox = formatSessionsValues(sessionsList) # Window Layout declarations game_layout = [ [sg.Text("Oblige Executable")], [sg.InputText(default_text=configList[0], key="oblige", do_not_clear=True), sg.FileBrowse(target="oblige")], [sg.Text("Oblige Config")], [sg.InputText(default_text=configList[1], key="oblige_config", do_not_clear=True), sg.FileBrowse( target="oblige_config", file_types=(("Text Files", "*.txt"),))], [sg.Text("Source Port")], [sg.InputText(default_text=configList[2], key="source_port", do_not_clear=True), sg.FileBrowse(target="source_port")], [sg.Text("IWAD")], [sg.InputText(default_text=configList[3], key="iwad", do_not_clear=True), sg.FileBrowse( target="iwad", file_types=(("IWAD Files", "*.wad"),))] ] mod_layout = [ [sg.Listbox(key="pwads", values=pwadList, size=(50, 5))], [sg.FilesBrowse("Add", key="Add", target=( "Add"), enable_events=True, file_types=(("PWAD Files", "*.wad;*.pk3"),)), sg.Button("Remove"), sg.Button("Clear"), sg.Text("", visible=False), sg.Button("▲"), sg.Button("▼")]
def the_gui(): """Starts and executes the GUI Returns when the user exits / closes the window """ ffmpeg_path = Path('ffmpeg_hevc.exe') settings_path = Path("settings.json") presets = { 0: "placebo", 1: "placebo", 2: "placebo", 3: "placebo", 4: "veryslow", 5: "slower", 6: "slow", 7: "medium", 8: "fast", 9: "faster", 10: "veryfast", 11: "superfast", 12: "ultrafast" } # queue used to communicate between the gui and the threads gui_queue = queue.Queue() encode_queue = queue.Queue() encode_list = [] encode_event = queue.Queue( ) # queue for handling when encodes finish and start # Define default settings to make it possible to generate settings.json settings = {"settings": {"theme": "Default1"}} status_deque = deque(maxlen=1) # deque for handling the status bar element check_paths(ffmpeg_path, gui_queue) # Load settings from json if it exist if settings_path.exists(): with settings_path.open() as file: settings = json.load(file) sg.change_look_and_feel(settings["settings"]["theme"]) else: print("Could not find settings.json") write_settings(settings_path, settings) tooltips = { # ENCODE "tune": "0 = visual quality, 1 = psnr/ssim, 2 = vmaf", "preset": "Trades speed for quality and compression.\n'Veryfast' and up only works for 1080p or higher, while 'ultrafast' and 'superfast' is 4k and higher only.\nYou might have a file that is just a few pixels away fitting 1080p, and you will be limited to the 'faster' preset or slower\nBest to stay around medium unless you have a godly pc/trash pc", "drc": "Enables variable bitrate. Lets the encoder vary the targeted quality. \nIf you are unsure, leave it off", "qmin": "Minimum quality level in DRC mode. Must be lower than qmax", "qmax": "Maximum quality level in DRC mode. Must be higher than qmin", "qp": "The quality the encoder will target. Lower values result in higher quality, but much larger filesize. \nUsually stay around 20 for h.264 content, but can often go lower for mpeg2 content. Recommend 22 or 23 for 1080p with high bitrate. \nExperiment with quality by enabling test encode!", # FILTERS "sharpen": "How much to sharpen the image with unsharp, with a moderate impact to encode speed. \nIt is usually a good idea to sharpen the image a bit when transcoding. I recommend about 0.2 to 0.3", # AUDIO "skip_audio": "Enable to skip all audio tracks. Disable to passthrough audio", # BUTTONS "pause_queue": "Once the queue is paused the current job will finish, but the next job will not be started.", "start_encode": "Add job to queue, start it if no encode is currently running.", # MISC "test_encode": "Only encode part of the video. Lets you compare quality of encode to source, and estimate filesize. \nSpecify how many frames, usually 1000 is enough" } params = { "input": "", "output": "", "skip_audio": "", "qp": 20, "subtitles": False, "enable_filters": "-vf", "drc": 0, "qmin": 19, "qmax": 21, "sharpen_mode": "", "crop": "", "tune": 0, "preset": 7, "test_encode": "", "n_frames": "1000", "start_time": "00:00:00.000", "end_time": "", } old_params = params.copy() video_metadata = { "contains_video": False, "frame_count": None, "size": None, "fps": None, "duration": None, "width": None, "height": None, } menu_def = [['&Settings', ['&Themes', '!&Preferences', '---', 'E&xit']], ['&Presets', ['!&Save preset', '---', '!Preset1']]] drc_col = [ [ sg.Checkbox("Dynamic rate control", key="-DRC-", enable_events=True, tooltip=tooltips["drc"]) ], [ sg.Text("minQP", size=(5, 1), tooltip=tooltips["qmin"]), sg.Spin([i for i in range(1, 51)], initial_value=params["qmin"], key="-QMIN-", size=(5, 1), enable_events=True, disabled=True, tooltip=tooltips["qmin"]), sg.Text("maxQP", size=(5, 1), tooltip=tooltips["qmax"]), sg.Spin([i for i in range(1, 51)], initial_value=params["qmax"], key="-QMAX-", size=(5, 1), enable_events=True, disabled=True, tooltip=tooltips["qmax"]), ], ] encoding_col = [ [ sg.Column([ [sg.Text("Quality", tooltip=tooltips["qp"])], [ sg.Text("QP", size=(2, 1)), sg.Spin([i for i in range(1, 51)], initial_value=params["qp"], key="-QP-", size=(5, 1), enable_events=True, tooltip=tooltips["qp"]) ], ]), sg.VerticalSeparator(), sg.Column(drc_col), sg.VerticalSeparator(), sg.Column([[ sg.Text("Preset (medium)", size=(10, 1), key="-PRESET_TEXT-", tooltip=tooltips["preset"]) ], [ sg.Slider(range=(0, 12), default_value=7, orientation="horizontal", key="-PRESET-", enable_events=True, tooltip=tooltips["preset"]) ]]), # sg.Column([[sg.Text("Tune", size=(5, 1), tooltip=tooltips["tune"])], [sg.DropDown([0, 1, 2], default_value=0, key="-TUNE-", enable_events=True, tooltip=tooltips["tune"])]]) # Tune is no longer an option ], ] audio_col = [[ sg.Checkbox("Skip audio", key="-AUDIO-", enable_events=True, default=False, tooltip=tooltips["skip_audio"]) ]] def range_with_floats(start, stop, step): """Func for generating a range of decimals""" while stop > start: yield round( start, 2) # adding round() to our function and rounding to 2 digits start += step filter_col = [[ sg.Checkbox("Sharpen", key="-SHARP_CONTROL-", size=(8, 1), enable_events=True, tooltip=tooltips["sharpen"]), sg.Spin([i for i in range_with_floats(-1.50, 1.50, 0.05)], key="-SHARPEN-", initial_value=0.25, size=(6, 1), enable_events=True, disabled=True, tooltip=tooltips["sharpen"]) ]] video_col = [[ sg.T("Resolution"), sg.Input(default_text="WDxHG", disabled=True, key="-RESOLUTION-"), sg.T("Crop"), sg.Input(key="-CROP-", enable_events=True), sg.Button("Autocrop") ]] layout = [ [sg.Menu(menu_def)], [sg.Text("Browse or drag n drop video file")], [ sg.Text("Input"), sg.Input(key="-INPUT-", enable_events=True), sg.FileBrowse(enable_events=True) ], # [ sg.Text("Output"), sg.Input(key="-OUTPUT-", enable_events=True), sg.SaveAs(enable_events=True) ], [sg.Frame("Encode options", encoding_col)], [ sg.Frame("Audio options", audio_col), sg.Frame("Filters", filter_col) ], [sg.Frame("Video", video_col)], [ sg.Frame("Misc", [[ sg.Checkbox("Test encode (n frames)", size=(16, 1), key="-TEST_ENCODE-", enable_events=True, tooltip=tooltips["test_encode"]), sg.Input(default_text=params["n_frames"], size=(5, 1), enable_events=True, key="-TEST_FRAMES-", disabled=True, tooltip=tooltips["test_encode"]) ], [ sg.T("Start time", size=(7, 1)), sg.Input(default_text=params["start_time"], enable_events=True, key="-START_TIME-", size=(9, 1), tooltip="Start timestamp"), sg.T("End time", size=(6, 1)), sg.Input(default_text="00:00:00.000", enable_events=True, key="-END_TIME-", size=(9, 1), tooltip="End timestamp") ]]) ], # [sg.Frame("Command", [[sg.Column([[sg.Multiline(key="-COMMAND-", size=(60, 3))]])]])], [ sg.Frame("Queue", [[ sg.Column([[sg.Listbox(values=[], key="-QUEUE_DISPLAY-")], [ sg.Button("Remove task", size=(15, 1)), sg.Button("UP", size=(7, 1)), sg.Button("DOWN", size=(7, 1)) ]]) ]]) ], [ sg.Button("Start encode / add to queue", key="Start encode", size=(20, 1), tooltip=tooltips["start_encode"]), sg.Button("Stop encode", size=(20, 1)), sg.Button("Pause queue", key="Pause queue", size=(20, 1), tooltip=tooltips["pause_queue"]) ], [sg.T("", key="-STATUS_BOX-")], [sg.Output()], # Disable this line to get output to the console # [sg.ProgressBar(100, key="-PROGRESSBAR-")], [sg.Button('Exit')], ] window = sg.Window('SVT_GUI', layout) encoder = threading.Thread(target=encode_thread, args=(encode_queue, gui_queue, status_deque, encode_event), daemon=True) try: encoder.start() except Exception as e: print('Error starting work thread. Bad input?\n ' + str(e)) encode_queue_active.set() # Start active # progressbar = window["-PROGRESSBAR-"] def update_command(): window["-COMMAND-"].update(' '.join(format_command())) def format_command(): input_text = "" output_text = "" if params["input"] != "": input_path = Path(params["input"]) input_text = str(input_path) if params["output"] != "": output_path = Path(params["output"]) output_text = str(output_path) enable_filters = params[ "enable_filters"] if params["sharpen_mode"] != "" or params[ "crop"] else "" # todo: Add check for each filter here filters = ",".join( filter(None, [params["sharpen_mode"], params["crop"]])) print("filters: " + (filters if filters else "None")) n_frames = params["n_frames"] if params[ "test_encode"] != "" else "" # Disable vframes number if we dont want to do test encode # Filter list before return to remove empty strings return list( filter(None, [ "-i", input_text, "-y", "-ss", params["start_time"], ("-to" if params["end_time"] else ""), params["end_time"], "-sn", params["skip_audio"], "-map", "0", enable_filters, filters, "-c:v", "libsvt_hevc", params["test_encode"], n_frames, "-rc", str(params["drc"]), "-qmin", str(params["qmin"]), "-qmax", str(params["qmax"]), "-qp", str(params["qp"]), "-preset", str(params["preset"]), output_text ])) def toggle_queue(): if encode_queue_active.is_set(): encode_queue_active.clear() window.Element("Pause queue").update("Unpause Queue") else: encode_queue_active.set() window.Element("Pause queue").update("Pause Queue") def pause_queue(): if encode_queue_active.is_set(): encode_queue_active.clear() window.Element("Pause queue").update("Unpause Queue") def autocrop(): try: # TODO: If the video is shorter than around 16 seconds we might not get any crop values because of the low framerate and start time start_time = int( (video_metadata["duration"] / 4) / 1000) # Start detecting crop at 1/4 of the video duration command = [ ffmpeg_path.absolute().as_posix(), "-ss", str(start_time), "-i", str(Path(params["input"])), "-t", "01:20", "-vsync", "vfr", "-vf", "fps=0.2,cropdetect", "-f", "null", "-" ] process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, close_fds=True) # out, err = process.communicate() crop_values = [] for line in process.stdout: # print(line) if "crop=" in line: crop_values.append(line.split("crop=")[1]) if len(crop_values) > 0: most_common = max(set(crop_values), key=crop_values.count) print("CROP: " + most_common) if most_common: return most_common else: print("Could not generate a crop :(") return "" except Exception as ex: print(ex.args) print("Could not generate a crop :(") return "" def update_queue_display(): window.Element("-QUEUE_DISPLAY-").update(values=[ i["status"] + " | " + i["title"] + " - " + i["uuid"] for i in encode_list ]) def build_encode_queue(): clear_queue(encode_queue) for i in encode_list: if i["status"] == "⏱ waiting": encode_queue.put(i) # # # --------------------- EVENT LOOP --------------------- # while True: event, values = window.read(timeout=100) if event in (None, 'Exit'): break elif event == "-INPUT-": window.Element("-INPUT-").update( background_color="white") # Reset background color file_string = values["-INPUT-"].replace("file:///", "") input_file = Path(file_string) if input_file.exists() and input_file.is_file(): params["input"] = input_file.absolute() # Update params # Fill in output based on folder and filename of input new_file = input_file while new_file.exists(): new_file = Path( new_file.with_name(new_file.stem + "_new.mkv")) params["output"] = str(new_file.absolute()) window.Element("-OUTPUT-").update(str(new_file.absolute())) print("** Analyzing input using mediainfo... **") media_info = MediaInfo.parse(str(input_file.absolute())) for track in media_info.tracks: if track: if track.track_type == "General": video_metadata["name"] = track.file_name_extension elif track.track_type == 'Video': video_metadata["contains_video"] = True video_metadata["frame_count"] = track.frame_count video_metadata["size"] = int( track.stream_size ) / 1048576 if track.stream_size else None # in MiB video_metadata["fps"] = track.frame_rate video_metadata["width"] = track.width video_metadata["height"] = track.height # Reset the start and end time params params["end_time"] = "" params["start_time"] = "00:00:00.000" if track.height and track.width: window.Element("-RESOLUTION-").update( "%ix%i" % (track.width, track.height)) if track.duration: video_metadata["duration"] = float( track.duration) # hours, rem = divmod(float(track.duration), 3600) # minutes, seconds = divmod(rem, 60) milliseconds = float(track.duration) seconds = (milliseconds / 1000) % 60 minutes = int( (milliseconds / (1000 * 60)) % 60) hours = int( (milliseconds / (1000 * 60 * 60)) % 24) formatted_duration = "{:0>2}:{:0>2}:{:06.3f}".format( hours, minutes, seconds) print("Duration:", formatted_duration) window.Element("-END_TIME-").update( disabled=False) window.Element("-END_TIME-").update( formatted_duration) else: window.Element("-END_TIME-").update( disabled=True) if video_metadata["frame_count"] is None and video_metadata[ "contains_video"]: print( "Could not extract frame count, will not be able to report progress %" ) if not video_metadata["contains_video"]: print( "This file is either not a video file or does not contain a video stream." ) window.Element("-INPUT-").update(background_color="red") print('** Analyze done **') else: print("Can't find file: " + str(input_file.absolute())) elif event == "-OUTPUT-": if values[ "-OUTPUT-"] == "": # If the user clicks the saveAs button and cancels, the output string will be empty. Better to keep the old value in that case window.Element("-OUTPUT-").update(params["output"]) else: file_string = values["-OUTPUT-"].replace("file:///", "") params["output"] = file_string ################## # ENCODE SETTINGS elif event == "-QP-": params["qp"] = values["-QP-"] elif event == "-DRC-": val = values["-DRC-"] if val: params["drc"] = 1 window.Element("-QMIN-").update(disabled=False) window.Element("-QMAX-").update(disabled=False) window.Element("-QP-").update(disabled=True) else: params["drc"] = 0 window.Element("-QMIN-").update(disabled=True) window.Element("-QMAX-").update(disabled=True) window.Element("-QP-").update(disabled=False) elif event == "-PRESET-": # TODO: handle limiting preset by resolution as per https://github.com/OpenVisualCloud/SVT-HEVC/blob/master/Docs/svt-hevc_encoder_user_guide.md#encoding-presets-table window.Element("-PRESET_TEXT-").update("Preset ({})".format( presets[values["-PRESET-"]])) params["preset"] = values["-PRESET-"] elif event == "-TEST_ENCODE-": val = values["-TEST_ENCODE-"] if val: window.Element("-TEST_FRAMES-").update(disabled=False) params["test_encode"] = "-vframes" else: window.Element("-TEST_FRAMES-").update(disabled=True) params["test_encode"] = "" elif event == "-TEST_FRAMES-": val = ''.join( i for i in values["-TEST_FRAMES-"] if i.isdigit()) # Remove any non numbers from the input window.Element("-TEST_FRAMES-").update(val) params["n_frames"] = val elif event == "-START_TIME-": params["start_time"] = values["-START_TIME-"] elif event == "-END_TIME-": params["end_time"] = values["-END_TIME-"] ################## # AUDIO SETTINGS elif event == "-AUDIO-": if values["-AUDIO-"]: params["skip_audio"] = "-an" else: params["skip_audio"] = "" ################## # FILTER SETTINGS elif event == "-SHARPEN-": params["sharpen_mode"] = "unsharp=5:5:{}:5:5:{}".format( values["-SHARPEN-"], values["-SHARPEN-"]) elif event == "-CROP-": if values["-CROP-"]: params["crop"] = "crop=" + values["-CROP-"] else: params["crop"] = "" elif event == "-SHARP_CONTROL-": if values["-SHARP_CONTROL-"]: window.Element("-SHARPEN-").update(disabled=False) params["sharpen_mode"] = "unsharp=5:5:{}:5:5:{}".format( values["-SHARPEN-"], values["-SHARPEN-"]) else: window.Element("-SHARPEN-").update(disabled=True) params["sharpen_mode"] = "" ################## # QUEUE BUTTONS elif event == "Remove task": if values["-QUEUE_DISPLAY-"]: for queue_item in values[ "-QUEUE_DISPLAY-"]: # TODO: make alternative to nesting loops job_id = queue_item.split()[-1] for i, job in enumerate(encode_list): if job["uuid"] == job_id and job[ "status"] != "▶ started": encode_list.pop(i) build_encode_queue() update_queue_display() elif event == "UP": if values["-QUEUE_DISPLAY-"] and len( values["-QUEUE_DISPLAY-"]) == 1 and len(encode_list) > 1: job_id = values["-QUEUE_DISPLAY-"][0].split()[-1] for i, job in enumerate(encode_list): if job["uuid"] == job_id and i != 0: encode_list.insert(i - 1, encode_list.pop(i)) build_encode_queue() update_queue_display() elif event == "DOWN": if values["-QUEUE_DISPLAY-"] and len( values["-QUEUE_DISPLAY-"]) == 1 and len(encode_list) > 1: job_id = values["-QUEUE_DISPLAY-"][0].split()[-1] for i, job in enumerate(encode_list): if job["uuid"] == job_id and i != len(encode_list) - 1: encode_list.insert(i + 1, encode_list.pop(i)) build_encode_queue() update_queue_display() ################## # OTHER INTERACTS elif event == "Start encode": if not params["input"] or params["input"] == "": print("Missing input") elif not params["output"] or params["output"] == "": print("Missing output") elif not video_metadata["contains_video"]: print( "Cannot start encode because input file does not have a video track" ) else: finished_command = [ffmpeg_path.absolute().as_posix() ] + format_command() try: job_id = uuid.uuid4().hex encode_list.append({ "title": video_metadata["name"], "uuid": job_id, "status": "⏱ waiting", "output_file": Path(params["output"]), "command": finished_command, "metadata": video_metadata, "test_encode": int(params["n_frames"]) if params["test_encode"] != "" else False }) build_encode_queue() update_queue_display() except Exception as e: # TODO: make this better. Is it even needed? print('Error adding job. Bad input?:\n "%s"' % finished_command) elif event == "Stop encode": if encoder is not None: stoprequest.set() pause_queue() elif event == "Pause queue": toggle_queue() encode_queue.put(_skip) elif event == "Autocrop": crop = autocrop() params["crop"] = "crop=" + crop window.Element("-CROP-").update(crop) elif event == "Themes": theme = run_themes_window() # Save theme if theme and settings_path.exists(): settings["settings"]["theme"] = theme write_settings(settings_path, settings) print("Changed theme to {}. Restart the program to apply.". format(theme)) try: window.Element("-STATUS_BOX-").update(status_deque.popleft()) except IndexError: pass # --------------- Check for incoming messages from threads --------------- try: message = gui_queue.get_nowait() except queue.Empty: # get_nowait() will get exception when Queue is empty message = None # break from the loop if no more messages are queued up try: # Check for job events event = encode_event.get_nowait() print(event) for i, job in enumerate(encode_list): if job["uuid"] == event["uuid"]: item = encode_list[i] item["status"] = event["event"] encode_list[i] = item update_queue_display() except queue.Empty: pass # if message received from queue, display the message in the Window if message: print("#> " + message) # Update display of the encode command # if params.items() != old_params.items(): # update_command() # old_params = params.copy() # We have reached the end of the program, so lets clean up. window.disable() window.refresh() # have to refresh window manually outside of event loop if encoder is not None: stoprequest.set() # Clear queue then add sentinel to make thread stop waiting clear_queue(encode_queue) encode_queue.put(_sentinel) encode_queue_active.set( ) # We have to make sure the encode queue is active for it to finish, if not it will keep waiting print("\n** Taking a sec to shut everything down... **\n") window.refresh() encoder.join() if encoder.is_alive(): print("Thread still alive! wtf") window.refresh() window.close()
size=(150, 30)) ]]) ] waypoint_frame = [ sg.Frame('Waypoint', [ [ sg.Text('Waypoint path: ', pad=(20, 20)), sg.InputText(key='save_waypoint'), sg.Button('Record waypoint', size=BUTTON_SIZE), sg.Button('Stop record', size=BUTTON_SIZE) ], [ sg.Text('Open waypoint'), sg.InputText(key='waypoint', enable_events=True), sg.FileBrowse(key='Browse', size=BUTTON_SIZE) ], ]) ] waypoints_loaded = {} lines = {} for meta in WAYPOINT_META: line = sg.Multiline() lines[meta] = line loaded = [sg.Frame(meta.capitalize(), [[line]])] waypoints_loaded[meta] = loaded waypoint_loaded_frame = [ sg.Frame('Loaded waypoints', waypoints_loaded.values()) ]