def HowDoI(): ''' Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle Excellent example of 2 GUI concepts 1. Output Element that will show text in a scrolled window 2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but doesn't close the form :return: never returns ''' # ------- Make a new Window ------- # sg.ChangeLookAndFeel('GreenTan') # give our form a spiffy set of colors layout = [ [sg.Text('Ask and your answer will appear here....')], [sg.Output(size=(900, 500), font=('Courier', 10))], [ sg.Spin(values=(1, 4), initial_value=1, size=(50, 25), key='Num Answers', font=('Helvetica', 15)), sg.Text('Num Answers',font=('Helvetica', 15), size=(170,22)), sg.Checkbox('Display Full Text', key='full text', font=('Helvetica', 15), size=(200,22)), sg.T('Command History', font=('Helvetica', 15)), sg.T('', size=(100,25), text_color=sg.BLUES[0], key='history'), sg.Stretch()], [sg.Multiline(size=(600, 100), enter_submits=True, focus=True, key='query', do_not_clear=False), sg.Stretch(), sg.ReadButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True), sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0])), sg.Stretch()] ] window = sg.Window('How Do I ??', default_element_size=(100, 25), # element_padding=(10,10), icon=DEFAULT_ICON, font=('Helvetica',14), default_button_element_size=(70,50), return_keyboard_events=True, no_titlebar=False, grab_anywhere=True,) window.Layout(layout) # ---===--- Loop taking in user input and using it to query HowDoI --- # command_history = [] history_offset = 0 while True: event, values = window.Read() if event in ['SEND', 'query']: # window.FindElement('+OUTPUT+').Update('test of output') # manually clear input because keyboard events blocks clear query = values['query'].rstrip() # print(query) QueryHowDoI(query, values['Num Answers'], values['full text']) # send the string to HowDoI command_history.append(query) history_offset = len(command_history)-1 window.FindElement('query').Update('') # manually clear input because keyboard events blocks clear window.FindElement('history').Update('\n'.join(command_history[-3:])) elif event is None or event == 'EXIT': # if exit button or closed using X break elif 'Up' in event and len(command_history): # scroll back in history command = command_history[history_offset] history_offset -= 1 * (history_offset > 0) # decrement is not zero window.FindElement('query').Update(command) elif 'Down' in event and len(command_history): # scroll forward in history history_offset += 1 * (history_offset < len(command_history)-1) # increment up to end of list command = command_history[history_offset] window.FindElement('query').Update(command) elif 'Escape' in event: # clear currently line window.FindElement('query').Update('')
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 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()
sg.T(""), sg.T(""), sg.T(""), sg.T("") ], [ sg.T(" FOLDER: "), sg.I(key="pasta", size=(46, 0.9)), sg.FolderBrowse("BROWSE", size=(10, 0.95)) ], [ sg.T(size=(20, 1)), sg.B("RUN", size=(8, 0.9)), sg.B("STOP", disabled=True, size=(8, 0.9)), sg.B("EXIT", size=(8, 0.9)) ], [sg.Output(background_color="Black", text_color="White")]] window = sg.Window('File Sharing System', resizable=False, size=(600, 300)).layout(Layout) def terminate_thread(thread): if not thread.is_alive(): return exc = ctypes.py_object(SystemExit) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(thread.ident), exc) if res == 0: raise ValueError("nonexistent thread id") elif res > 1:
upper_menu_layout = [ ['Help', 'About'], ] # Application General Layout layout = [[sg.Menu(upper_menu_layout)], [sg.Text('First select which protocol do you want to use: ')], [ sg.Checkbox('HTTP', key='http', enable_events=True), sg.Checkbox('Raw TCP', key='tcp', enable_events=True) ], tcp_frame, http_frame, [ sg.Frame('STATUS LOG', layout=[ [sg.Output(size=(40, 15), key='-OUTPUT-')], ]) ], [sg.Button('Submit'), sg.Button('Clear log')]] upper_menu_layout = [['Help'], ['About']] # Create the window window = sg.Window('RSTEG TCP', layout, location=(1920 / 3, 1080 / 3), auto_size_text=14) # Render flags http_visible_flag = False tcp_visible_flag = False post_details_flag = False
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()
[ sg.Text('Checkbox', size=(200, 35)), sg.Checkbox('Checkbox', change_submits=True) ], [sg.Text('RadioButton', size=(200, 35)), sg.Radio('Radio Button', 1)], [sg.Text('Slider', size=(200, 35)), sg.Slider(orientation='h')], [sg.Text('Button', size=(200, 35)), sg.Button('Button')], [sg.Text('Table', size=(200, 35)), sg.Table([[0, 1, 3, 4]])], [ sg.Text('Frame', size=(200, 35)), sg.Frame('Frame', [[sg.T('')], [sg.T('')]]) ], [sg.Text('Stdout Output', size=(200, 35)), sg.Output(size=(200, 75))], [sg.Text('Dial', size=(200, 35)), sg.Dial(size=(150, 75)), sg.Stretch()], [sg.Button('Blank'), sg.Button('Exit')] ] window = sg.Window('Window Title', font=('Helvetica', 13)).Layout(layout) while True: # Event Loop event, values = window.Read() print(event, values) if event is None or event == 'Exit': break window.Close()
key='Saida', tooltip='Local onde as pastas contendo os documentos estão.'), sg.FolderBrowse("PASTA", size=(8, 1), tooltip='Procurar pasta.'), sg.Stretch() ], [sg.B('EXECUTAR', tooltip='Executar análise.', key='exec', size=(10, 1))], [ sg.T("MENSAGENS:", size=(14, 1), tooltip='Mensagens provindas do processo executado.'), sg.Stretch(), sg.B("MODO DE USAR", key='usar', tooltip='Descrição do preenchimento de cada campo.', size=(15, 1)) ], [sg.Output(key='out')], [ sg.B("LIMPAR", key='limpar', size=(10, 1), tooltip="Limpa o texto da caixa de mensagens."), sg.ProgressBar(max_value=100, key="prog", orientation="h") ] ] window = sg.Window("COPIADOR DE ARQUIVOS", size=(800, 480)).Layout(layout) def func(): files = glob(PASTA_PA + "\\**\\*.{0}".format(EXT), recursive=True) print("Iniciando cópia...\n")
sg.change_look_and_feel('DarkBlue1') #colour layout = [[sg.Text('| -N- | Sample space:'), sg.InputText(key='-N-')], [sg.Text('| -P- | Success rate: '), sg.InputText(key='-P-')], [sg.Text('| -K- | Number of successes:'), sg.InputText(key='-K-')], [sg.Text('Choose an operation: ')], [ sg.Radio('=', 1, key=r_keys[0], default=True), sg.Radio('<', 1, key=r_keys[1]), sg.Radio('<=', 1, key=r_keys[2]), sg.Radio('>', 1, key=r_keys[3]), sg.Radio('>=', 1, key=r_keys[4]) ], [sg.Button('Calculate'), sg.Button('Clear'), sg.Button('Exit')], [sg.Output(size=(30, 10), key='_output_')]] window = sg.Window('Binomial Calculator', layout) #makes window while True: event, values = window.read() n = values['-N-'] p = values['-P-'] k = values['-K-'] op = [key for key in r_keys if values[key]][0] if event in (None, 'Exit'): window.close() if event == 'Calculate': try: print(calcProb(int(n), float(p), int(k), op))
[ sg.Button( " Start Converting ", tooltip= "This will convert the images to text, it may take a minute depending on PC speed and number of decos", key="convertButton"), sg.Button( " Export (fix errors first!) ", tooltip="FIX ANY ERRORS BEFORE PRESSING THIS OR IT WONT WORK!!!!!", key="exportButton") ], [ sg.Text("Progress:"), sg.ProgressBar(100, orientation="h", key="bar"), sg.Text("0/X", key="bartext") ], [sg.Output()], [sg.Button("Exit")] ] window = sg.Window("MHW Deco Exporter", location=(800, 400)) window.Layout(layout).Finalize() # the region caprture method, isnt used if defaultregion() is used instead def capture(): global x1, y1, drawing, num, img, img2, x2, y2 x1, y1, x2, y2 = 0, 0, 0, 0 drawing = False