예제 #1
0
def _layout_(config):
    import PySimpleGUIQt as qt
    struct = [[qt.Menu(_top_menu_())], [qt.Text('Welcome to Test API!')],
              [qt.Combo(['Living Room', 'Playroom'])],
              [qt.Frame('', _sense_frame_(config))],
              [qt.Frame('', list(_button_frame_()))]]

    return struct
예제 #2
0
    def render(self):
        sg.theme('dark')
        menu_def = [['File', [PREFERENCES_MENU]]]
        layout = [[sg.Menu(menu_def, background_color='white')],
                  [sg.Text(WELCOME_TEXT)],
                  [self.start_stop_button]]

        window = sg.Window("Captionizer", layout, element_padding=(16, 16))
        self._event_loop(window)
        window.close()
예제 #3
0
def make_layout():
    layout = [
        [sg.Menu(make_menu(), key="-menu-")],
        [sg.Stretch(), sg.Text("Star Wars Dice Roller", font=FONT_HEADING), sg.Stretch()],
        [sg.HorizontalSeparator()]
    ]
    active = 0
    col_layout = [[],[]]
    for stat,val in character["stats"].items():
        col_layout[active].extend(make_stat_section(stat,val))
        if active == 0:
            active = 1
        else:
            active = 0
    layout.append([
        sg.Column(layout=col_layout[0]),
        sg.Column(layout=col_layout[1]),
        sg.Column(layout=[
            [sg.HorizontalSeparator(),],
            [
                sg.Stretch(),
                sg.Text(text="Action Modifiers", font=FONT_HEADING),
                sg.Stretch(),
            ],
            [
                sg.Text(text="Advantages",font=FONT_STAT),
                sg.Stretch(),
                sg.Slider(range=(0,5), default_value=0,orientation="h",size=(45, 10),key="adv",background_color="skyblue",enable_events=True),
                sg.Text(text="+",font=FONT_LOG),
                sg.Text(text="0", key="curr_adv",font=FONT_LOG),
                sg.Text(text="d",font=FONT_LOG),
            ],
            [
                sg.Text(text="Penalties",font=FONT_STAT),
                sg.Stretch(),
                sg.Slider(range=(0,5), default_value=0,orientation="h",size=(45, 10),key="pen",background_color="pink",enable_events=True),
                sg.Text(text="-",font=FONT_LOG),
                sg.Text(text="0", key="curr_pen",font=FONT_LOG),
                sg.Text(text="d",font=FONT_LOG),
            ],
            [sg.HorizontalSeparator(),],
            [sg.Text(text="Result", font=FONT_HEADING),sg.Stretch()],
            [sg.Text(text="Roll something!",key="-result-",font=FONT_RESULT,size_px=(650,100) , relief=sg.RELIEF_RIDGE)],
            [sg.HorizontalSeparator()],
            [sg.Text(text="Results Log", font=FONT_HEADING),sg.Stretch()],
            [sg.Text(text="",key="-resultlog-",font=FONT_LOG,relief=sg.RELIEF_SUNKEN)],
        ],size=(90,90)),
        sg.Column(layout=make_weapon_section(character["weapons"]))
    ])
    return layout
예제 #4
0
def make_edit_layout():
    layout = [
        [sg.Menu(make_menu(), key="-menu-")],
        [sg.Stretch(), sg.Text("Star Wars Dice Roller", font=FONT_HEADING), sg.Stretch()],
        [sg.HorizontalSeparator()]
    ]
    active = 0
    col_layout = [[],[]]
    for stat,val in character["stats"].items():
        col_layout[active].extend(make_edit_stat_section(stat,val))
        if active == 0:
            active = 1
        else:
            active = 0
    layout.append([
        sg.Column(layout=col_layout[0]),
        sg.Column(layout=col_layout[1]),
        sg.Column(layout=make_edit_weapons_section(character["weapons"]))
    ])
    return layout
