gui package

The GUI Package contains the entire code base for Faceswap’s optional GUI. The GUI itself is largely self-generated from the command line options specified in lib.cli.args.

stats module

Package Summary

Calculations Class that performs calculations on the GlobalSession raw data for the given session id.
GlobalSession Holds information about a loaded or current training session by accessing a model’s state file and Tensorboard logs.
SessionsSummary Performs top level summary calculations for each session ID within the loaded or currently training Session for display in the Analysis tree view.
TensorBoardLogs Parse data from TensorBoard logs.

stats Module

Stats functions for the GUI.

Holds the globally loaded training session. This will either be a user selected session (loaded in the analysis tab) or the currently training session.

class lib.gui.analysis.stats.Calculations(session_id, display='loss', loss_keys='loss', selections='raw', avg_samples=500, smooth_amount=0.9, flatten_outliers=False)

Bases: object

Class that performs calculations on the GlobalSession raw data for the given session id.

Parameters:
  • session_id (int or None) – The session id number for the selected session from the Analysis tab. Should be None if all sessions are being calculated
  • display ({"loss", "rate"}, optional) – Whether to display a graph for loss or training rate. Default: “loss”
  • loss_keys (list, optional) – The list of loss keys to display on the graph. Default: [“loss”]
  • selections (list, optional) – The selected annotations to display. Default: [“raw”]
  • avg_samples (int, optional) – The number of samples to use for performing moving average calculation. Default: 500.
  • smooth_amount (float, optional) – The amount of smoothing to apply for performing smoothing calculation. Default: 0.9.
  • flatten_outliers (bool, optional) – True if values significantly away from the average should be excluded, otherwise False. Default: False
iterations

The number of iterations in the data set.

Type:int
refresh()

Refresh the stats

set_iterations_limit(limit)

Set the number of iterations to display in the calculations.

If a value greater than 0 is passed, then the latest iterations up to the given limit will be calculated.

Parameters:limit (int) – The number of iterations to calculate data for. 0 to calculate for all data
set_smooth_amount(amount)

Set the amount of smoothing to apply to smoothed graph.

Parameters:amount (float) – The amount of smoothing to apply to smoothed graph
start_iteration

The starting iteration number of a limit has been set on the amount of data.

Type:int
stats

The final calculated statistics

Type:dict
update_selections(selection, option)

Update the type of selected data.

Parameters:
  • selection (str) – The selection to update (as can exist in _selections)
  • option (bool) – True if the selection should be included, False if it should be removed
class lib.gui.analysis.stats.GlobalSession

Bases: object

Holds information about a loaded or current training session by accessing a model’s state file and Tensorboard logs. This class should not be accessed directly, rather through lib.gui.analysis.Session

batch_sizes

The batch sizes for each session_id for the model.

Type:dict
clear()

Clear the currently loaded session.

full_summary

List of dictionaries containing summary statistics for each session id.

Type:list
get_loss(session_id)

Obtain the loss values for the given session_id.

Parameters:session_id (int or None) – The session ID to return loss for. Pass None to return loss for all sessions.
Returns:Loss names as key, numpy.ndarray as value. If No session ID was provided all session’s losses are collated
Return type:dict
get_loss_keys(session_id)

Obtain the loss keys for the given session_id.

Parameters:session_id (int or None) – The session ID to return the loss keys for. Pass None to return loss keys for all sessions.
Returns:The loss keys for the given session. If None is passed as session_id then a unique list of all loss keys for all sessions is returned
Return type:list
get_timestamps(session_id)

Obtain the time stamps keys for the given session_id.

Parameters:session_id (int or None) – The session ID to return the time stamps for. Pass None to return time stamps for all sessions.
Returns:If a session ID has been given then a single numpy.ndarray will be returned with the session’s time stamps. Otherwise a ‘dict’ will be returned with the session IDs as key with numpy.ndarray of timestamps as values
Return type:dict or numpy.ndarray
initialize_session(model_folder, model_name, is_training=False)

Initialize a Session.

Load’s the model’s state file, and sets the paths to any underlying Tensorboard logs, ready for access on request.