예제 #5
0
def Window():
    col_prop = [
        [
            sg.T(' k [W/(m·K)]', size=(10, 1)),
            sg.In('', size=(15, 1), justification='right', key='-k-'),
            sg.Button('Temperature Dependant', size=(18, 1), key='-loadk-'),
            sg.Button('📊', size=(4, 1), key='-plotk-')
        ],
    ]

    menu_def = [['File', ['Load', 'Save', 'Exit']], ['Help', ['About']]]

    layout = [[sg.Menu(menu_def)], [sg.Column(col_prop)]]
    window = sg.Window('Name!', layout)

    kparams = np.array([['', '']])

    while True:
        event, values = window.read()
        if event in (None, 'Exit'):
            break
        if event == '-loadk-':
            try:
                tpar = kWindow(kparams)
                if tpar is not None: kparams = tpar
            except:
                pass
        if event == '-plotk-':
            if kparams[0, 0] == '' and values['-k-'] == '':
                sg.PopupOK(
                    'You need to define the «Thermal Conductivity» first!',
                    title='Warning')
            elif values['-k-'] != '':
                plotk(float(values['-k-']))
            else:
                plotk(kparams)
    window.close()
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()
예제 #7
0
def main():
    sg.ChangeLookAndFeel('GreenTan')
    # sg.SetOptions(element_padding=(0,0))
    # ------ Menu Definition ------ #
    menu_def = [
        ['&File', ['&Open', '&Save', '&Properties', 'E&xit']],
        [
            '&Edit',
            ['&Paste', [
                'Special',
                'Normal',
            ], 'Undo'],
        ],
        ['&Toolbar', ['Command &1', 'Command &2', 'Command &3', 'Command &4']],
        ['&Help', '&About...'],
    ]

    treedata = sg.TreeData()

    treedata.Insert(
        "",
        '_A_',
        'Tree Item 1',
        [1, 2, 3],
    )
    treedata.Insert(
        "",
        '_B_',
        'B',
        [4, 5, 6],
    )
    treedata.Insert(
        "_A_",
        '_A1_',
        'Sub Item 1',
        ['can', 'be', 'anything'],
    )
    treedata.Insert(
        "",
        '_C_',
        'C',
        [],
    )
    treedata.Insert(
        "_C_",
        '_C1_',
        'C1',
        ['or'],
    )
    treedata.Insert("_A_", '_A2_', 'Sub Item 2', [None, None])
    treedata.Insert("_A1_", '_A3_', 'A30', ['getting deep'])
    treedata.Insert("_C_", '_C2_', 'C2', ['nothing', 'at', 'all'])

    for i in range(100):
        treedata.Insert('_C_', i, i, [])

    frame1 = [
        [sg.Input('Input Text', size=(250, 35)),
         sg.Stretch()],
        [
            sg.Multiline(size=(250, 75), default_text='Multiline Input'),
            sg.MultilineOutput(size=(250, 75), default_text='Multiline Output')
        ],
    ]

    frame2 = [
        [sg.Listbox(['Listbox 1', 'Listbox 2', 'Listbox 3'], size=(200, 85))],
        [
            sg.Combo(['Combo item 1', 'Combo item 2', 'Combo item 3'],
                     size=(200, 35))
        ],
        [sg.Spin([1, 2, 3], size=(40, 30))],
    ]

    frame3 = [
        [sg.Checkbox('Checkbox1', True),
         sg.Checkbox('Checkbox1')],
        [
            sg.Radio('Radio Button1', 1),
            sg.Radio('Radio Button2', 1, default=True),
            sg.Stretch()
        ],
    ]

    frame4 = [
        [
            sg.Slider(range=(0, 100),
                      orientation='v',
                      size=(3, 30),
                      default_value=40),
            sg.Dial(range=(0, 100),
                    tick_interval=50,
                    size=(150, 150),
                    default_value=40),
            sg.Stretch()
        ],
    ]
    matrix = [[str(x * y) for x in range(4)] for y in range(3)]

    frame5 = [
        [
            sg.Table(values=matrix,
                     max_col_width=25,
                     auto_size_columns=True,
                     display_row_numbers=True,
                     change_submits=False,
                     bind_return_key=True,
                     justification='right',
                     num_rows=8,
                     alternating_row_color='lightblue',
                     key='_table_',
                     text_color='black'),
            sg.Tree(data=treedata,
                    headings=['col1', 'col2', 'col3'],
                    change_submits=True,
                    auto_size_columns=True,
                    num_rows=10,
                    col0_width=10,
                    key='_TREE_',
                    show_expanded=True,
                    size=(200, 150)),
            sg.Stretch()
        ],
    ]

    graph_elem = sg.Graph((880, 150), (0, 0), (600, 300), key='+GRAPH+')

    frame6 = [
        [graph_elem, sg.Stretch()],
    ]

    tab1 = sg.Tab('Graph Number 1', frame6)
    tab2 = sg.Tab('Graph Number 2', [[]])

    layout = [
        [sg.Menu(menu_def)],
        [
            sg.Image(data_base64=logo),
            sg.Frame('Input Text Group', frame1, title_color='red'),
            sg.Stretch()
        ],
        [
            sg.Frame('Multiple Choice Group', frame2, title_color='green'),
            sg.Frame('Binary Choice Group', frame3, title_color='purple'),
            sg.Frame('Variable Choice Group', frame4, title_color='blue'),
            sg.Stretch()
        ],
        [
            sg.Frame('Structured Data Group', frame5, title_color='red'),
        ],
        # [sg.Frame('Graphing Group', frame6)],
        [sg.TabGroup([[tab1, tab2]])],
        [
            sg.ProgressBar(max_value=600,
                           start_value=400,
                           size=(600, 25),
                           key='+PROGRESS+'),
            sg.Stretch(),
            sg.ButtonMenu('&Menu', ['Menu', ['&Pause Graph', 'Menu item']],
                          key='_MENU_'),
            sg.Button('Button'),
            sg.Button('Exit')
        ],
    ]

    window = sg.Window('Window Title',
                       font=('Helvetica', 13),
                       default_button_element_size=(100, 30),
                       auto_size_buttons=False,
                       default_element_size=(200,
                                             22)).Layout(layout).Finalize()
    graph_elem.DrawCircle((200, 200), 50, 'blue')
    i = 0
    graph_paused = False
    while True:  # Event Loop
        # sg.TimerStart()
        event, values = window.Read(timeout=0)
        if event is None or event == 'Exit':
            break
        if event == 'Button':
            print(event, values)
        if values['_MENU_'] == 'Pause Graph':
            graph_paused = not graph_paused
        if not graph_paused:
            i += 1

            if i >= 600:
                graph_elem.Move(-1, 0)
            graph_elem.DrawLine((i, 0), (i, randint(0, 300)),
                                width=1,
                                color='#{:06x}'.format(randint(0, 0xffffff)))
        window.FindElement('+PROGRESS+').UpdateBar(i % 600)

        # sg.TimerStop()
    window.Close()
예제 #8
0
파일: client.py 프로젝트: jahosp/rsteg-tcp
                         sg.Text('Retransmission probability'),
                         sg.InputText(default_text='0.07',
                                      enable_events=True,
                                      key='prob')
                     ],
                 ],
                 visible=False,
                 key='tcp_frame')
    ]

    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']]
예제 #9
0
                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


layout = [[sg.Menu(menu_def, tearoff=True)],
          [
              sg.Txt('Status:', size=(10, 1), font=("Ariel", 16)),
              sg.Txt('Load raw data file.',
                     size=(30, 2),
                     font=("Ariel", 16),
                     key='output')
          ],
          [
              sg.Button('Load Data', size=(15, 1), font=("Ariel", 16)),
              sg.Button('Settings', size=(15, 1), font=("Ariel", 16)),
              sg.Button('Exit', size=(12, 1), font=("Ariel", 16))
          ]]

# should be : [sg.FileBrowse(), sg.Exit()]]
예제 #10
0
# ------ 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))],
]

layout = [
    [sg.Menu(menu_def, tearoff=True)],
    [
        sg.Text('(Almost) All widgets in one Window!',
                justification='c',
                font=("Helvetica", 25),
                relief=sg.RELIEF_RIDGE)
    ], [sg.Text('Here is some text.... and a place to enter text')],
    [sg.InputText('This is my text', size=(400, 22))],
    [
        sg.Frame(
            layout=[[
                sg.Checkbox('Checkbox', size=(185, 22)),
                sg.Checkbox('My second checkbox!', default=True)
            ],
                    [
                        sg.Radio(
예제 #11
0
    lf_str = last_fetched.strftime("%d/%m/%Y %H:%M:%S")
    lf_statement = f'Last fetched: {lf_str}'
    print(lf_statement)

    return s_data


if parser.gui:
    print('')
    import PySimpleGUIQt as Qt

    Qt.theme('DarkAmber')

    menu_def = [['Application', 'Settings']]

    layout = [[Qt.Menu(menu_def, tearoff=False, pad=(200, 1))],
              [
                  Qt.MultilineOutput(autoscroll=True,
                                     key='output',
                                     do_not_clear=False)
              ],
              [
                  Qt.Button('Refresh', enable_events=True, key='refresh_bttn'),
                  Qt.Button('Inspect',
                            enable_events=True,
                            key='inspect_bttn',
                            visible=False),
                  Qt.CloseButton('Close', key='close_bttn')
              ]]

    window = Qt.Window('CoVid 19 United States Stats',
예제 #12
0
    visible=False,
)
frm_tools_afx = sg.Frame(
    title="Apply Audio FX",
    layout=[[sg.T("Tools AFX")]],
    key="_frm_tools_afx_",
    visible=False,
)
frm_tools_convert = sg.Frame(
    title="Convert File Types",
    layout=[[sg.T("Tools Convert")]],
    key="_frm_tools_convert_",
    visible=False,
)
frm_tools_export = sg.Frame(
    title="Export For Platform",
    layout=[[sg.T("Tools Export")]],
    key="_frm_tools_export_",
    visible=False,
)

layout = [
    [sg.Menu(menu_def)],
    [frm_main],
    [frm_config],
    [frm_tools_name],
    [frm_tools_afx],
    [frm_tools_convert],
    [frm_tools_export],
]
예제 #13
0
    last_fetched = datetime.now()
    lf_str = last_fetched.strftime("%d/%m/%Y %H:%M:%S")
    lf_statement = f'Last fetched: {lf_str}'
    print(lf_statement)

    return s_data


if parser.gui:
    print('')
    import PySimpleGUIQt as Qt

    Qt.theme(app_theme)

    layout = [[Qt.Menu(main_menu.definition, tearoff=False, pad=(200, 1))],
              [Qt.MultilineOutput(autoscroll=True, key='output')],
              [
                  Qt.Button('Refresh', enable_events=True, key='refresh_bttn'),
                  Qt.Button('Inspect',
                            enable_events=True,
                            key='inspect_bttn',
                            visible=False),
                  Qt.CloseButton('Close', key='close_bttn')
              ]]

    window = Qt.Window('CoVid 19 United States Stats',
                       layout,
                       size=(500, 600),
                       icon=c_icon)
    print = window['output'].print