Parameters:
  • model_folder (str, optional) – If loading a session manually (e.g. for the analysis tab), then the path to the model folder must be provided. For training sessions, this should be left at None
  • model_name (str, optional) – If loading a session manually (e.g. for the analysis tab), then the model filename must be provided. For training sessions, this should be left at None
  • is_training (bool, optional) – True if the session is being initialized for a training session, otherwise False. Default: False
is_loaded

True if session data is loaded otherwise False

Type:bool
is_training

True if the loaded session is the currently training model, otherwise False

Type:bool
logging_disabled

True if logging is enabled for the currently training session otherwise False.

Type:bool
model_filename

The full model filename

Type:str
session_ids

The sorted list of all existing session ids in the state file

Type:list
stop_training()

Clears the internal training flag. To be called when training completes.

class lib.gui.analysis.stats.SessionsSummary(session)

Bases: object

Performs top level summary calculations for each session ID within the loaded or currently training Session for display in the Analysis tree view.

Parameters:session (GlobalSession) – The loaded or currently training session
get_summary_stats()

Compile the individual session statistics and calculate the total.

Format the stats for display

Returns:A list of summary statistics dictionaries containing the Session ID, start time, end time, elapsed time, rate, batch size and number of iterations for each session id within the loaded data as well as the totals.
Return type:list

event_reader Module

Handles the loading and collation of events from Tensorflow event log files.

class lib.gui.analysis.event_reader.TensorBoardLogs(logs_folder, is_training)

Bases: object

Parse data from TensorBoard logs.

Process the input logs folder and stores the individual filenames per session.

Caches timestamp and loss data on request and returns this data from the cache.

Parameters:
  • logs_folder (str) – The folder that contains the Tensorboard log files
  • is_training (bool) – True if the events are being read whilst Faceswap is training otherwise False
get_loss(session_id=None)

Read the loss from the TensorBoard event logs

Parameters:session_id (int, optional) – The Session ID to return the loss for. Set to None to return all session losses. Default None
Returns:The session id(s) as key, with a further dictionary as value containing the loss name and list of loss values for each step
Return type:dict
get_timestamps(session_id=None)

Read the timestamps from the TensorBoard logs.

As loss timestamps are slightly different for each loss, we collect the timestamp from the batch_loss key.

Parameters:session_id (int, optional) – The Session ID to return the timestamps for. Set to None to return all session timestamps. Default None
Returns:The session id(s) as key with list of timestamps per step as value
Return type:dict
session_ids

Sorted list of integers of available session ids.

Type:list
set_training(is_training)

Set the internal training flag to the given is_training value.

If a new training session is being instigated, refresh the log filenames

Parameters:is_training (bool) – True to indicate that the logs to be read are from the currently training session otherwise False

custom_widgets module

Module Summary

ConsoleOut The Console out section of the GUI.
ContextMenu A Pop up menu to be triggered when right clicking on widgets that this menu has been applied to.
MultiOption Similar to the standard ttk.Radio widget, but with the ability to select multiple pre-defined options.
RightClickMenu A Pop up menu that can be bound to a right click mouse event to bring up a context menu
StatusBar Status Bar for displaying the Status Message and Progress Bar at the bottom of the GUI.
Tooltip Create a tooltip for a given widget as the mouse goes on it.

Module

Custom widgets for Faceswap GUI

class lib.gui.custom_widgets.ConsoleOut(parent, debug)

Bases: tkinter.ttk.Frame

The Console out section of the GUI.

A Read only text box for displaying the output from stdout/stderr.

All handling is internal to this method. To clear the console, the stored tkinter variable in tk_vars console_clear should be triggered.

Parameters:
  • parent (tkinter object) – The Console’s parent widget
  • debug (bool) – True if console output should not be directed to this widget otherwise False
class lib.gui.custom_widgets.ContextMenu(widget)

Bases: tkinter.Menu

A Pop up menu to be triggered when right clicking on widgets that this menu has been applied to.

This widget provides a simple right click pop up menu to the widget passed in with Cut, Copy, Paste and Select all menu items.

Parameters:widget (tkinter object) – The widget to apply the ContextMenu to

Example

>>> text_box = ttk.Entry(parent)
>>> text_box.pack()
>>> right_click_menu = ContextMenu(text_box)
>>> right_click_menu.cm_bind()
cm_bind()

Bind the menu to the given widgets Right Click event

After associating a widget with this ContextMenu this function should be called to bind it to the right click button

class lib.gui.custom_widgets.MultiOption(parent, value, variable, **kwargs)

Bases: tkinter.ttk.Checkbutton

Similar to the standard ttk.Radio widget, but with the ability to select multiple pre-defined options. Selected options are generated as nargs for the argument parser to consume.

Parameters:
  • parent (ttk.Frame) – The tkinter parent widget for the check button
  • value (str) – The raw option value for this check button
  • variable (tkinter.StingVar) – The master variable for the group of check buttons that this check button will belong to. The output of this variable will be a string containing a space separated list of the selected check button options
class lib.gui.custom_widgets.PopupProgress(title, total)

Bases: tkinter.Toplevel

A simple pop up progress bar that appears of the center of the root window.

When this is called, the root will be disabled until the close() method is called.

Parameters:
  • title (str) – The title to appear above the progress bar
  • total (int or float) – The total count of items for the progress bar

Example

>>> total = 100
>>> progress = PopupProgress("My title...", total)
>>> for i in range(total):
>>>     progress.update(1)
>>> progress.close()
progress_bar

The progress bar object within the pop up window.

Type:tkinter.ttk.Progressbar
step(amount)

Increment the progress bar.

Parameters:amount (int or float) – The amount to increment the progress bar by
stop()

Stop the progress bar, re-enable the root window and destroy the pop up window.

update_title(title)

Update the title that displays above the progress bar.

Parameters:title (str) – The title to appear above the progress bar
class lib.gui.custom_widgets.RightClickMenu(labels, actions, hotkeys=None)

Bases: tkinter.Menu

A Pop up menu that can be bound to a right click mouse event to bring up a context menu

Parameters:
  • labels (list) – A list of label titles that will appear in the right click menu
  • actions (list) – A list of python functions that are called when the corresponding label is clicked on
  • hotkeys (list, optional) – The hotkeys corresponding to the labels. If using hotkeys, then there must be an entry in the list for every label even if they don’t all use hotkeys. Labels without a hotkey can be an empty string or None. Passing None instead of a list means that no actions will be given hotkeys. NB: The hotkey is not bound by this class, that needs to be done in code. Giving hotkeys here means that they will be displayed in the menu though. Default: None
popup(event)

Pop up the right click menu.

Parameters:event (class:tkinter.Event) – The tkinter mouse event calling this popup
class lib.gui.custom_widgets.StatusBar(parent, hide_status=False)

Bases: tkinter.ttk.Frame

Status Bar for displaying the Status Message and Progress Bar at the bottom of the GUI.

Parameters:
  • parent (tkinter object) – The parent tkinter widget that will hold the status bar
  • hide_status (bool, optional) – True to hide the status message that appears at the far left hand side of the status frame otherwise False. Default: False
message

The variable to hold the status bar message on the left hand side of the status bar.

Type:tkinter.StringVar
progress_update(message, position, update_position=True)

Update the GUIs progress bar and position.

Parameters:
  • message (str) – The message to display next to the progress bar
  • position (int) – The position that the progress bar should be set to
  • update_position (bool, optional) – If True then the progress bar will be updated to the position given in position. If False the progress bar will not be updates. Default: True
start(mode)

Set progress bar mode and display,

Parameters:mode (["indeterminate", "determinate"]) – The mode that the progress bar should be executed in
stop()

Reset progress bar and hide

class lib.gui.custom_widgets.ToggledFrame(parent, *args, text='', theme='CPanel', toggle_var=None, **kwargs)

Bases: tkinter.ttk.Frame

A collapsible and expandable frame.

The frame contains a header given in the text argument, and adds an expand contract button. Clicking on the header will expand and contract the sub-frame below

Parameters:
  • text (str) – The text to appear in the Toggle Frame header
  • theme (str, optional) – The theme to use for the panel header. Default: “CPanel”
  • subframe_style (str, optional) – The name of the ttk Style to use for the sub frame. Default: None
  • toggle_var (tk.BooleanVar, optional) – If provided, this variable will control the expanded (True) and minimized (False) state of the widget. Set to None to create the variable internally. Default: None
is_expanded

True if the Toggle Frame is expanded. False if it is minimized.

Type:bool
class lib.gui.custom_widgets.Tooltip(widget, *, pad=(5, 3, 5, 3), text='widget info', text_variable=None, wait_time=400, wrap_length=250)

Bases: object

Create a tooltip for a given widget as the mouse goes on it.

Parameters:
  • widget (tkinter object) – The widget to apply the tool-tip to
  • pad (tuple, optional) – (left, top, right, bottom) padding for the tool-tip. Default: (5, 3, 5, 3)
  • text (str, optional) – The text to be displayed in the tool-tip. Default: ‘widget info’
  • text_variable (tkinter.strVar, optional) – The text variable to use for dynamic help text. Appended after the contents of text if provided. Default: None
  • wait_time (int, optional) – The time in milliseconds to wait before showing the tool-tip. Default: 400
  • wrap_length (int, optional) – The text length for each line before wrapping. Default: 250

Example

>>> button = ttk.Button(parent, text="Exit")
>>> Tooltip(button, text="Click to exit")
>>> button.pack()

Notes

Adapted from StackOverflow: http://stackoverflow.com/questions/3221956 and http://www.daniweb.com/programming/software-development/code/484591/a-tooltip-class-for-tkinter

display module

Display Frame of the Faceswap GUI

This is the large right hand area of the GUI. At default, the Analysis tab is always displayed here. Further optional tabs will also be displayed depending on the currently executing Faceswap task.

class lib.gui.display.DisplayNotebook(parent)

Bases: tkinter.ttk.Notebook

The tkinter Notebook that holds the display items.

Parameters:parent (tk.PanedWindow) – The paned window that holds the Display Notebook
runningtask

The global tkinter variable that indicates whether a Faceswap task is currently running or not.

Type:tkinter.BooleanVar

display_analysis module

Module Summary

Analysis Session Analysis Tab.
StatsData Stats frame of analysis tab.

Module

Analysis tab of Display Frame of the Faceswap GUI

class lib.gui.display_analysis.Analysis(parent, tab_name, helptext)

Bases: lib.gui.display_page.DisplayPage

Session Analysis Tab.

The area of the GUI that holds the session summary stats for model training sessions.

Parameters:
  • parent (lib.gui.display.DisplayNotebook) – The ttk.Notebook that holds this session summary statistics page
  • tab_name (str) – The name of the tab to be displayed in the notebook
  • helptext (str) – The help text to display for the summary statistics page
on_tab_select()

Callback for when the analysis tab is selected.

If Faceswap is currently training a model, then update the statistics with the latest values.

set_vars()

Set the analysis specific tkinter variables to vars.

The tracked variables are the global variables that:
  • Trigger when a graph refresh has been requested.
  • Trigger training is commenced or halted
  • The variable holding the location of the current Tensorboard log folder.
Returns:The dictionary of variable names to tkinter variables
Return type:dict
class lib.gui.display_analysis.StatsData(parent, selected_id, helptext)

Bases: tkinter.ttk.Frame

Stats frame of analysis tab.

Holds the tree-view containing the summarized session statistics in the Analysis tab.

Parameters:
  • parent (tkinter.Frame) – The frame within the Analysis Notebook that will hold the statistics
  • selected_id (tkinter.IntVar) – The tkinter variable that holds the currently selected session ID
  • helptext (str) – The help text to display for the summary statistics page
tree_clear()

Clear all of the summary data from the tree-view.

tree_insert_data(sessions_summary)

Insert the summary data into the statistics tree-view.

Parameters:sessions_summary (list) – List of session summary dicts for populating into the tree-view

popup_configure module

The pop-up window of the Faceswap GUI for the setting of configuration options.

class lib.gui.popup_configure.DisplayArea(top_level, parent, configurations, tree, theme)

Bases: tkinter.ttk.Frame

The option configuration area of the pop up options.

Parameters:
  • top_level (:class:tk.Toplevel) – The tkinter Top Level widget
  • parent (tkinter.ttk.Frame) – The parent frame that holds the Display Area of the pop up configuration window
  • tree (tkinter.ttk.TreeView) – The Tree View navigator for the pop up configuration window
  • configurations (dict) – Dictionary containing the FaceswapConfig object for each configuration section for the requested pop-up window
  • theme (dict) – The color mapping for the settings pop-up theme
config_dict

The configuration dictionary for all display pages.

Type:dict
displayed_key

The current display page’s lookup key for configuration options.

Type:str
reset(page_only=False)

Reset all configuration options to their default values.

Parameters:page_only (bool, optional) – True resets just the currently selected page’s options to default, False resets all plugins within the currently selected config to default. Default: False
save(page_only=False)

Save the configuration file to disk.

Parameters:page_only (bool, optional) – True saves just the currently selected page’s options, False saves all the plugins options within the currently selected config. Default: False
select_options(section, subsections)

Display the page for the given section and subsections.

Parameters:
  • section (str) – The main section to be navigated to (or root node)
  • subsections (list) – The full list of subsections ending on the required node

popup_session module

Pop-up Graph launched from the Analysis tab of the Faceswap GUI

class lib.gui.popup_session.SessionPopUp(session_id, data_points)

Bases: tkinter.Toplevel

Pop up for detailed graph/stats for selected session.

session_id: int or “Total”
The session id number for the selected session from the Analysis tab. Should be the string “Total” if all sessions are being graphed
data_points: int
The number of iterations in the selected session

project module

Module Summary

LastSession Faceswap Last Session handling.
Project Faceswap .fsw Project File handling.
Tasks Faceswap .fst Task File handling.

Module

Handling of Faceswap GUI Projects, Tasks and Last Session

class lib.gui.project.LastSession(config)

Bases: lib.gui.project._GuiSession

Faceswap Last Session handling.

Faceswap LastSession handles saving the state of the Faceswap GUI at close and reloading the state at launch.

Last Session behavior can be configured in config.gui.ini.

Parameters:config (lib.gui.utils.Config) – The master GUI config
ask_load()

Pop a message box to ask the user if they wish to load their last session.

from_dict(options)

Set the _options property based on the given options dictionary and update the GUI to use these values.

This function is required for reloading the GUI state when the GUI has been force refreshed on a config change.

Parameters:options (dict) – The options to set. Should be the output of to_dict()
load()

Load the last session.

Loads the last saved session options. Checks if a previous project was loaded and whether there have been changes since the last saved version of the project. Sets the display and Project and Task objects accordingly.

save()

Save a snapshot of currently set GUI config options.

Called on Faceswap shutdown.

to_dict()

Collect the current GUI options and place them in a dict for retrieval or storage.

This function is required for reloading the GUI state when the GUI has been force refreshed on a config change.

Returns:dict
Return type:The current cli options ready for saving or retrieval by from_dict()
class lib.gui.project.Project(config, file_handler)

Bases: lib.gui.project._GuiSession

Faceswap .fsw Project File handling.

Faceswap projects handle the management of all task tabs in the GUI and updates the main Faceswap title bar with the project name and modified state.

Parameters:
cli_options

the raw cli options from _options with project fields removed.

Type:dict
close(*args)

Clear the current project and set all options to default.

Parameters:*args (tuple) – Unused, but needs to be present for arguments passed by tkinter event handling
confirm_close()

Pop a message box to get confirmation that an unsaved project should be closed

Returns:bool
Return type:True if user confirms close, False if user cancels close
filename

The currently active project filename.

Type:str
load(*args, filename=None)

Load a project from a saved .fsw project file.

Parameters:
  • *args (tuple) – Unused, but needs to be present for arguments passed by tkinter event handling
  • filename (str, optional) – If a filename is passed in, This will be used, otherwise a file handler will be launched to select the relevant file.
new(*args)

Create a new project with default options.

Pops a file handler to select location.

Parameters:*args (tuple) – Unused, but needs to be present for arguments passed by tkinter event handling
reload(*args)

Reset all GUI’s option tabs to their last saved state.

Parameters:*args (tuple) – Unused, but needs to be present for arguments passed by tkinter event handling
save(*args, save_as=False)

Save the current GUI state to a .fsw project file.

Parameters:
  • *args (tuple) – Unused, but needs to be present for arguments passed by tkinter event handling
  • save_as (bool, optional) – Whether to save to the stored filename, or pop open a file handler to ask for a location. If there is no stored filename, then a file handler will automatically be popped.
set_default_options()

Set the default options. The Default GUI options are stored on Faceswap startup.

Exposed as the _default_options for a project cannot be set until after the main Command Tabs have been loaded.

set_modified_callback()

Adds a callback to each of the _modified_vars tkinter variables When one of these variables is changed, triggers _modified_callback() with the command that was changed.

This is exposed as the callback can only be added after the main Command Tabs have been drawn, and their options’ initial values have been set.

class lib.gui.project.Tasks(config, file_handler)

Bases: lib.gui.project._GuiSession

Faceswap .fst Task File handling.

Faceswap tasks handle the management of each individual task tab in the GUI. Unlike Projects, Tasks contains all the active tasks currently running, rather than an individual task.

Parameters:
add_project_task(filename, command, options)

Add an individual task from a loaded Project to the internal _tasks dict.

Project tasks take priority over any other tasks, so the individual tasks from a new project must be placed in the _tasks dict.

Parameters:
  • filename (str) – The filename of the session project file
  • command (str) – The tab that this task’s options belong to
  • options (dict) – The options for this task loaded from the project
clear()

Reset all GUI options to their default values for the active tab.

clear_tasks()

Clears all of the stored tasks.

This is required when loading a task stored in a legacy project file, and is only to be called by Project when a project has been loaded which is in fact a task.

load(*args, filename=None, current_tab=True)

Load a task into this Tasks class.

Tasks can be loaded from project .fsw files or task .fst files, depending on where this function is being called from.

Parameters:
  • *args (tuple) – Unused, but needs to be present for arguments passed by tkinter event handling
  • filename (str, optional) – If a filename is passed in, This will be used, otherwise a file handler will be launched to select the relevant file.
  • current_tab (bool, optional) – True if the task to be loaded must be for the currently selected tab. False if loading a task into any tab. If current_tab is True then tasks can be loaded from .fsw and .fst files, otherwise they can only be loaded from .fst files. Default: True
reload()

Reset currently selected tab GUI options to their last saved state.

save(save_as=False)

Save the current GUI state for the active tab to a .fst faceswap task file.

Parameters:save_as (bool, optional) – Whether to save to the stored filename, or pop open a file handler to ask for a location. If there is no stored filename, then a file handler will automatically be popped.

theme module

Module

functions for implementing themes in Faceswap’s GUI

class lib.gui.theme.Style(default_font, root, path_cache)

Bases: object

Set the overarching theme and customize widgets.

Parameters:
  • default_font (tuple) – The name and size of the default font
  • root (tkinter.Tk) – The root tkinter object
  • path_cache (str) – The path to the GUI’s cache
user_theme

The currently selected user theme.

Type:dict

utils module

Module Summary

Config The centralized configuration class for holding items that should be made available to all parts of the GUI.
FileHandler Handles all GUI File Dialog actions and tasks.
Images The centralized image repository for holding all icons and images required by the GUI.
LongRunningTask Runs long running tasks in a background thread to prevent the GUI from becoming unresponsive.
get_config Get the Master GUI configuration.
get_images Get the Master GUI Images handler.
initialize_config Initialize the GUI Master Config and add to global constant.
initialize_images Initialize the Images handler and add to global constant.

Module

Utility functions for the GUI

class lib.gui.utils.Config(root, cli_opts, statusbar)

Bases: object

The centralized configuration class for holding items that should be made available to all parts of the GUI.

This class should be initialized on GUI startup through initialize_config(). Any further access to this class should be through get_config().

Parameters:
  • root (tkinter.Tk) – The root Tkinter object
  • cli_opts (lib.gui.options.CliOpts) – The command line options object
  • statusbar (lib.gui.custom_widgets.StatusBar) – The GUI Status bar
cli_opts

The command line options for this GUI Session.

Type:lib.gui.options.CliOptions
command_notebook

The main Faceswap Command Notebook.

Type:lib.gui.command.CommandNoteboook
default_font

The selected font as configured in user settings. First item is the font (str) second item the font size (int).

Type:tuple
default_options

The default options for all tabs

Type:dict
modified_vars

The command notebook modified tkinter variables.

Type:dict
pathcache

The path to the GUI cache folder

Type:str
project

The project session handler.

Type:lib.gui.project.Project
refresh_config()

Reload the user config from file.

root

The root tkinter window.

Type:tkinter.Tk
scaling_factor

The scaling factor for current display.

Type:float
set_active_tab_by_name(name)

Sets the command_notebook or tools_notebook to active based on given name.

Parameters:name (str) – The name of the tab to set active
set_command_notebook(notebook)

Set the command notebook to the command_notebook attribute and enable the modified callback for project.

Parameters:notebook (lib.gui.command.CommandNotebook) – The main command notebook for the Faceswap GUI
set_cursor_busy(widget=None)

Set the root or widget cursor to busy.

Parameters:widget (tkinter object, optional) – The widget to set busy cursor for. If the provided value is None then sets the cursor busy for the whole of the GUI. Default: None.
set_cursor_default(widget=None)

Set the root or widget cursor to default.

Parameters:widget (tkinter object, optional) – The widget to set default cursor for. If the provided value is None then sets the cursor busy for the whole of the GUI. Default: None
set_default_options()

Set the default options for lib.gui.projects

The Default GUI options are stored on Faceswap startup.

Exposed as the _default_opts for a project cannot be set until after the main Command Tabs have been loaded.

set_geometry(width, height, fullscreen=False)

Set the geometry for the root tkinter object.

Parameters:
  • width (int) – The width to set the window to (prior to scaling)
  • height (int) – The height to set the window to (prior to scaling)
  • fullscreen (bool, optional) – Whether to set the window to full-screen mode. If True then width and height are ignored. Default: False
set_modified_true(command)

Set the modified variable to True for the given command in modified_vars.

Parameters:command (str) – The command to set the modified state to True
set_root_title(text=None)

Set the main title text for Faceswap.

The title will always begin with ‘Faceswap.py’. Additional text can be appended.

Parameters:text (str, optional) – Additional text to be appended to the GUI title bar. Default: None
statusbar

The GUI StatusBar tkinter.ttk.Frame.

Type:lib.gui.custom_widgets.StatusBar
tasks

The session tasks handler.

Type:lib.gui.project.Tasks
tk_vars

The global tkinter variables.

Type:dict
tools_notebook

The Faceswap Tools sub-Notebook.

Type:lib.gui.command.ToolsNotebook
user_config

The GUI config in dict form.

Type:dict
user_config_dict

The GUI config in dict form.

Type:dict
user_theme

The GUI theme selection options.

Type:dict
class lib.gui.utils.FileHandler(handle_type, file_type, title=None, initial_folder=None, initial_file=None, command=None, action=None, variable=None)

Bases: object

Handles all GUI File Dialog actions and tasks.

Parameters:
  • handle_type ([‘open’, ‘save’, ‘filename’, ‘filename_multi’, ‘save_filename’, ‘context’, dir]) – The type of file dialog to return. open and save will perform the open and save actions and return the file. filename returns the filename from an open dialog. filename_multi allows for multi-selection of files and returns a list of files selected. save_filename returns the filename from a save as dialog. context is a context sensitive parameter that returns a certain dialog based on the current options. dir asks for a folder location.
  • file_type (['default', 'alignments', 'config_project', 'config_task', 'config_all', 'csv', 'image', 'ini', 'state', 'log', 'video']) – The type of file that this dialog is for. default allows selection of any files. Other options limit the file type selection
  • title (str, optional) – The title to display on the file dialog. If None then the default title will be used. Default: None
  • initial_folder (str, optional) – The folder to initially open with the file dialog. If None then tkinter will decide. Default: None
  • initial_file (str, optional) – The filename to set with the file dialog. If None then tkinter no initial filename is. specified. Default: None
  • command (str, optional) – Required for context handling file dialog, otherwise unused. Default: None
  • action (str, optional) – Required for context handling file dialog, otherwise unused. Default: None
  • variable (tkinter.StringVar, optional) – Required for context handling file dialog, otherwise unused. The variable to associate with this file dialog. Default: None
return_file

The return value from the file dialog

Type:str or object

Example

>>> handler = FileHandler('filename', 'video', title='Select a video...')
>>> video_file = handler.return_file
>>> print(video_file)
'/path/to/selected/video.mp4'
class lib.gui.utils.Images

Bases: object

The centralized image repository for holding all icons and images required by the GUI.

This class should be initialized on GUI startup through initialize_images(). Any further access to this class should be through get_images().

delete_preview()

Delete the preview files in the cache folder and reset the image cache.

Should be called when terminating tasks, or when Faceswap starts up or shuts down.

icons

The faceswap icons for all parts of the GUI. The dictionary key is the icon name (str) the value is the icon sized and formatted for display (PIL.ImageTK.PhotoImage).

Example

>>> icons = get_images().icons
>>> save = icons["save"]
>>> button = ttk.Button(parent, image=save)
>>> button.pack()
Type:dict
load_latest_preview(thumbnail_size, frame_dims)

Load the latest preview image for extract and convert.

Retrieves the latest preview images from the faceswap output folder, resizes to thumbnails and lays out for display. Places the images into previewoutput for loading into the display panel.

Parameters:
  • thumbnail_size (int) – The size of each thumbnail that should be created
  • frame_dims (tuple) – The (width (int), height (int)) of the display panel that will display the preview
load_training_preview()

Load the training preview images.

Reads the training image currently stored in the cache folder and loads them to previewtrain for retrieval in the GUI.

previewoutput

First item in the tuple is the extract or convert preview image (PIL.Image), the second item is the image in a format that tkinter can display (PIL.ImageTK.PhotoImage).

The value of the property is None if no extract or convert task is running or there are no files available in the output folder.

Type:Tuple or None
previewtrain

The training preview images. Dictionary key is the image name (str). Dictionary values are a list of the training image (PIL.Image), the image formatted for tkinter display (PIL.ImageTK.PhotoImage), the last modification time of the image (float).

The value of this property is None if training is not running or there are no preview images available.

Type:dict or None
resize_image(name, frame_dims)

Resize the training preview image based on the passed in frame size.

If the canvas that holds the preview image changes, update the image size to fit the new canvas and refresh previewtrain.

Parameters:
  • name (str) – The name of the training image to be resized
  • frame_dims (tuple) – The (width (int), height (int)) of the display panel that will display the preview
set_faceswap_output_path(location)

Set the path that will contain the output from an Extract or Convert task.

Required so that the GUI can fetch output images to display for return in previewoutput.

Parameters:location (str) – The output location that has been specified for an Extract or Convert task
class lib.gui.utils.LongRunningTask(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=True, widget=None)

Bases: threading.Thread

Runs long running tasks in a background thread to prevent the GUI from becoming unresponsive.

This is sub-classed from Threading.Thread so check documentation there for base parameters. Additional parameters listed below.

Parameters:widget (tkinter object, optional) – The widget that this LongRunningTask is associated with. Used for setting the busy cursor in the correct location. Default: None.
complete

Event is set if the thread has completed its task, otherwise it is unset.

Type:threading.Event
get_result()

Return the result from the given task.

Returns:The result of the thread will depend on the given task. If a call is made to get_result() prior to the thread completing its task then None will be returned
Return type:varies
run()

Commence the given task in a background thread.

class lib.gui.utils.PreviewTrigger

Bases: object

Trigger to indicate to underlying Faceswap process that the preview image should be updated.

Writes a file to the cache folder that is picked up by the main process.

clear()

Remove the trigger file from the cache folder

set()

Place the trigger file into the cache folder

lib.gui.utils.get_config()

Get the Master GUI configuration.

Returns:The Master GUI Config
Return type:Config
lib.gui.utils.get_images()

Get the Master GUI Images handler.

Returns:The Master GUI Images handler
Return type:Images
lib.gui.utils.initialize_config(root, cli_opts, statusbar)

Initialize the GUI Master Config and add to global constant.

This should only be called once on first GUI startup. Future access to Config should only be executed through get_config().

Parameters:
  • root (tkinter.Tk) – The root Tkinter object
  • cli_opts (lib.gui.options.CliOpts) – The command line options object
  • statusbar (lib.gui.custom_widgets.StatusBar) – The GUI Status bar
lib.gui.utils.initialize_images()

Initialize the Images handler and add to global constant.

This should only be called once on first GUI startup. Future access to Images handler should only be executed through get_images().

lib.gui.utils.preview_trigger()

Set the global preview trigger if it has not always been set and return.

Returns:The trigger to indicate to the main faceswap process that it should perform a training preview update
Return type:PreviewTrigger