code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _isURITrustableAndTrusted(self, URIToTest): """Returns a tuple of booleans: (trustable, trusted). A given URI is "trustable" if it uses HTTP or HTTPS (constants.TRUSTABLE_WEB_PROTOCOLS). A given URI is "trusted" if it matches an entry in the trustedDomains config. Such an entry is considered matching if the domain is the same and the path is a prefix of the given URI's path. A "trustable" URI is always "trusted" if the config onlySwitchToTrustedDomains is false. """ o = urlparse(URIToTest) trustable = o.scheme in constants.TRUSTABLE_WEB_PROTOCOLS if not trustable: # untrustable URIs are never trusted, return early return False, False if not self._config['onlySwitchToTrustedDomains']: # trust all trustable URIs in this case return trustable, True # check for matching trusted domains if self._config['trustedDomains']: for entry in self._config['trustedDomains']: trustedDomain, _, path = entry.partition('/') foundMatch = False if o.hostname in (trustedDomain, "www." + trustedDomain): foundMatch = True elif "*" in trustedDomain: wildcardRegex = "^("+re.escape(trustedDomain).replace("\\*","([^.]+)")+")$" wildcardMatch = bool(re.fullmatch(wildcardRegex, o.hostname, re.IGNORECASE)) if wildcardMatch: foundMatch = True if not foundMatch: continue if path and not o.path.startswith('/' + path): # trusted domain has a path component and it does not match continue # match found, trust this domain return trustable, True # no matches found, do not trust this domain return trustable, False
Returns a tuple of booleans: (trustable, trusted). A given URI is "trustable" if it uses HTTP or HTTPS (constants.TRUSTABLE_WEB_PROTOCOLS). A given URI is "trusted" if it matches an entry in the trustedDomains config. Such an entry is considered matching if the domain is the same and the path is a prefix of the given URI's path. A "trustable" URI is always "trusted" if the config onlySwitchToTrustedDomains is false.
_isURITrustableAndTrusted
python
Syncplay/syncplay
syncplay/client.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/client.py
Apache-2.0
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ExceptionToCheck: the exception to check. may be a tuple of excpetions to check :type ExceptionToCheck: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int :param logger: logger to use. If None, print :type logger: logging.Logger instance """ def deco_retry(f): def f_retry(*args, **kwargs): mtries, mdelay = tries, delay try_one_last_time = True while mtries > 1: try: # try_one_last_time = False return f(*args, **kwargs) break except ExceptionToCheck as e: if logger: msg = getMessage("retrying-notification").format(str(e), mdelay) logger.warning(msg) time.sleep(mdelay) mtries -= 1 mdelay *= backoff if try_one_last_time: return f(*args, **kwargs) return return f_retry # true decorator return deco_retry
Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ExceptionToCheck: the exception to check. may be a tuple of excpetions to check :type ExceptionToCheck: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int :param logger: logger to use. If None, print :type logger: logging.Logger instance
retry
python
Syncplay/syncplay
syncplay/utils.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/utils.py
Apache-2.0
def write(self, fp): """Write an .ini-format representation of the configuration state.""" if self._defaults: fp.write("[%s]\n" % DEFAULTSECT) for (key, value) in list(self._defaults.items()): fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in self._sections: fp.write("[%s]\n" % section) for (key, value) in list(self._sections[section].items()): if key == "__name__": continue if (value is not None) or (self._optcre == self.OPTCRE): key = " = ".join((key, str(value).replace('\n', '\n\t'))) fp.write("%s\n" % key) fp.write("\n")
Write an .ini-format representation of the configuration state.
write
python
Syncplay/syncplay
syncplay/ui/ConfigurationGetter.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/ui/ConfigurationGetter.py
Apache-2.0
def _qInstallMessageHandler(handler): """Install a message handler that works in all bindings Args: handler: A function that takes 3 arguments, or None """ def messageOutputHandler(*args): # In Qt4 bindings, message handlers are passed 2 arguments # In Qt5 bindings, message handlers are passed 3 arguments # The first argument is a QtMsgType # The last argument is the message to be printed # The Middle argument (if passed) is a QMessageLogContext if len(args) == 3: msgType, logContext, msg = args elif len(args) == 2: msgType, msg = args logContext = None else: raise TypeError( "handler expected 2 or 3 arguments, got {0}".format(len(args))) if isinstance(msg, bytes): # In python 3, some bindings pass a bytestring, which cannot be # used elsewhere. Decoding a python 2 or 3 bytestring object will # consistently return a unicode object. msg = msg.decode() handler(msgType, logContext, msg) passObject = messageOutputHandler if handler else handler if Qt.IsPySide or Qt.IsPyQt4: return Qt._QtCore.qInstallMsgHandler(passObject) elif Qt.IsPySide2 or Qt.IsPyQt5 or Qt.IsPySide6: return Qt._QtCore.qInstallMessageHandler(passObject)
Install a message handler that works in all bindings Args: handler: A function that takes 3 arguments, or None
_qInstallMessageHandler
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _wrapinstance(ptr, base=None): """Enable implicit cast of pointer to most suitable class This behaviour is available in sip per default. Based on http://nathanhorne.com/pyqtpyside-wrap-instance Usage: This mechanism kicks in under these circumstances. 1. Qt.py is using PySide 1 or 2. 2. A `base` argument is not provided. See :func:`QtCompat.wrapInstance()` Arguments: ptr (long): Pointer to QObject in memory base (QObject, optional): Base class to wrap with. Defaults to QObject, which should handle anything. """ assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>" assert (base is None) or issubclass(base, Qt.QtCore.QObject), ( "Argument 'base' must be of type <QObject>") if Qt.IsPyQt4 or Qt.IsPyQt5: func = getattr(Qt, "_sip").wrapinstance elif Qt.IsPySide2: func = getattr(Qt, "_shiboken2").wrapInstance elif Qt.IsPySide6: func = getattr(Qt, "_shiboken6").wrapInstance elif Qt.IsPySide: func = getattr(Qt, "_shiboken").wrapInstance else: raise AttributeError("'module' has no attribute 'wrapInstance'") if base is None: if Qt.IsPyQt4 or Qt.IsPyQt5: base = Qt.QtCore.QObject else: q_object = func(long(ptr), Qt.QtCore.QObject) meta_object = q_object.metaObject() while True: class_name = meta_object.className() try: base = getattr(Qt.QtWidgets, class_name) except AttributeError: try: base = getattr(Qt.QtCore, class_name) except AttributeError: meta_object = meta_object.superClass() continue break return func(long(ptr), base)
Enable implicit cast of pointer to most suitable class This behaviour is available in sip per default. Based on http://nathanhorne.com/pyqtpyside-wrap-instance Usage: This mechanism kicks in under these circumstances. 1. Qt.py is using PySide 1 or 2. 2. A `base` argument is not provided. See :func:`QtCompat.wrapInstance()` Arguments: ptr (long): Pointer to QObject in memory base (QObject, optional): Base class to wrap with. Defaults to QObject, which should handle anything.
_wrapinstance
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _isvalid(object): """Check if the object is valid to use in Python runtime. Usage: See :func:`QtCompat.isValid()` Arguments: object (QObject): QObject to check the validity of. """ if hasattr(Qt, "_shiboken2"): return getattr(Qt, "_shiboken2").isValid(object) elif hasattr(Qt, "_shiboken"): return getattr(Qt, "_shiboken").isValid(object) elif hasattr(Qt, "_sip"): return not getattr(Qt, "_sip").isdeleted(object) else: raise AttributeError("'module' has no attribute isValid")
Check if the object is valid to use in Python runtime. Usage: See :func:`QtCompat.isValid()` Arguments: object (QObject): QObject to check the validity of.
_isvalid
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _loadUi(uifile, baseinstance=None): """Dynamically load a user interface from the given `uifile` This function calls `uic.loadUi` if using PyQt bindings, else it implements a comparable binding for PySide. Documentation: http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi Arguments: uifile (str): Absolute path to Qt Designer file. baseinstance (QWidget): Instantiated QWidget or subclass thereof Return: baseinstance if `baseinstance` is not `None`. Otherwise return the newly created instance of the user interface. """ if hasattr(Qt, "_uic"): return Qt._uic.loadUi(uifile, baseinstance) elif hasattr(Qt, "_QtUiTools"): # Implement `PyQt5.uic.loadUi` for PySide(2) class _UiLoader(Qt._QtUiTools.QUiLoader): """Create the user interface in a base instance. Unlike `Qt._QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interface in an existing instance of the top-level class if needed. This mimics the behaviour of `PyQt5.uic.loadUi`. """ def __init__(self, baseinstance): super(_UiLoader, self).__init__(baseinstance) self.baseinstance = baseinstance self.custom_widgets = {} def _loadCustomWidgets(self, etree): """ Workaround to pyside-77 bug. From QUiLoader doc we should use registerCustomWidget method. But this causes a segfault on some platforms. Instead we fetch from customwidgets DOM node the python class objects. Then we can directly use them in createWidget method. """ def headerToModule(header): """ Translate a header file to python module path foo/bar.h => foo.bar """ # Remove header extension module = os.path.splitext(header)[0] # Replace os separator by python module separator return module.replace("/", ".").replace("\\", ".") custom_widgets = etree.find("customwidgets") if custom_widgets is None: return for custom_widget in custom_widgets: class_name = custom_widget.find("class").text header = custom_widget.find("header").text module = importlib.import_module(headerToModule(header)) self.custom_widgets[class_name] = getattr(module, class_name) def load(self, uifile, *args, **kwargs): from xml.etree.ElementTree import ElementTree # For whatever reason, if this doesn't happen then # reading an invalid or non-existing .ui file throws # a RuntimeError. etree = ElementTree() etree.parse(uifile) self._loadCustomWidgets(etree) widget = Qt._QtUiTools.QUiLoader.load( self, uifile, *args, **kwargs) # Workaround for PySide 1.0.9, see issue #208 widget.parentWidget() return widget def createWidget(self, class_name, parent=None, name=""): """Called for each widget defined in ui file Overridden here to populate `baseinstance` instead. """ if parent is None and self.baseinstance: # Supposed to create the top-level widget, # return the base instance instead return self.baseinstance # For some reason, Line is not in the list of available # widgets, but works fine, so we have to special case it here. if class_name in self.availableWidgets() + ["Line"]: # Create a new widget for child widgets widget = Qt._QtUiTools.QUiLoader.createWidget(self, class_name, parent, name) elif class_name in self.custom_widgets: widget = self.custom_widgets[class_name](parent=parent) else: raise Exception("Custom widget '%s' not supported" % class_name) if self.baseinstance: # Set an attribute for the new child widget on the base # instance, just like PyQt5.uic.loadUi does. setattr(self.baseinstance, name, widget) return widget widget = _UiLoader(baseinstance).load(uifile) Qt.QtCore.QMetaObject.connectSlotsByName(widget) return widget else: raise NotImplementedError("No implementation available for loadUi")
Dynamically load a user interface from the given `uifile` This function calls `uic.loadUi` if using PyQt bindings, else it implements a comparable binding for PySide. Documentation: http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi Arguments: uifile (str): Absolute path to Qt Designer file. baseinstance (QWidget): Instantiated QWidget or subclass thereof Return: baseinstance if `baseinstance` is not `None`. Otherwise return the newly created instance of the user interface.
_loadUi
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _loadCustomWidgets(self, etree): """ Workaround to pyside-77 bug. From QUiLoader doc we should use registerCustomWidget method. But this causes a segfault on some platforms. Instead we fetch from customwidgets DOM node the python class objects. Then we can directly use them in createWidget method. """ def headerToModule(header): """ Translate a header file to python module path foo/bar.h => foo.bar """ # Remove header extension module = os.path.splitext(header)[0] # Replace os separator by python module separator return module.replace("/", ".").replace("\\", ".") custom_widgets = etree.find("customwidgets") if custom_widgets is None: return for custom_widget in custom_widgets: class_name = custom_widget.find("class").text header = custom_widget.find("header").text module = importlib.import_module(headerToModule(header)) self.custom_widgets[class_name] = getattr(module, class_name)
Workaround to pyside-77 bug. From QUiLoader doc we should use registerCustomWidget method. But this causes a segfault on some platforms. Instead we fetch from customwidgets DOM node the python class objects. Then we can directly use them in createWidget method.
_loadCustomWidgets
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def headerToModule(header): """ Translate a header file to python module path foo/bar.h => foo.bar """ # Remove header extension module = os.path.splitext(header)[0] # Replace os separator by python module separator return module.replace("/", ".").replace("\\", ".")
Translate a header file to python module path foo/bar.h => foo.bar
headerToModule
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def createWidget(self, class_name, parent=None, name=""): """Called for each widget defined in ui file Overridden here to populate `baseinstance` instead. """ if parent is None and self.baseinstance: # Supposed to create the top-level widget, # return the base instance instead return self.baseinstance # For some reason, Line is not in the list of available # widgets, but works fine, so we have to special case it here. if class_name in self.availableWidgets() + ["Line"]: # Create a new widget for child widgets widget = Qt._QtUiTools.QUiLoader.createWidget(self, class_name, parent, name) elif class_name in self.custom_widgets: widget = self.custom_widgets[class_name](parent=parent) else: raise Exception("Custom widget '%s' not supported" % class_name) if self.baseinstance: # Set an attribute for the new child widget on the base # instance, just like PyQt5.uic.loadUi does. setattr(self.baseinstance, name, widget) return widget
Called for each widget defined in ui file Overridden here to populate `baseinstance` instead.
createWidget
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _import_sub_module(module, name): """import_sub_module will mimic the function of importlib.import_module""" module = __import__(module.__name__ + "." + name) for level in name.split("."): module = getattr(module, level) return module
import_sub_module will mimic the function of importlib.import_module
_import_sub_module
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _reassign_misplaced_members(binding): """Apply misplaced members from `binding` to Qt.py Arguments: binding (dict): Misplaced members """ for src, dst in _misplaced_members[binding].items(): dst_value = None src_parts = src.split(".") src_module = src_parts[0] src_member = None if len(src_parts) > 1: src_member = src_parts[1:] if isinstance(dst, (list, tuple)): dst, dst_value = dst dst_parts = dst.split(".") dst_module = dst_parts[0] dst_member = None if len(dst_parts) > 1: dst_member = dst_parts[1] # Get the member we want to store in the namesapce. if not dst_value: try: _part = getattr(Qt, "_" + src_module) while src_member: member = src_member.pop(0) _part = getattr(_part, member) dst_value = _part except AttributeError: # If the member we want to store in the namespace does not # exist, there is no need to continue. This can happen if a # request was made to rename a member that didn't exist, for # example if QtWidgets isn't available on the target platform. _log("Misplaced member has no source: {0}".format(src)) continue try: src_object = getattr(Qt, dst_module) except AttributeError: if dst_module not in _common_members: # Only create the Qt parent module if its listed in # _common_members. Without this check, if you remove QtCore # from _common_members, the default _misplaced_members will add # Qt.QtCore so it can add Signal, Slot, etc. msg = 'Not creating missing member module "{m}" for "{c}"' _log(msg.format(m=dst_module, c=dst_member)) continue # If the dst is valid but the Qt parent module does not exist # then go ahead and create a new module to contain the member. setattr(Qt, dst_module, _new_module(dst_module)) src_object = getattr(Qt, dst_module) # Enable direct import of the new module sys.modules[__name__ + "." + dst_module] = src_object if not dst_value: dst_value = getattr(Qt, "_" + src_module) if src_member: dst_value = getattr(dst_value, src_member) setattr( src_object, dst_member or dst_module, dst_value )
Apply misplaced members from `binding` to Qt.py Arguments: binding (dict): Misplaced members
_reassign_misplaced_members
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _build_compatibility_members(binding, decorators=None): """Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can be used to change the returned value to a standard value. The key should be the classname, the value is a dict where the keys are the target method names, and the values are the decorator functions. """ decorators = decorators or dict() # Allow optional site-level customization of the compatibility members. # This method does not need to be implemented in QtSiteConfig. try: import QtSiteConfig except ImportError: pass else: if hasattr(QtSiteConfig, 'update_compatibility_decorators'): QtSiteConfig.update_compatibility_decorators(binding, decorators) _QtCompat = type("QtCompat", (object,), {}) for classname, bindings in _compatibility_members[binding].items(): attrs = {} for target, binding in bindings.items(): namespaces = binding.split('.') try: src_object = getattr(Qt, "_" + namespaces[0]) except AttributeError as e: _log("QtCompat: AttributeError: %s" % e) # Skip reassignment of non-existing members. # This can happen if a request was made to # rename a member that didn't exist, for example # if QtWidgets isn't available on the target platform. continue # Walk down any remaining namespace getting the object assuming # that if the first namespace exists the rest will exist. for namespace in namespaces[1:]: src_object = getattr(src_object, namespace) # decorate the Qt method if a decorator was provided. if target in decorators.get(classname, []): # staticmethod must be called on the decorated method to # prevent a TypeError being raised when the decorated method # is called. src_object = staticmethod( decorators[classname][target](src_object)) attrs[target] = src_object # Create the QtCompat class and install it into the namespace compat_class = type(classname, (_QtCompat,), attrs) setattr(Qt.QtCompat, classname, compat_class)
Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can be used to change the returned value to a standard value. The key should be the classname, the value is a dict where the keys are the target method names, and the values are the decorator functions.
_build_compatibility_members
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _pyside6(): """Initialise PySide6 These functions serve to test the existence of a binding along with set it up in such a way that it aligns with the final step; adding members from the original binding to Qt.py """ import PySide6 as module extras = ["QtUiTools"] try: try: # Before merge of PySide and shiboken import shiboken6 except ImportError: # After merge of PySide and shiboken, May 2017 from PySide6 import shiboken6 extras.append("shiboken6") except ImportError: pass _setup(module, extras) Qt.__binding_version__ = module.__version__ if hasattr(Qt, "_shiboken6"): Qt.QtCompat.wrapInstance = _wrapinstance Qt.QtCompat.getCppPointer = _getcpppointer Qt.QtCompat.delete = shiboken6.delete if hasattr(Qt, "_QtUiTools"): Qt.QtCompat.loadUi = _loadUi if hasattr(Qt, "_QtCore"): Qt.__qt_version__ = Qt._QtCore.qVersion() Qt.QtCompat.dataChanged = ( lambda self, topleft, bottomright, roles=None: self.dataChanged.emit(topleft, bottomright, roles or []) ) if hasattr(Qt, "_QtWidgets"): Qt.QtCompat.setSectionResizeMode = \ Qt._QtWidgets.QHeaderView.setSectionResizeMode _reassign_misplaced_members("PySide6") _build_compatibility_members("PySide6")
Initialise PySide6 These functions serve to test the existence of a binding along with set it up in such a way that it aligns with the final step; adding members from the original binding to Qt.py
_pyside6
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _pyside2(): """Initialise PySide2 These functions serve to test the existence of a binding along with set it up in such a way that it aligns with the final step; adding members from the original binding to Qt.py """ import PySide2 as module extras = ["QtUiTools"] try: try: # Before merge of PySide and shiboken import shiboken2 except ImportError: # After merge of PySide and shiboken, May 2017 from PySide2 import shiboken2 extras.append("shiboken2") except ImportError: pass _setup(module, extras) Qt.__binding_version__ = module.__version__ if hasattr(Qt, "_shiboken2"): Qt.QtCompat.wrapInstance = _wrapinstance Qt.QtCompat.getCppPointer = _getcpppointer Qt.QtCompat.delete = shiboken2.delete if hasattr(Qt, "_QtUiTools"): Qt.QtCompat.loadUi = _loadUi if hasattr(Qt, "_QtCore"): Qt.__qt_version__ = Qt._QtCore.qVersion() Qt.QtCompat.dataChanged = ( lambda self, topleft, bottomright, roles=None: self.dataChanged.emit(topleft, bottomright, roles or []) ) if hasattr(Qt, "_QtWidgets"): Qt.QtCompat.setSectionResizeMode = \ Qt._QtWidgets.QHeaderView.setSectionResizeMode _reassign_misplaced_members("PySide2") _build_compatibility_members("PySide2")
Initialise PySide2 These functions serve to test the existence of a binding along with set it up in such a way that it aligns with the final step; adding members from the original binding to Qt.py
_pyside2
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _standardizeQFileDialog(some_function): """Decorator that makes PyQt4 return conform to other bindings""" def wrapper(*args, **kwargs): ret = (some_function(*args, **kwargs)) # PyQt4 only returns the selected filename, force it to a # standard return of the selected filename, and a empty string # for the selected filter return ret, '' wrapper.__doc__ = some_function.__doc__ wrapper.__name__ = some_function.__name__ return wrapper
Decorator that makes PyQt4 return conform to other bindings
_standardizeQFileDialog
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _convert(lines): """Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = _convert(f.readlines()) """ def parse(line): line = line.replace("from PySide2 import", "from Qt import QtCompat,") line = line.replace("QtWidgets.QApplication.translate", "QtCompat.translate") if "QtCore.SIGNAL" in line: raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 " "and so Qt.py does not support it: you " "should avoid defining signals inside " "your ui files.") return line parsed = list() for line in lines: line = parse(line) parsed.append(line) return parsed
Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = _convert(f.readlines())
_convert
python
Syncplay/syncplay
syncplay/vendor/Qt.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py
Apache-2.0
def _add(self, xer, primary, type): """ Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example). """ if xer not in primary: primary[xer] = TwistedSocketNotifier(None, self, xer, type)
Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example).
_add
python
Syncplay/syncplay
syncplay/vendor/qt5reactor.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/qt5reactor.py
Apache-2.0
def _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """ if xer in primary: notifier = primary.pop(xer) notifier.shutdown()
Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away.
_remove
python
Syncplay/syncplay
syncplay/vendor/qt5reactor.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/qt5reactor.py
Apache-2.0
def doIteration(self, delay=None, fromqt=False): """This method is called by a Qt timer or by network activity on a file descriptor""" if not self.running and self._blockApp: self._blockApp.quit() self._timer.stop() if delay is None: delay = 0 delay = max(delay, 1) if not fromqt: self.qApp.processEvents(QEventLoop.AllEvents, delay * 1000) timeout = self.timeout() if timeout is not None: self._timer.setInterval(timeout * 1000) self._timer.start()
This method is called by a Qt timer or by network activity on a file descriptor
doIteration
python
Syncplay/syncplay
syncplay/vendor/qt5reactor.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/qt5reactor.py
Apache-2.0
def iterate(self, delay=None, fromqt=False): """See twisted.internet.interfaces.IReactorCore.iterate.""" self.runUntilCurrent() self.doEvents() self.doIteration(delay, fromqt=fromqt)
See twisted.internet.interfaces.IReactorCore.iterate.
iterate
python
Syncplay/syncplay
syncplay/vendor/qt5reactor.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/qt5reactor.py
Apache-2.0
def theme(): """ Uses the Windows Registry to detect if the user is using Dark Mode """ # Registry will return 0 if Windows is in Dark Mode and 1 if Windows is in Light Mode. This dictionary converts that output into the text that the program is expecting. valueMeaning = {0: "Dark", 1: "Light"} # In HKEY_CURRENT_USER, get the Personalisation Key. try: key = getKey(hkey, "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize") # In the Personalisation Key, get the AppsUseLightTheme subkey. This returns a tuple. # The first item in the tuple is the result we want (0 or 1 indicating Dark Mode or Light Mode); the other value is the type of subkey e.g. DWORD, QWORD, String, etc. subkey = getSubkeyValue(key, "AppsUseLightTheme")[0] except FileNotFoundError: # some headless Windows instances (e.g. GitHub Actions or Docker images) do not have this key return None return valueMeaning[subkey]
Uses the Windows Registry to detect if the user is using Dark Mode
theme
python
Syncplay/syncplay
syncplay/vendor/darkdetect/_windows_detect.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/darkdetect/_windows_detect.py
Apache-2.0
def __init__(self, ipc_socket, callback=None, quit_callback=None): """Create the wrapper. *ipc_socket* is the pipe name. (Not including \\\\.\\pipe\\) *callback(json_data)* is the function for recieving events. *quit_callback* is called when the socket connection dies. """ ipc_socket = "\\\\.\\pipe\\" + ipc_socket self.callback = callback self.quit_callback = quit_callback access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE limit = 5 # Connection may fail at first. Try 5 times. for _ in range(limit): try: pipe_handle = _winapi.CreateFile( ipc_socket, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING, _winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL ) break except OSError: time.sleep(1) else: raise MPVError("Cannot connect to pipe.") self.socket = PipeConnection(pipe_handle) if self.callback is None: self.callback = lambda data: None threading.Thread.__init__(self)
Create the wrapper. *ipc_socket* is the pipe name. (Not including \\.\pipe\) *callback(json_data)* is the function for recieving events. *quit_callback* is called when the socket connection dies.
__init__
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def send(self, data): """Send *data* to the pipe, encoded as JSON.""" try: self.socket.send_bytes(json.dumps(data).encode('utf-8') + b'\n') except OSError as ex: raise ex
Send *data* to the pipe, encoded as JSON.
send
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def run(self): """Process pipe events. Do not run this directly. Use *start*.""" data = b'' try: while True: current_data = self.socket.recv_bytes(2048) if current_data == b'': break data += current_data if data[-1] != 10: continue data = data.decode('utf-8', 'ignore').encode('utf-8') for item in data.split(b'\n'): if item == b'': continue json_data = json.loads(item) self.callback(json_data) data = b'' except EOFError: if self.quit_callback: self.quit_callback() except Exception as ex: log.error("Pipe connection died.", exc_info=1) if self.quit_callback: self.quit_callback()
Process pipe events. Do not run this directly. Use *start*.
run
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def __init__(self, ipc_socket, callback=None, quit_callback=None): """Create the wrapper. *ipc_socket* is the path to the socket. *callback(json_data)* is the function for recieving events. *quit_callback* is called when the socket connection dies. """ self.ipc_socket = ipc_socket self.callback = callback self.quit_callback = quit_callback self.socket = socket.socket(socket.AF_UNIX) self.socket.connect(self.ipc_socket) if self.callback is None: self.callback = lambda data: None threading.Thread.__init__(self)
Create the wrapper. *ipc_socket* is the path to the socket. *callback(json_data)* is the function for recieving events. *quit_callback* is called when the socket connection dies.
__init__
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def send(self, data): """Send *data* to the socket, encoded as JSON.""" if self.socket is None: raise BrokenPipeError("socket is closed") self.socket.send(json.dumps(data).encode('utf-8') + b'\n')
Send *data* to the socket, encoded as JSON.
send
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def run(self): """Process socket events. Do not run this directly. Use *start*.""" data = b'' try: while True: current_data = self.socket.recv(1024) if current_data == b'': break data += current_data if data[-1] != 10: continue data = data.decode('utf-8', 'ignore').encode('utf-8') for item in data.split(b'\n'): if item == b'': continue json_data = json.loads(item) self.callback(json_data) data = b'' except Exception as ex: log.error("Socket connection died.", exc_info=1) if self.quit_callback: self.quit_callback()
Process socket events. Do not run this directly. Use *start*.
run
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def __init__(self, ipc_socket, mpv_location=None, env=None, **kwargs): """ Create and start the MPV process. Will block until socket/pipe is available. *ipc_socket* is the path to the Unix/Linux socket or name of the Windows pipe. *mpv_location* is the path to mpv. If left unset it tries the one in the PATH. All other arguments are forwarded to MPV as command-line arguments. """ if mpv_location is None: if os.name == 'nt': mpv_location = "mpv.exe" else: mpv_location = "mpv" log.debug("Staring MPV from {0}.".format(mpv_location)) if os.name == 'nt': ipc_socket = "\\\\.\\pipe\\" + ipc_socket if os.name != 'nt' and os.path.exists(ipc_socket): os.remove(ipc_socket) log.debug("Using IPC socket {0} for MPV.".format(ipc_socket)) self.ipc_socket = ipc_socket args = self._get_arglist(mpv_location, **kwargs) self._start_process(ipc_socket, args, env=env)
Create and start the MPV process. Will block until socket/pipe is available. *ipc_socket* is the path to the Unix/Linux socket or name of the Windows pipe. *mpv_location* is the path to mpv. If left unset it tries the one in the PATH. All other arguments are forwarded to MPV as command-line arguments.
__init__
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def __init__(self, ipc_socket, callback=None, quit_callback=None): """Create the wrapper. *ipc_socket* is the path to the Unix/Linux socket or name of the Windows pipe. *callback(event_name, data)* is the function for recieving events. *quit_callback* is called when the socket connection to MPV dies. """ Socket = UnixSocket if os.name == 'nt': Socket = WindowsSocket self.callback = callback self.quit_callback = quit_callback if self.callback is None: self.callback = lambda event, data: None self.socket = Socket(ipc_socket, self.event_callback, self.quit_callback) self.socket.start() self.command_id = 1 self.rid_lock = threading.Lock() self.socket_lock = threading.Lock() self.cid_result = {} self.cid_wait = {}
Create the wrapper. *ipc_socket* is the path to the Unix/Linux socket or name of the Windows pipe. *callback(event_name, data)* is the function for recieving events. *quit_callback* is called when the socket connection to MPV dies.
__init__
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def event_callback(self, data): """Internal callback for recieving events from MPV.""" if "request_id" in data: self.cid_result[data["request_id"]] = data self.cid_wait[data["request_id"]].set() elif "event" in data: self.callback(data["event"], data)
Internal callback for recieving events from MPV.
event_callback
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def command(self, command, *args): """ Issue a command to MPV. Will block until completed or timeout is reached. *command* is the name of the MPV command All further arguments are forwarded to the MPV command. Throws TimeoutError if timeout of 120 seconds is reached. """ self.rid_lock.acquire() command_id = self.command_id self.command_id += 1 self.rid_lock.release() event = threading.Event() self.cid_wait[command_id] = event command_list = [command] command_list.extend(args) try: self.socket_lock.acquire() self.socket.send({"command":command_list, "request_id": command_id}) finally: self.socket_lock.release() has_event = event.wait(timeout=TIMEOUT) if has_event: data = self.cid_result[command_id] del self.cid_result[command_id] del self.cid_wait[command_id] if data["error"] != "success": if data["error"] == "property unavailable": return None raise MPVError(data["error"]) else: return data.get("data") else: raise TimeoutError("No response from MPV.")
Issue a command to MPV. Will block until completed or timeout is reached. *command* is the name of the MPV command All further arguments are forwarded to the MPV command. Throws TimeoutError if timeout of 120 seconds is reached.
command
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def run(self): """Process socket events. Do not run this directly. Use *start*.""" while True: event = self.queue.get() if event == "quit": break try: event[0](*event[1]) except Exception: log.error("EventHandler caught exception from {0}.".format(event), exc_info=1)
Process socket events. Do not run this directly. Use *start*.
run
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def __init__(self, start_mpv=True, ipc_socket=None, mpv_location=None, log_handler=None, loglevel=None, quit_callback=None, **kwargs): """ Create the interface to MPV and process instance. *start_mpv* will start an MPV process if true. (Default: True) *ipc_socket* is the path to the Unix/Linux socket or name of Windows pipe. (Default: Random Temp File) *mpv_location* is the location of MPV for *start_mpv*. (Default: Use MPV in PATH) *log_handler(level, prefix, text)* is an optional handler for log events. (Default: Disabled) *loglevel* is the level for log messages. Levels are fatal, error, warn, info, v, debug, trace. (Default: Disabled) *quit_callback* is called when the socket connection to MPV dies. All other arguments are forwarded to MPV as command-line arguments if *start_mpv* is used. """ self.properties = {} self.event_bindings = {} self.key_bindings = {} self.property_bindings = {} self.mpv_process = None self.mpv_inter = None self.quit_callback = quit_callback self.event_handler = EventHandler() self.event_handler.start() if ipc_socket is None: rand_file = "mpv{0}".format(random.randint(0, 2**48)) if os.name == "nt": ipc_socket = rand_file else: ipc_socket = "/tmp/{0}".format(rand_file) if start_mpv: self._start_mpv(ipc_socket, mpv_location, **kwargs) self.mpv_inter = MPVInter(ipc_socket, self._callback, self._quit_callback) self.properties = set(x.replace("-", "_") for x in self.command("get_property", "property-list")) try: command_list = [x["name"] for x in self.command("get_property", "command-list")] except MPVError: command_list = FALLBACK_COMMAND_LIST for command in command_list: object.__setattr__(self, command.replace("-", "_"), self._get_wrapper(command)) self._dir = list(self.properties) self._dir.extend(object.__dir__(self)) self.observer_id = 1 self.observer_lock = threading.Lock() self.keybind_id = 1 self.keybind_lock = threading.Lock() if log_handler is not None and loglevel is not None: self.command("request_log_messages", loglevel) @self.on_event("log-message") def log_handler_event(data): self.event_handler.put_task(log_handler, data["level"], data["prefix"], data["text"].strip()) @self.on_event("property-change") def event_handler(data): if data.get("id") in self.property_bindings: self.event_handler.put_task(self.property_bindings[data["id"]], data["name"], data.get("data")) @self.on_event("client-message") def client_message_handler(data): args = data["args"] if len(args) == 2 and args[0] == "custom-bind": self.event_handler.put_task(self.key_bindings[args[1]])
Create the interface to MPV and process instance. *start_mpv* will start an MPV process if true. (Default: True) *ipc_socket* is the path to the Unix/Linux socket or name of Windows pipe. (Default: Random Temp File) *mpv_location* is the location of MPV for *start_mpv*. (Default: Use MPV in PATH) *log_handler(level, prefix, text)* is an optional handler for log events. (Default: Disabled) *loglevel* is the level for log messages. Levels are fatal, error, warn, info, v, debug, trace. (Default: Disabled) *quit_callback* is called when the socket connection to MPV dies. All other arguments are forwarded to MPV as command-line arguments if *start_mpv* is used.
__init__
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def bind_event(self, name, callback): """ Bind a callback to an MPV event. *name* is the MPV event name. *callback(event_data)* is the function to call. """ if name not in self.event_bindings: self.event_bindings[name] = set() self.event_bindings[name].add(callback)
Bind a callback to an MPV event. *name* is the MPV event name. *callback(event_data)* is the function to call.
bind_event
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def on_event(self, name): """ Decorator to bind a callback to an MPV event. @on_event(name) def my_callback(event_data): pass """ def wrapper(func): self.bind_event(name, func) return func return wrapper
Decorator to bind a callback to an MPV event. @on_event(name) def my_callback(event_data): pass
on_event
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def on_key_press(self, name): """ Decorator to bind a callback to an MPV keypress event. @on_key_press(key_name) def my_callback(): pass """ def wrapper(func): self.bind_key_press(name, func) return func return wrapper
Decorator to bind a callback to an MPV keypress event. @on_key_press(key_name) def my_callback(): pass
on_key_press
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def bind_key_press(self, name, callback): """ Bind a callback to an MPV keypress event. *name* is the key symbol. *callback()* is the function to call. """ self.keybind_lock.acquire() keybind_id = self.keybind_id self.keybind_id += 1 self.keybind_lock.release() bind_name = "bind{0}".format(keybind_id) self.key_bindings["bind{0}".format(keybind_id)] = callback try: self.keybind(name, "script-message custom-bind {0}".format(bind_name)) except MPVError: self.define_section(bind_name, "{0} script-message custom-bind {1}".format(name, bind_name)) self.enable_section(bind_name)
Bind a callback to an MPV keypress event. *name* is the key symbol. *callback()* is the function to call.
bind_key_press
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def bind_property_observer(self, name, callback): """ Bind a callback to an MPV property change. *name* is the property name. *callback(name, data)* is the function to call. Returns a unique observer ID needed to destroy the observer. """ self.observer_lock.acquire() observer_id = self.observer_id self.observer_id += 1 self.observer_lock.release() self.property_bindings[observer_id] = callback self.command("observe_property", observer_id, name) return observer_id
Bind a callback to an MPV property change. *name* is the property name. *callback(name, data)* is the function to call. Returns a unique observer ID needed to destroy the observer.
bind_property_observer
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def property_observer(self, name): """ Decorator to bind a callback to an MPV property change. @property_observer(property_name) def my_callback(name, data): pass """ def wrapper(func): self.bind_property_observer(name, func) return func return wrapper
Decorator to bind a callback to an MPV property change. @property_observer(property_name) def my_callback(name, data): pass
property_observer
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def wait_for_property(self, name): """ Waits for the value of a property to change. *name* is the name of the property. """ event = threading.Event() first_event = True def handler(*_): nonlocal first_event if first_event == True: first_event = False else: event.set() observer_id = self.bind_property_observer(name, handler) event.wait() self.unbind_property_observer(observer_id)
Waits for the value of a property to change. *name* is the name of the property.
wait_for_property
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def terminate(self, join=True): """Terminate the connection to MPV and process (if *start_mpv* is used).""" if self.mpv_process: self.mpv_process.stop() if self.mpv_inter: self.mpv_inter.stop(join) self.event_handler.stop(join)
Terminate the connection to MPV and process (if *start_mpv* is used).
terminate
python
Syncplay/syncplay
syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py
Apache-2.0
def caption_images( caption_text: str, images_dir: str, overwrite: bool, caption_ext: str, prefix: str, postfix: str, find_text: str, replace_text: str, ): """ Captions images in a given directory with a given caption text. Args: caption_text (str): The text to be used as the caption. images_dir (str): The directory containing the images to be captioned. overwrite (bool): Whether to overwrite existing captions. caption_ext (str): The file extension for the caption files. prefix (str): Text to be added before the caption text. postfix (str): Text to be added after the caption text. find_text (str): Text to be replaced in the caption files. replace_text (str): Text to replace the found text in the caption files. Returns: None """ # Check if images_dir and caption_ext are provided missing_parameters = [] if not images_dir: missing_parameters.append("image directory") if not caption_ext: missing_parameters.append("caption file extension") if missing_parameters: log.info( "The following parameter(s) are missing: {}. " "Please provide these to proceed with captioning the images.".format(", ".join(missing_parameters)) ) return # Log the captioning process if caption_text: log.info(f"Captioning files in {images_dir} with {caption_text}...") # Build the command to run caption.py run_cmd = [ rf"{PYTHON}", rf"{scriptdir}/tools/caption.py", "--caption_text", caption_text, ] # Add optional flags to the command if overwrite: run_cmd.append("--overwrite") if caption_ext: run_cmd.append("--caption_file_ext") run_cmd.append(caption_ext) run_cmd.append(rf"{images_dir}") # Reconstruct the safe command string for display command_to_run = " ".join(run_cmd) log.info(f"Executing command: {command_to_run}") # Set the environment variable for the Python path env = setup_environment() # Run the command in the sd-scripts folder context subprocess.run(run_cmd, env=env, shell=False) # Check if overwrite option is enabled if overwrite: # Add prefix and postfix to caption files or find and replace text in caption files if prefix or postfix or find_text: # Add prefix and/or postfix to caption files add_pre_postfix( folder=images_dir, caption_file_ext=caption_ext, prefix=prefix, postfix=postfix, ) # Replace specified text in caption files if find and replace text is provided if find_text: find_replace( folder_path=images_dir, caption_file_ext=caption_ext, search_text=find_text, replace_text=replace_text, ) else: # Show a message if modification is not possible without overwrite option enabled if prefix or postfix: log.info( 'Could not modify caption files with requested change because the "Overwrite existing captions in folder" option is not selected.' ) # Log the end of the captioning process log.info("Captioning done.")
Captions images in a given directory with a given caption text. Args: caption_text (str): The text to be used as the caption. images_dir (str): The directory containing the images to be captioned. overwrite (bool): Whether to overwrite existing captions. caption_ext (str): The file extension for the caption files. prefix (str): Text to be added before the caption text. postfix (str): Text to be added after the caption text. find_text (str): Text to be replaced in the caption files. replace_text (str): Text to replace the found text in the caption files. Returns: None
caption_images
python
bmaltais/kohya_ss
kohya_gui/basic_caption_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/basic_caption_gui.py
Apache-2.0
def list_images_dirs(path): """ Lists directories within a specified path and updates the current image directory. Parameters: path (str): The directory path to list image directories from. Returns: list: A list of directories within the specified path. """ # Allows list_images_dirs to modify current_images_dir outside of this function nonlocal current_images_dir current_images_dir = path return list(list_dirs(path))
Lists directories within a specified path and updates the current image directory. Parameters: path (str): The directory path to list image directories from. Returns: list: A list of directories within the specified path.
list_images_dirs
python
bmaltais/kohya_ss
kohya_gui/basic_caption_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/basic_caption_gui.py
Apache-2.0
def get_images_in_directory(directory_path): """ Returns a list of image file paths found in the provided directory path. Parameters: - directory_path: A string representing the path to the directory to search for images. Returns: - A list of strings, where each string is the full path to an image file found in the specified directory. """ import os # List of common image file extensions to look for image_extensions = [".jpg", ".jpeg", ".png", ".bmp", ".gif", ".webp"] # Generate a list of image file paths in the directory image_files = [ # constructs the full path to the file os.path.join(directory_path, file) # lists all files and directories in the given path for file in os.listdir(directory_path) # gets the file extension in lowercase if os.path.splitext(file)[1].lower() in image_extensions ] # Return the list of image file paths return image_files
Returns a list of image file paths found in the provided directory path. Parameters: - directory_path: A string representing the path to the directory to search for images. Returns: - A list of strings, where each string is the full path to an image file found in the specified directory.
get_images_in_directory
python
bmaltais/kohya_ss
kohya_gui/blip2_caption_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/blip2_caption_gui.py
Apache-2.0
def generate_caption( file_list, processor, model, device, caption_file_ext=".txt", num_beams=5, repetition_penalty=1.5, length_penalty=1.2, max_new_tokens=40, min_new_tokens=20, do_sample=True, temperature=1.0, top_p=0.0, ): """ Fetches and processes each image in file_list, generates captions based on the image, and writes the generated captions to a file. Parameters: - file_list: A list of file paths pointing to the images to be captioned. - processor: The preprocessor for the BLIP2 model. - model: The BLIP2 model to be used for generating captions. - device: The device on which the computation is performed. - extension: The extension for the output text files. - num_beams: Number of beams for beam search. Default: 5. - repetition_penalty: Penalty for repeating tokens. Default: 1.5. - length_penalty: Penalty for sentence length. Default: 1.2. - max_new_tokens: Maximum number of new tokens to generate. Default: 40. - min_new_tokens: Minimum number of new tokens to generate. Default: 20. """ for file_path in file_list: image = Image.open(file_path) inputs = processor(images=image, return_tensors="pt").to(device, torch.float16) if top_p == 0.0: generated_ids = model.generate( **inputs, num_beams=num_beams, repetition_penalty=repetition_penalty, length_penalty=length_penalty, max_new_tokens=max_new_tokens, min_new_tokens=min_new_tokens, ) else: generated_ids = model.generate( **inputs, do_sample=do_sample, top_p=top_p, max_new_tokens=max_new_tokens, min_new_tokens=min_new_tokens, temperature=temperature, ) generated_text = processor.batch_decode( generated_ids, skip_special_tokens=True )[0].strip() # Construct the output file path by replacing the original file extension with the specified extension output_file_path = os.path.splitext(file_path)[0] + caption_file_ext # Write the generated text to the output file with open(output_file_path, "w", encoding="utf-8") as output_file: output_file.write(generated_text) # Log the image file path with a message about the fact that the caption was generated log.info(f"{file_path} caption was generated")
Fetches and processes each image in file_list, generates captions based on the image, and writes the generated captions to a file. Parameters: - file_list: A list of file paths pointing to the images to be captioned. - processor: The preprocessor for the BLIP2 model. - model: The BLIP2 model to be used for generating captions. - device: The device on which the computation is performed. - extension: The extension for the output text files. - num_beams: Number of beams for beam search. Default: 5. - repetition_penalty: Penalty for repeating tokens. Default: 1.5. - length_penalty: Penalty for sentence length. Default: 1.2. - max_new_tokens: Maximum number of new tokens to generate. Default: 40. - min_new_tokens: Minimum number of new tokens to generate. Default: 20.
generate_caption
python
bmaltais/kohya_ss
kohya_gui/blip2_caption_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/blip2_caption_gui.py
Apache-2.0
def caption_images_beam_search( directory_path, num_beams, repetition_penalty, length_penalty, min_new_tokens, max_new_tokens, caption_file_ext, ): """ Captions all images in the specified directory using the provided prompt. Parameters: - directory_path: A string representing the path to the directory containing the images to be captioned. """ log.info("BLIP2 captionning beam...") if not os.path.isdir(directory_path): log.error(f"Directory {directory_path} does not exist.") return processor, model, device = load_model() image_files = get_images_in_directory(directory_path) generate_caption( file_list=image_files, processor=processor, model=model, device=device, num_beams=int(num_beams), repetition_penalty=float(repetition_penalty), length_penalty=length_penalty, min_new_tokens=int(min_new_tokens), max_new_tokens=int(max_new_tokens), caption_file_ext=caption_file_ext, )
Captions all images in the specified directory using the provided prompt. Parameters: - directory_path: A string representing the path to the directory containing the images to be captioned.
caption_images_beam_search
python
bmaltais/kohya_ss
kohya_gui/blip2_caption_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/blip2_caption_gui.py
Apache-2.0
def caption_images_nucleus( directory_path, do_sample, temperature, top_p, min_new_tokens, max_new_tokens, caption_file_ext, ): """ Captions all images in the specified directory using the provided prompt. Parameters: - directory_path: A string representing the path to the directory containing the images to be captioned. """ log.info("BLIP2 captionning nucleus...") if not os.path.isdir(directory_path): log.error(f"Directory {directory_path} does not exist.") return processor, model, device = load_model() image_files = get_images_in_directory(directory_path) generate_caption( file_list=image_files, processor=processor, model=model, device=device, do_sample=do_sample, temperature=temperature, top_p=top_p, min_new_tokens=int(min_new_tokens), max_new_tokens=int(max_new_tokens), caption_file_ext=caption_file_ext, )
Captions all images in the specified directory using the provided prompt. Parameters: - directory_path: A string representing the path to the directory containing the images to be captioned.
caption_images_nucleus
python
bmaltais/kohya_ss
kohya_gui/blip2_caption_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/blip2_caption_gui.py
Apache-2.0
def caption_images( train_data_dir: str, caption_file_ext: str, batch_size: int, num_beams: int, top_p: float, max_length: int, min_length: int, beam_search: bool, prefix: str = "", postfix: str = "", ) -> None: """ Automatically generates captions for images in the specified directory using the BLIP model. This function prepares and executes a command-line script to process images in batches, applying advanced NLP techniques for caption generation. It supports customization of the captioning process through various parameters like batch size, beam search, and more. Optionally, prefixes and postfixes can be added to captions. Args: train_data_dir (str): The directory containing the images to be captioned. caption_file_ext (str): The extension for the caption files. batch_size (int): The batch size for the captioning process. num_beams (int): The number of beams to use in the captioning process. top_p (float): The top p value to use in the captioning process. max_length (int): The maximum length of the captions. min_length (int): The minimum length of the captions. beam_search (bool): Whether to use beam search in the captioning process. prefix (str): The prefix to add to the captions. postfix (str): The postfix to add to the captions. """ # Check if the image folder is provided if not train_data_dir: log.info("Image folder is missing...") return # Check if the caption file extension is provided if not caption_file_ext: log.info("Please provide an extension for the caption files.") return log.info(f"Captioning files in {train_data_dir}...") # Construct the command to run make_captions.py run_cmd = [rf"{PYTHON}", rf"{scriptdir}/sd-scripts/finetune/make_captions.py"] # Add required arguments run_cmd.append("--batch_size") run_cmd.append(str(batch_size)) run_cmd.append("--num_beams") run_cmd.append(str(num_beams)) run_cmd.append("--top_p") run_cmd.append(str(top_p)) run_cmd.append("--max_length") run_cmd.append(str(max_length)) run_cmd.append("--min_length") run_cmd.append(str(min_length)) # Add optional flags to the command if beam_search: run_cmd.append("--beam_search") if caption_file_ext: run_cmd.append("--caption_extension") run_cmd.append(caption_file_ext) # Add the directory containing the training data run_cmd.append(rf"{train_data_dir}") # Add URL for caption model weights run_cmd.append("--caption_weights") run_cmd.append( rf"https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_large_caption.pth" ) # Set up the environment env = setup_environment() # Reconstruct the safe command string for display command_to_run = " ".join(run_cmd) log.info(f"Executing command: {command_to_run}") # Run the command in the sd-scripts folder context subprocess.run(run_cmd, env=env, shell=False, cwd=rf"{scriptdir}/sd-scripts") # Add prefix and postfix add_pre_postfix( folder=train_data_dir, caption_file_ext=caption_file_ext, prefix=prefix, postfix=postfix, ) log.info("...captioning done")
Automatically generates captions for images in the specified directory using the BLIP model. This function prepares and executes a command-line script to process images in batches, applying advanced NLP techniques for caption generation. It supports customization of the captioning process through various parameters like batch size, beam search, and more. Optionally, prefixes and postfixes can be added to captions. Args: train_data_dir (str): The directory containing the images to be captioned. caption_file_ext (str): The extension for the caption files. batch_size (int): The batch size for the captioning process. num_beams (int): The number of beams to use in the captioning process. top_p (float): The top p value to use in the captioning process. max_length (int): The maximum length of the captions. min_length (int): The minimum length of the captions. beam_search (bool): Whether to use beam search in the captioning process. prefix (str): The prefix to add to the captions. postfix (str): The postfix to add to the captions.
caption_images
python
bmaltais/kohya_ss
kohya_gui/blip_caption_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/blip_caption_gui.py
Apache-2.0
def noise_offset_type_change( noise_offset_type: str, ) -> Tuple[gr.Group, gr.Group]: """ Returns a tuple of Gradio Groups with visibility set based on the noise offset type. Parameters: noise_offset_type (str): The selected noise offset type. Returns: Tuple[gr.Group, gr.Group]: A tuple containing two Gradio Group elements with their visibility set. """ if noise_offset_type == "Original": return (gr.Group(visible=True), gr.Group(visible=False)) else: return (gr.Group(visible=False), gr.Group(visible=True))
Returns a tuple of Gradio Groups with visibility set based on the noise offset type. Parameters: noise_offset_type (str): The selected noise offset type. Returns: Tuple[gr.Group, gr.Group]: A tuple containing two Gradio Group elements with their visibility set.
noise_offset_type_change
python
bmaltais/kohya_ss
kohya_gui/class_advanced_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_advanced_training.py
Apache-2.0
def __init__( self, sdxl_checkbox: gr.Checkbox, learning_rate_value: float = "1e-6", lr_scheduler_value: str = "constant", lr_warmup_value: float = "0", lr_warmup_steps_value: int = 0, finetuning: bool = False, dreambooth: bool = False, config: dict = {}, ) -> None: """ Initializes the BasicTraining object with the given parameters. Args: sdxl_checkbox (gr.Checkbox): Checkbox to enable SDXL training. learning_rate_value (str): Initial learning rate value. lr_scheduler_value (str): Initial learning rate scheduler value. lr_warmup_value (str): Initial learning rate warmup value. finetuning (bool): If True, enables fine-tuning of the model. dreambooth (bool): If True, enables Dreambooth training. """ self.sdxl_checkbox = sdxl_checkbox self.learning_rate_value = learning_rate_value self.lr_scheduler_value = lr_scheduler_value self.lr_warmup_value = lr_warmup_value self.lr_warmup_steps_value= lr_warmup_steps_value self.finetuning = finetuning self.dreambooth = dreambooth self.config = config # Initialize old_lr_warmup and old_lr_warmup_steps with default values self.old_lr_warmup = 0 self.old_lr_warmup_steps = 0 # Initialize the UI components self.initialize_ui_components()
Initializes the BasicTraining object with the given parameters. Args: sdxl_checkbox (gr.Checkbox): Checkbox to enable SDXL training. learning_rate_value (str): Initial learning rate value. lr_scheduler_value (str): Initial learning rate scheduler value. lr_warmup_value (str): Initial learning rate warmup value. finetuning (bool): If True, enables fine-tuning of the model. dreambooth (bool): If True, enables Dreambooth training.
__init__
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def initialize_ui_components(self) -> None: """ Initializes the UI components for the training settings. """ # Initialize the training controls self.init_training_controls() # Initialize the precision and resources controls self.init_precision_and_resources_controls() # Initialize the learning rate and optimizer controls self.init_lr_and_optimizer_controls() # Initialize the gradient and learning rate controls self.init_grad_and_lr_controls() # Initialize the learning rate controls self.init_learning_rate_controls() # Initialize the scheduler controls self.init_scheduler_controls() # Initialize the resolution and bucket controls self.init_resolution_and_bucket_controls() # Setup the behavior of the SDXL checkbox self.setup_sdxl_checkbox_behavior()
Initializes the UI components for the training settings.
initialize_ui_components
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def init_training_controls(self) -> None: """ Initializes the training controls for the model. """ # Create a row for the training controls with gr.Row(): # Initialize the train batch size slider self.train_batch_size = gr.Slider( minimum=1, maximum=64, label="Train batch size", value=1, step=self.config.get("basic.train_batch_size", 1), ) # Initialize the epoch number input self.epoch = gr.Number( label="Epoch", value=self.config.get("basic.epoch", 1), precision=0 ) # Initialize the maximum train epochs input self.max_train_epochs = gr.Number( label="Max train epoch", info="training epochs (overrides max_train_steps). 0 = no override", step=1, # precision=0, minimum=0, value=self.config.get("basic.max_train_epochs", 0), ) # Initialize the maximum train steps input self.max_train_steps = gr.Number( label="Max train steps", info="Overrides # training steps. 0 = no override", step=1, # precision=0, value=self.config.get("basic.max_train_steps", 1600), ) # Initialize the save every N epochs input self.save_every_n_epochs = gr.Number( label="Save every N epochs", value=self.config.get("basic.save_every_n_epochs", 1), precision=0, ) # Initialize the caption extension input self.caption_extension = gr.Dropdown( label="Caption file extension", choices=["", ".cap", ".caption", ".txt"], value=".txt", interactive=True, )
Initializes the training controls for the model.
init_training_controls
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def init_precision_and_resources_controls(self) -> None: """ Initializes the precision and resources controls for the model. """ with gr.Row(): # Initialize the seed textbox self.seed = gr.Number( label="Seed", # precision=0, step=1, minimum=0, value=self.config.get("basic.seed", 0), info="Set to 0 to make random", ) # Initialize the cache latents checkbox self.cache_latents = gr.Checkbox( label="Cache latents", value=self.config.get("basic.cache_latents", True), ) # Initialize the cache latents to disk checkbox self.cache_latents_to_disk = gr.Checkbox( label="Cache latents to disk", value=self.config.get("basic.cache_latents_to_disk", False), )
Initializes the precision and resources controls for the model.
init_precision_and_resources_controls
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def init_lr_and_optimizer_controls(self) -> None: """ Initializes the learning rate and optimizer controls for the model. """ with gr.Row(): # Initialize the learning rate scheduler dropdown self.lr_scheduler = gr.Dropdown( label="LR Scheduler", choices=[ "adafactor", "constant", "constant_with_warmup", "cosine", "cosine_with_restarts", "linear", "piecewise_constant", "polynomial", "cosine_with_min_lr", "inverse_sqrt", "warmup_stable_decay", ], value=self.config.get("basic.lr_scheduler", self.lr_scheduler_value), ) # Initialize the learning rate scheduler type dropdown self.lr_scheduler_type = gr.Dropdown( label="LR Scheduler type", info="(Optional) custom scheduler module name", choices=[ "", "CosineAnnealingLR", ], value=self.config.get("basic.lr_scheduler_type", ""), allow_custom_value=True, ) # Initialize the optimizer dropdown self.optimizer = gr.Dropdown( label="Optimizer", choices=[ "AdamW", "AdamWScheduleFree", "AdamW8bit", "Adafactor", "bitsandbytes.optim.AdEMAMix8bit", "bitsandbytes.optim.PagedAdEMAMix8bit", "DAdaptation", "DAdaptAdaGrad", "DAdaptAdam", "DAdaptAdan", "DAdaptAdanIP", "DAdaptAdamPreprint", "DAdaptLion", "DAdaptSGD", "Lion", "Lion8bit", "PagedAdamW8bit", "PagedAdamW32bit", "PagedLion8bit", "Prodigy", "prodigyplus.ProdigyPlusScheduleFree", "pytorch_optimizer.CAME", "RAdamScheduleFree", "SGDNesterov", "SGDNesterov8bit", "SGDScheduleFree", ], value=self.config.get("basic.optimizer", "AdamW8bit"), interactive=True, allow_custom_value=True, )
Initializes the learning rate and optimizer controls for the model.
init_lr_and_optimizer_controls
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def init_grad_and_lr_controls(self) -> None: """ Initializes the gradient and learning rate controls for the model. """ with gr.Row(): # Initialize the maximum gradient norm slider self.max_grad_norm = gr.Number(label='Max grad norm', value=1.0, interactive=True) # Initialize the learning rate scheduler extra arguments textbox self.lr_scheduler_args = gr.Textbox( label="LR scheduler extra arguments", lines=2, placeholder="(Optional) eg: milestones=[1,10,30,50] gamma=0.1", value=self.config.get("basic.lr_scheduler_args", ""), ) # Initialize the optimizer extra arguments textbox self.optimizer_args = gr.Textbox( label="Optimizer extra arguments", lines=2, placeholder="(Optional) eg: relative_step=True scale_parameter=True warmup_init=True", value=self.config.get("basic.optimizer_args", ""), )
Initializes the gradient and learning rate controls for the model.
init_grad_and_lr_controls
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def init_learning_rate_controls(self) -> None: """ Initializes the learning rate controls for the model. """ with gr.Row(): # Adjust visibility based on training modes lr_label = ( "Learning rate Unet" if self.finetuning or self.dreambooth else "Learning rate" ) # Initialize the learning rate number input self.learning_rate = gr.Number( label=lr_label, value=self.config.get("basic.learning_rate", self.learning_rate_value), minimum=-1, maximum=1, info="Set to 0 to not train the Unet", ) # Initialize the learning rate TE number input self.learning_rate_te = gr.Number( label="Learning rate TE", value=self.config.get( "basic.learning_rate_te", self.learning_rate_value ), visible=self.finetuning or self.dreambooth, minimum=-1, maximum=1, info="Set to 0 to not train the Text Encoder", ) # Initialize the learning rate TE1 number input self.learning_rate_te1 = gr.Number( label="Learning rate TE1", value=self.config.get( "basic.learning_rate_te1", self.learning_rate_value ), visible=False, minimum=-1, maximum=1, info="Set to 0 to not train the Text Encoder 1", ) # Initialize the learning rate TE2 number input self.learning_rate_te2 = gr.Number( label="Learning rate TE2", value=self.config.get( "basic.learning_rate_te2", self.learning_rate_value ), visible=False, minimum=-1, maximum=1, info="Set to 0 to not train the Text Encoder 2", ) # Initialize the learning rate warmup slider self.lr_warmup = gr.Slider( label="LR warmup (% of total steps)", value=self.config.get("basic.lr_warmup", self.lr_warmup_value), minimum=0, maximum=100, step=1, ) # Initialize the learning rate warmup steps override self.lr_warmup_steps = gr.Number( label="LR warmup steps (override)", value=self.config.get("basic.lr_warmup_steps", self.lr_warmup_steps_value), minimum=0, step=1, ) def lr_scheduler_changed(scheduler, value, value_lr_warmup_steps): if scheduler == "constant": self.old_lr_warmup = value self.old_lr_warmup_steps = value_lr_warmup_steps value = 0 value_lr_warmup_steps = 0 interactive=False info="Can't use LR warmup with LR Scheduler constant... setting to 0 and disabling field..." else: if self.old_lr_warmup != 0: value = self.old_lr_warmup self.old_lr_warmup = 0 if self.old_lr_warmup_steps != 0: value_lr_warmup_steps = self.old_lr_warmup_steps self.old_lr_warmup_steps = 0 interactive=True info="" return gr.Slider(value=value, interactive=interactive, info=info), gr.Number(value=value_lr_warmup_steps, interactive=interactive, info=info) self.lr_scheduler.change( lr_scheduler_changed, inputs=[self.lr_scheduler, self.lr_warmup, self.lr_warmup_steps], outputs=[self.lr_warmup, self.lr_warmup_steps], )
Initializes the learning rate controls for the model.
init_learning_rate_controls
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def init_scheduler_controls(self) -> None: """ Initializes the scheduler controls for the model. """ with gr.Row(visible=not self.finetuning): # Initialize the learning rate scheduler number of cycles textbox self.lr_scheduler_num_cycles = gr.Number( label="LR # cycles", minimum=1, # precision=0, # round to nearest integer step=1, # Increment value by 1 info="Number of restarts for cosine scheduler with restarts", value=self.config.get("basic.lr_scheduler_num_cycles", 1), ) # Initialize the learning rate scheduler power textbox self.lr_scheduler_power = gr.Number( label="LR power", minimum=0.0, step=0.01, info="Polynomial power for polynomial scheduler", value=self.config.get("basic.lr_scheduler_power", 1.0), )
Initializes the scheduler controls for the model.
init_scheduler_controls
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def init_resolution_and_bucket_controls(self) -> None: """ Initializes the resolution and bucket controls for the model. """ with gr.Row(visible=not self.finetuning): # Initialize the maximum resolution textbox self.max_resolution = gr.Textbox( label="Max resolution", value=self.config.get("basic.max_resolution", "512,512"), placeholder="512,512", ) # Initialize the stop text encoder training slider self.stop_text_encoder_training = gr.Slider( minimum=-1, maximum=100, value=self.config.get("basic.stop_text_encoder_training", 0), step=1, label="Stop TE (% of total steps)", ) # Initialize the enable buckets checkbox self.enable_bucket = gr.Checkbox( label="Enable buckets", value=self.config.get("basic.enable_bucket", True), ) # Initialize the minimum bucket resolution slider self.min_bucket_reso = gr.Slider( label="Minimum bucket resolution", value=self.config.get("basic.min_bucket_reso", 256), minimum=64, maximum=4096, step=64, info="Minimum size in pixel a bucket can be (>= 64)", ) # Initialize the maximum bucket resolution slider self.max_bucket_reso = gr.Slider( label="Maximum bucket resolution", value=self.config.get("basic.max_bucket_reso", 2048), minimum=64, maximum=4096, step=64, info="Maximum size in pixel a bucket can be (>= 64)", )
Initializes the resolution and bucket controls for the model.
init_resolution_and_bucket_controls
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def setup_sdxl_checkbox_behavior(self) -> None: """ Sets up the behavior of the SDXL checkbox based on the finetuning and dreambooth flags. """ self.sdxl_checkbox.change( self.update_learning_rate_te, inputs=[ self.sdxl_checkbox, gr.Checkbox(value=self.finetuning, visible=False), gr.Checkbox(value=self.dreambooth, visible=False), ], outputs=[ self.learning_rate_te, self.learning_rate_te1, self.learning_rate_te2, ], )
Sets up the behavior of the SDXL checkbox based on the finetuning and dreambooth flags.
setup_sdxl_checkbox_behavior
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def update_learning_rate_te( self, sdxl_checkbox: gr.Checkbox, finetuning: bool, dreambooth: bool, ) -> Tuple[gr.Number, gr.Number, gr.Number]: """ Updates the visibility of the learning rate TE, TE1, and TE2 based on the SDXL checkbox and finetuning/dreambooth flags. Args: sdxl_checkbox (gr.Checkbox): The SDXL checkbox. finetuning (bool): Whether finetuning is enabled. dreambooth (bool): Whether dreambooth is enabled. Returns: Tuple[gr.Number, gr.Number, gr.Number]: A tuple containing the updated visibility for learning rate TE, TE1, and TE2. """ # Determine the visibility condition based on finetuning and dreambooth flags visibility_condition = finetuning or dreambooth # Return a tuple of gr.Number instances with updated visibility return ( gr.Number(visible=(not sdxl_checkbox and visibility_condition)), gr.Number(visible=(sdxl_checkbox and visibility_condition)), gr.Number(visible=(sdxl_checkbox and visibility_condition)), )
Updates the visibility of the learning rate TE, TE1, and TE2 based on the SDXL checkbox and finetuning/dreambooth flags. Args: sdxl_checkbox (gr.Checkbox): The SDXL checkbox. finetuning (bool): Whether finetuning is enabled. dreambooth (bool): Whether dreambooth is enabled. Returns: Tuple[gr.Number, gr.Number, gr.Number]: A tuple containing the updated visibility for learning rate TE, TE1, and TE2.
update_learning_rate_te
python
bmaltais/kohya_ss
kohya_gui/class_basic_training.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_basic_training.py
Apache-2.0
def execute_command(self, run_cmd: str, **kwargs): """ Execute a command if no other command is currently running. Parameters: - run_cmd (str): The command to execute. - **kwargs: Additional keyword arguments to pass to subprocess.Popen. """ if self.process and self.process.poll() is None: log.info("The command is already running. Please wait for it to finish.") else: # for i, item in enumerate(run_cmd): # log.info(f"{i}: {item}") # Reconstruct the safe command string for display command_to_run = " ".join(run_cmd) log.info(f"Executing command: {command_to_run}") # Execute the command securely self.process = subprocess.Popen(run_cmd, **kwargs) log.debug("Command executed.")
Execute a command if no other command is currently running. Parameters: - run_cmd (str): The command to execute. - **kwargs: Additional keyword arguments to pass to subprocess.Popen.
execute_command
python
bmaltais/kohya_ss
kohya_gui/class_command_executor.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_command_executor.py
Apache-2.0
def kill_command(self): """ Kill the currently running command and its child processes. """ if self.is_running(): try: # Get the parent process and kill all its children parent = psutil.Process(self.process.pid) for child in parent.children(recursive=True): child.kill() parent.kill() log.info("The running process has been terminated.") except psutil.NoSuchProcess: # Explicitly handle the case where the process does not exist log.info( "The process does not exist. It might have terminated before the kill command was issued." ) except Exception as e: # General exception handling for any other errors log.info(f"Error when terminating process: {e}") else: self.process = None log.info("There is no running process to kill.") return gr.Button(visible=True), gr.Button(visible=False or self.headless)
Kill the currently running command and its child processes.
kill_command
python
bmaltais/kohya_ss
kohya_gui/class_command_executor.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_command_executor.py
Apache-2.0
def __init__( self, headless: bool = False, config_dir: str = None, config: dict = {} ): """ Initialize the ConfigurationFile class. Parameters: - headless (bool): Whether to run in headless mode. - config_dir (str): The directory for configuration files. """ self.headless = headless self.config = config # Sets the directory for storing configuration files, defaults to a 'presets' folder within the script directory. self.current_config_dir = self.config.get( "config_dir", os.path.join(scriptdir, "presets") ) # Initialize the GUI components for configuration. self.create_config_gui()
Initialize the ConfigurationFile class. Parameters: - headless (bool): Whether to run in headless mode. - config_dir (str): The directory for configuration files.
__init__
python
bmaltais/kohya_ss
kohya_gui/class_configuration_file.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_configuration_file.py
Apache-2.0
def list_config_dir(self, path: str) -> list: """ List directories in the data directory. Parameters: - path (str): The path to list directories from. Returns: - list: A list of directories. """ self.current_config_dir = path if not path == "" else "." # Lists all .json files in the current configuration directory, used for populating dropdown choices. return list(list_files(self.current_config_dir, exts=[".json"], all=True))
List directories in the data directory. Parameters: - path (str): The path to list directories from. Returns: - list: A list of directories.
list_config_dir
python
bmaltais/kohya_ss
kohya_gui/class_configuration_file.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_configuration_file.py
Apache-2.0
def __init__( self, finetune: bool = False, headless: bool = False, config: dict = {} ): """ Initialize the Folders class. Parameters: - finetune (bool): Whether to finetune the model. - headless (bool): Whether to run in headless mode. """ self.headless = headless self.finetune = finetune # Load kohya_ss GUI configs from config.toml if it exist self.config = config # Set default directories if not provided self.current_output_dir = self.config.get( "output_dir", os.path.join(scriptdir, "outputs") ) self.current_logging_dir = self.config.get( "logging_dir", os.path.join(scriptdir, "logs") ) self.current_reg_data_dir = self.config.get( "reg_data_dir", os.path.join(scriptdir, "reg") ) # Create directories if they don't exist self.create_directory_if_not_exists(self.current_output_dir) self.create_directory_if_not_exists(self.current_logging_dir) # Create the GUI for folder selection self.create_folders_gui()
Initialize the Folders class. Parameters: - finetune (bool): Whether to finetune the model. - headless (bool): Whether to run in headless mode.
__init__
python
bmaltais/kohya_ss
kohya_gui/class_folders.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_folders.py
Apache-2.0
def create_directory_if_not_exists(self, directory: str) -> None: """ Create a directory if it does not exist. Parameters: - directory (str): The directory to create. """ if ( directory is not None and directory.strip() != "" and not os.path.exists(directory) ): os.makedirs(directory, exist_ok=True)
Create a directory if it does not exist. Parameters: - directory (str): The directory to create.
create_directory_if_not_exists
python
bmaltais/kohya_ss
kohya_gui/class_folders.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_folders.py
Apache-2.0
def load_config(self, config_file_path: str = "./config.toml") -> dict: """ Loads the Kohya SS GUI configuration from a TOML file. Returns: dict: The configuration data loaded from the TOML file. """ try: # Attempt to load the TOML configuration file from the specified directory. config = toml.load(f"{config_file_path}") log.debug(f"Loaded configuration from {config_file_path}") except FileNotFoundError: # If the config file is not found, initialize `config` as an empty dictionary to handle missing configurations gracefully. config = {} log.debug( f"No configuration file found at {config_file_path}. Initializing empty configuration." ) return config
Loads the Kohya SS GUI configuration from a TOML file. Returns: dict: The configuration data loaded from the TOML file.
load_config
python
bmaltais/kohya_ss
kohya_gui/class_gui_config.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_gui_config.py
Apache-2.0
def save_config(self, config: dict, config_file_path: str = "./config.toml"): """ Saves the Kohya SS GUI configuration to a TOML file. Parameters: - config (dict): The configuration data to save. """ # Write the configuration data to the TOML file with open(f"{config_file_path}", "w", encoding="utf-8") as f: toml.dump(config, f)
Saves the Kohya SS GUI configuration to a TOML file. Parameters: - config (dict): The configuration data to save.
save_config
python
bmaltais/kohya_ss
kohya_gui/class_gui_config.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_gui_config.py
Apache-2.0
def get(self, key: str, default=None): """ Retrieves the value of a specified key from the configuration data. Parameters: - key (str): The key to retrieve the value for. - default: The default value to return if the key is not found. Returns: The value associated with the key, or the default value if the key is not found. """ # Split the key into a list of keys if it contains a dot (.) keys = key.split(".") # Initialize `data` with the entire configuration data data = self.config # Iterate over the keys to access nested values for k in keys: log.debug(k) # If the key is not found in the current data, return the default value if k not in data: log.debug( f"Key '{key}' not found in configuration. Returning default value." ) return default # Update `data` to the value associated with the current key data = data.get(k) # Return the final value log.debug(f"Returned {data}") return data
Retrieves the value of a specified key from the configuration data. Parameters: - key (str): The key to retrieve the value for. - default: The default value to return if the key is not found. Returns: The value associated with the key, or the default value if the key is not found.
get
python
bmaltais/kohya_ss
kohya_gui/class_gui_config.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_gui_config.py
Apache-2.0
def is_config_loaded(self) -> bool: """ Checks if the configuration was loaded from a file. Returns: bool: True if the configuration was loaded from a file, False otherwise. """ is_loaded = self.config != {} log.debug(f"Configuration was loaded from file: {is_loaded}") return is_loaded
Checks if the configuration was loaded from a file. Returns: bool: True if the configuration was loaded from a file, False otherwise.
is_config_loaded
python
bmaltais/kohya_ss
kohya_gui/class_gui_config.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_gui_config.py
Apache-2.0
def create_prompt_file(sample_prompts, output_dir): """ Creates a prompt file for image sampling. Args: sample_prompts (str): The prompts to use for image sampling. output_dir (str): The directory where the output images will be saved. Returns: str: The path to the prompt file. """ sample_prompts_path = os.path.join(output_dir, "sample/prompt.txt") if not os.path.exists(os.path.dirname(sample_prompts_path)): os.makedirs(os.path.dirname(sample_prompts_path)) with open(sample_prompts_path, "w", encoding="utf-8") as f: f.write(sample_prompts) return sample_prompts_path
Creates a prompt file for image sampling. Args: sample_prompts (str): The prompts to use for image sampling. output_dir (str): The directory where the output images will be saved. Returns: str: The path to the prompt file.
create_prompt_file
python
bmaltais/kohya_ss
kohya_gui/class_sample_images.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_sample_images.py
Apache-2.0
def initialize_accordion(self): """ Initializes the accordion for the Gradio interface. """ with gr.Row(): self.sample_every_n_steps = gr.Number( label="Sample every n steps", value=self.config.get("samples.sample_every_n_steps", 0), precision=0, interactive=True, ) self.sample_every_n_epochs = gr.Number( label="Sample every n epochs", value=self.config.get("samples.sample_every_n_epochs", 0), precision=0, interactive=True, ) self.sample_sampler = gr.Dropdown( label="Sample sampler", choices=[ "ddim", "pndm", "lms", "euler", "euler_a", "heun", "dpm_2", "dpm_2_a", "dpmsolver", "dpmsolver++", "dpmsingle", "k_lms", "k_euler", "k_euler_a", "k_dpm_2", "k_dpm_2_a", ], value=self.config.get("samples.sample_sampler", "euler_a"), interactive=True, ) with gr.Row(): self.sample_prompts = gr.Textbox( lines=5, label="Sample prompts", interactive=True, placeholder="masterpiece, best quality, 1girl, in white shirts, upper body, looking at viewer, simple background --n low quality, worst quality, bad anatomy,bad composition, poor, low effort --w 768 --h 768 --d 1 --l 7.5 --s 28", info="Enter one sample prompt per line to generate multiple samples per cycle. Optional specifiers include: --w (width), --h (height), --d (seed), --l (cfg scale), --s (sampler steps) and --n (negative prompt). To modify sample prompts during training, edit the prompt.txt file in the samples directory.", value=self.config.get("samples.sample_prompts", ""), )
Initializes the accordion for the Gradio interface.
initialize_accordion
python
bmaltais/kohya_ss
kohya_gui/class_sample_images.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_sample_images.py
Apache-2.0
def __init__( self, headless: bool = False, finetuning: bool = False, training_type: str = "", config: dict = {}, sd3_checkbox: gr.Checkbox = False, ) -> None: """ Initializes the AdvancedTraining class with given settings. Parameters: headless (bool): Run in headless mode without GUI. finetuning (bool): Enable model fine-tuning. training_type (str): The type of training to be performed. config (dict): Configuration options for the training process. """ self.headless = headless self.finetuning = finetuning self.training_type = training_type self.config = config self.sd3_checkbox = sd3_checkbox # Define the behavior for changing noise offset type. def noise_offset_type_change( noise_offset_type: str, ) -> Tuple[gr.Group, gr.Group]: """ Returns a tuple of Gradio Groups with visibility set based on the noise offset type. Parameters: noise_offset_type (str): The selected noise offset type. Returns: Tuple[gr.Group, gr.Group]: A tuple containing two Gradio Group elements with their visibility set. """ if noise_offset_type == "Original": return (gr.Group(visible=True), gr.Group(visible=False)) else: return (gr.Group(visible=False), gr.Group(visible=True)) with gr.Accordion( "SD3", open=False, elem_id="sd3_tab", visible=False ) as sd3_accordion: with gr.Group(): gr.Markdown("### SD3 Specific Parameters") with gr.Row(): self.weighting_scheme = gr.Dropdown( label="Weighting Scheme", choices=["logit_normal", "sigma_sqrt", "mode", "cosmap", "uniform"], value=self.config.get("sd3.weighting_scheme", "logit_normal"), interactive=True, ) self.logit_mean = gr.Number( label="Logit Mean", value=self.config.get("sd3.logit_mean", 0.0), interactive=True, ) self.logit_std = gr.Number( label="Logit Std", value=self.config.get("sd3.logit_std", 1.0), interactive=True, ) self.mode_scale = gr.Number( label="Mode Scale", value=self.config.get("sd3.mode_scale", 1.29), interactive=True, ) with gr.Row(): self.clip_l = gr.Textbox( label="CLIP-L Path", placeholder="Path to CLIP-L model", value=self.config.get("sd3.clip_l", ""), interactive=True, ) self.clip_l_button = gr.Button( document_symbol, elem_id="open_folder_small", visible=(not headless), interactive=True, ) self.clip_l_button.click( get_any_file_path, outputs=self.clip_l, show_progress=False, ) self.clip_g = gr.Textbox( label="CLIP-G Path", placeholder="Path to CLIP-G model", value=self.config.get("sd3.clip_g", ""), interactive=True, ) self.clip_g_button = gr.Button( document_symbol, elem_id="open_folder_small", visible=(not headless), interactive=True, ) self.clip_g_button.click( get_any_file_path, outputs=self.clip_g, show_progress=False, ) self.t5xxl = gr.Textbox( label="T5-XXL Path", placeholder="Path to T5-XXL model", value=self.config.get("sd3.t5xxl", ""), interactive=True, ) self.t5xxl_button = gr.Button( document_symbol, elem_id="open_folder_small", visible=(not headless), interactive=True, ) self.t5xxl_button.click( get_any_file_path, outputs=self.t5xxl, show_progress=False, ) with gr.Row(): self.save_clip = gr.Checkbox( label="Save CLIP models", value=self.config.get("sd3.save_clip", False), interactive=True, ) self.save_t5xxl = gr.Checkbox( label="Save T5-XXL model", value=self.config.get("sd3.save_t5xxl", False), interactive=True, ) with gr.Row(): self.t5xxl_device = gr.Textbox( label="T5-XXL Device", placeholder="Device for T5-XXL (e.g., cuda:0)", value=self.config.get("sd3.t5xxl_device", ""), interactive=True, ) self.t5xxl_dtype = gr.Dropdown( label="T5-XXL Dtype", choices=["float32", "fp16", "bf16"], value=self.config.get("sd3.t5xxl_dtype", "bf16"), interactive=True, ) self.sd3_text_encoder_batch_size = gr.Number( label="Text Encoder Batch Size", value=self.config.get("sd3.text_encoder_batch_size", 1), minimum=1, maximum=1024, step=1, interactive=True, ) self.sd3_cache_text_encoder_outputs = gr.Checkbox( label="Cache Text Encoder Outputs", value=self.config.get("sd3.cache_text_encoder_outputs", False), info="Cache text encoder outputs to speed up inference", interactive=True, ) self.sd3_cache_text_encoder_outputs_to_disk = gr.Checkbox( label="Cache Text Encoder Outputs to Disk", value=self.config.get( "sd3.cache_text_encoder_outputs_to_disk", False ), info="Cache text encoder outputs to disk to speed up inference", interactive=True, ) with gr.Row(): self.clip_l_dropout_rate = gr.Number( label="CLIP-L Dropout Rate", value=self.config.get("sd3.clip_l_dropout_rate", 0.0), interactive=True, minimum=0.0, info="Dropout rate for CLIP-L encoder" ) self.clip_g_dropout_rate = gr.Number( label="CLIP-G Dropout Rate", value=self.config.get("sd3.clip_g_dropout_rate", 0.0), interactive=True, minimum=0.0, info="Dropout rate for CLIP-G encoder" ) self.t5_dropout_rate = gr.Number( label="T5 Dropout Rate", value=self.config.get("sd3.t5_dropout_rate", 0.0), interactive=True, minimum=0.0, info="Dropout rate for T5-XXL encoder" ) with gr.Row(): self.sd3_fused_backward_pass = gr.Checkbox( label="Fused Backward Pass", value=self.config.get("sd3.fused_backward_pass", False), info="Enables the fusing of the optimizer step into the backward pass for each parameter. Only Adafactor optimizer is supported.", interactive=True, ) self.disable_mmap_load_safetensors = gr.Checkbox( label="Disable mmap load safe tensors", info="Disable memory mapping when loading the model's .safetensors in SDXL.", value=self.config.get("sd3.disable_mmap_load_safetensors", False), ) self.enable_scaled_pos_embed = gr.Checkbox( label="Enable Scaled Positional Embeddings", info="Enable scaled positional embeddings in the model.", value=self.config.get("sd3.enable_scaled_pos_embed", False), ) self.pos_emb_random_crop_rate = gr.Number( label="Positional Embedding Random Crop Rate", value=self.config.get("sd3.pos_emb_random_crop_rate", 0.0), interactive=True, minimum=0.0, info="Random crop rate for positional embeddings" ) self.sd3_checkbox.change( lambda sd3_checkbox: gr.Accordion(visible=sd3_checkbox), inputs=[self.sd3_checkbox], outputs=[sd3_accordion], )
Initializes the AdvancedTraining class with given settings. Parameters: headless (bool): Run in headless mode without GUI. finetuning (bool): Enable model fine-tuning. training_type (str): The type of training to be performed. config (dict): Configuration options for the training process.
__init__
python
bmaltais/kohya_ss
kohya_gui/class_sd3.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_sd3.py
Apache-2.0
def noise_offset_type_change( noise_offset_type: str, ) -> Tuple[gr.Group, gr.Group]: """ Returns a tuple of Gradio Groups with visibility set based on the noise offset type. Parameters: noise_offset_type (str): The selected noise offset type. Returns: Tuple[gr.Group, gr.Group]: A tuple containing two Gradio Group elements with their visibility set. """ if noise_offset_type == "Original": return (gr.Group(visible=True), gr.Group(visible=False)) else: return (gr.Group(visible=False), gr.Group(visible=True))
Returns a tuple of Gradio Groups with visibility set based on the noise offset type. Parameters: noise_offset_type (str): The selected noise offset type. Returns: Tuple[gr.Group, gr.Group]: A tuple containing two Gradio Group elements with their visibility set.
noise_offset_type_change
python
bmaltais/kohya_ss
kohya_gui/class_sd3.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_sd3.py
Apache-2.0
def list_dataset_config_dirs(path: str) -> list: """ List directories and toml files in the dataset_config directory. Parameters: - path (str): The path to list directories and files from. Returns: - list: A list of directories and files. """ current_dataset_config_dir = path if not path == "" else "." # Lists all .json files in the current configuration directory, used for populating dropdown choices. return list( list_files(current_dataset_config_dir, exts=[".toml"], all=True) )
List directories and toml files in the dataset_config directory. Parameters: - path (str): The path to list directories and files from. Returns: - list: A list of directories and files.
list_dataset_config_dirs
python
bmaltais/kohya_ss
kohya_gui/class_source_model.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/class_source_model.py
Apache-2.0
def get_executable_path(executable_name: str = None) -> str: """ Retrieve and sanitize the path to an executable in the system's PATH. Args: executable_name (str): The name of the executable to find. Returns: str: The full, sanitized path to the executable if found, otherwise an empty string. """ if executable_name: executable_path = shutil.which(executable_name) if executable_path: # Replace backslashes with forward slashes on Windows # if os.name == "nt": # executable_path = executable_path.replace("\\", "/") return executable_path else: return "" # Return empty string if the executable is not found else: return "" # Return empty string if no executable name is provided
Retrieve and sanitize the path to an executable in the system's PATH. Args: executable_name (str): The name of the executable to find. Returns: str: The full, sanitized path to the executable if found, otherwise an empty string.
get_executable_path
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def check_if_model_exist( output_name: str, output_dir: str, save_model_as: str, headless: bool = False ) -> bool: """ Checks if a model with the same name already exists and prompts the user to overwrite it if it does. Parameters: output_name (str): The name of the output model. output_dir (str): The directory where the model is saved. save_model_as (str): The format to save the model as. headless (bool, optional): If True, skips the verification and returns False. Defaults to False. Returns: bool: True if the model already exists and the user chooses not to overwrite it, otherwise False. """ if headless: log.info( "Headless mode, skipping verification if model already exist... if model already exist it will be overwritten..." ) return False if save_model_as in ["diffusers", "diffusers_safetendors"]: ckpt_folder = os.path.join(output_dir, output_name) if os.path.isdir(ckpt_folder): msg = f"A diffuser model with the same name {ckpt_folder} already exists. Do you want to overwrite it?" if not ynbox(msg, "Overwrite Existing Model?"): log.info("Aborting training due to existing model with same name...") return True elif save_model_as in ["ckpt", "safetensors"]: ckpt_file = os.path.join(output_dir, output_name + "." + save_model_as) if os.path.isfile(ckpt_file): msg = f"A model with the same file name {ckpt_file} already exists. Do you want to overwrite it?" if not ynbox(msg, "Overwrite Existing Model?"): log.info("Aborting training due to existing model with same name...") return True else: log.info( 'Can\'t verify if existing model exist when save model is set as "same as source model", continuing to train model...' ) return False return False
Checks if a model with the same name already exists and prompts the user to overwrite it if it does. Parameters: output_name (str): The name of the output model. output_dir (str): The directory where the model is saved. save_model_as (str): The format to save the model as. headless (bool, optional): If True, skips the verification and returns False. Defaults to False. Returns: bool: True if the model already exists and the user chooses not to overwrite it, otherwise False.
check_if_model_exist
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def output_message(msg: str = "", title: str = "", headless: bool = False) -> None: """ Outputs a message to the user, either in a message box or in the log. Parameters: msg (str, optional): The message to be displayed. Defaults to an empty string. title (str, optional): The title of the message box. Defaults to an empty string. headless (bool, optional): If True, the message is logged instead of displayed in a message box. Defaults to False. Returns: None """ if headless: log.info(msg) else: msgbox(msg=msg, title=title)
Outputs a message to the user, either in a message box or in the log. Parameters: msg (str, optional): The message to be displayed. Defaults to an empty string. title (str, optional): The title of the message box. Defaults to an empty string. headless (bool, optional): If True, the message is logged instead of displayed in a message box. Defaults to False. Returns: None
output_message
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_id): """ Creates a refresh button that can be used to update UI components. Parameters: refresh_component (list or object): The UI component(s) to be refreshed. refresh_method (callable): The method to be called when the button is clicked. refreshed_args (dict or callable): The arguments to be passed to the refresh method. elem_id (str): The ID of the button element. Returns: gr.Button: The configured refresh button. """ # Converts refresh_component into a list for uniform processing. If it's already a list, keep it the same. refresh_components = ( refresh_component if isinstance(refresh_component, list) else [refresh_component] ) # Initialize label to None. This will store the label of the first component with a non-None label, if any. label = None # Iterate over each component to find the first non-None label and assign it to 'label'. for comp in refresh_components: label = getattr(comp, "label", None) if label is not None: break # Define the refresh function that will be triggered upon clicking the refresh button. def refresh(): # Invoke the refresh_method, which is intended to perform the refresh operation. refresh_method() # Determine the arguments for the refresh: call refreshed_args if it's callable, otherwise use it directly. args = refreshed_args() if callable(refreshed_args) else refreshed_args # For each key-value pair in args, update the corresponding properties of each component. for k, v in args.items(): for comp in refresh_components: setattr(comp, k, v) # Use gr.update to refresh the UI components. If multiple components are present, update each; else, update only the first. return ( [gr.Dropdown(**(args or {})) for _ in refresh_components] if len(refresh_components) > 1 else gr.Dropdown(**(args or {})) ) # Create a refresh button with the specified label (via refresh_symbol), ID, and classes. # 'refresh_symbol' should be defined outside this function or passed as an argument, representing the button's label or icon. refresh_button = gr.Button( value=refresh_symbol, elem_id=elem_id, elem_classes=["tool"] ) # Configure the button to invoke the refresh function. refresh_button.click(fn=refresh, inputs=[], outputs=refresh_components) # Return the configured refresh button to be used in the UI. return refresh_button
Creates a refresh button that can be used to update UI components. Parameters: refresh_component (list or object): The UI component(s) to be refreshed. refresh_method (callable): The method to be called when the button is clicked. refreshed_args (dict or callable): The arguments to be passed to the refresh method. elem_id (str): The ID of the button element. Returns: gr.Button: The configured refresh button.
create_refresh_button
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def get_file_path( file_path="", default_extension=".json", extension_name="Config files" ): """ Opens a file dialog to select a file, allowing the user to navigate and choose a file with a specific extension. If no file is selected, returns the initially provided file path or an empty string if not provided. This function is conditioned to skip the file dialog on macOS or if specific environment variables are present, indicating a possible automated environment where a dialog cannot be displayed. Parameters: - file_path (str): The initial file path or an empty string by default. Used as the fallback if no file is selected. - default_extension (str): The default file extension (e.g., ".json") for the file dialog. - extension_name (str): The display name for the type of files being selected (e.g., "Config files"). Returns: - str: The path of the file selected by the user, or the initial `file_path` if no selection is made. Raises: - TypeError: If `file_path`, `default_extension`, or `extension_name` are not strings. Note: - The function checks the `ENV_EXCLUSION` list against environment variables to determine if the file dialog should be skipped, aiming to prevent its appearance during automated operations. - The dialog will also be skipped on macOS (`sys.platform != "darwin"`) as a specific behavior adjustment. """ # Validate parameter types if not isinstance(file_path, str): raise TypeError("file_path must be a string") if not isinstance(default_extension, str): raise TypeError("default_extension must be a string") if not isinstance(extension_name, str): raise TypeError("extension_name must be a string") # Environment and platform check to decide on showing the file dialog if not any(var in os.environ for var in ENV_EXCLUSION) and sys.platform != "darwin": current_file_path = file_path # Backup in case no file is selected initial_dir, initial_file = get_dir_and_file( file_path ) # Decompose file path for dialog setup # Initialize a hidden Tkinter window for the file dialog root = Tk() root.wm_attributes("-topmost", 1) # Ensure the dialog is topmost root.withdraw() # Hide the root window to show only the dialog # Open the file dialog and capture the selected file path file_path = filedialog.askopenfilename( filetypes=((extension_name, f"*{default_extension}"), ("All files", "*.*")), defaultextension=default_extension, initialfile=initial_file, initialdir=initial_dir, ) root.destroy() # Cleanup by destroying the Tkinter root window # Fallback to the initial path if no selection is made if not file_path: file_path = current_file_path # Return the selected or fallback file path return file_path
Opens a file dialog to select a file, allowing the user to navigate and choose a file with a specific extension. If no file is selected, returns the initially provided file path or an empty string if not provided. This function is conditioned to skip the file dialog on macOS or if specific environment variables are present, indicating a possible automated environment where a dialog cannot be displayed. Parameters: - file_path (str): The initial file path or an empty string by default. Used as the fallback if no file is selected. - default_extension (str): The default file extension (e.g., ".json") for the file dialog. - extension_name (str): The display name for the type of files being selected (e.g., "Config files"). Returns: - str: The path of the file selected by the user, or the initial `file_path` if no selection is made. Raises: - TypeError: If `file_path`, `default_extension`, or `extension_name` are not strings. Note: - The function checks the `ENV_EXCLUSION` list against environment variables to determine if the file dialog should be skipped, aiming to prevent its appearance during automated operations. - The dialog will also be skipped on macOS (`sys.platform != "darwin"`) as a specific behavior adjustment.
get_file_path
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def get_any_file_path(file_path: str = "") -> str: """ Opens a file dialog to select any file, allowing the user to navigate and choose a file. If no file is selected, returns the initially provided file path or an empty string if not provided. This function is conditioned to skip the file dialog on macOS or if specific environment variables are present, indicating a possible automated environment where a dialog cannot be displayed. Parameters: - file_path (str): The initial file path or an empty string by default. Used as the fallback if no file is selected. Returns: - str: The path of the file selected by the user, or the initial `file_path` if no selection is made. Raises: - TypeError: If `file_path` is not a string. - EnvironmentError: If there's an issue accessing environment variables. - RuntimeError: If there's an issue initializing the file dialog. Note: - The function checks the `ENV_EXCLUSION` list against environment variables to determine if the file dialog should be skipped, aiming to prevent its appearance during automated operations. - The dialog will also be skipped on macOS (`sys.platform != "darwin"`) as a specific behavior adjustment. """ # Validate parameter type if not isinstance(file_path, str): raise TypeError("file_path must be a string") try: # Check for environment variable conditions if ( not any(var in os.environ for var in ENV_EXCLUSION) and sys.platform != "darwin" ): current_file_path: str = file_path initial_dir, initial_file = get_dir_and_file(file_path) # Initialize a hidden Tkinter window for the file dialog root = Tk() root.wm_attributes("-topmost", 1) root.withdraw() try: # Open the file dialog and capture the selected file path file_path = filedialog.askopenfilename( initialdir=initial_dir, initialfile=initial_file, ) except Exception as e: raise RuntimeError(f"Failed to open file dialog: {e}") finally: root.destroy() # Fallback to the initial path if no selection is made if not file_path: file_path = current_file_path except KeyError as e: raise EnvironmentError(f"Failed to access environment variables: {e}") # Return the selected or fallback file path return file_path
Opens a file dialog to select any file, allowing the user to navigate and choose a file. If no file is selected, returns the initially provided file path or an empty string if not provided. This function is conditioned to skip the file dialog on macOS or if specific environment variables are present, indicating a possible automated environment where a dialog cannot be displayed. Parameters: - file_path (str): The initial file path or an empty string by default. Used as the fallback if no file is selected. Returns: - str: The path of the file selected by the user, or the initial `file_path` if no selection is made. Raises: - TypeError: If `file_path` is not a string. - EnvironmentError: If there's an issue accessing environment variables. - RuntimeError: If there's an issue initializing the file dialog. Note: - The function checks the `ENV_EXCLUSION` list against environment variables to determine if the file dialog should be skipped, aiming to prevent its appearance during automated operations. - The dialog will also be skipped on macOS (`sys.platform != "darwin"`) as a specific behavior adjustment.
get_any_file_path
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def get_folder_path(folder_path: str = "") -> str: """ Opens a folder dialog to select a folder, allowing the user to navigate and choose a folder. If no folder is selected, returns the initially provided folder path or an empty string if not provided. This function is conditioned to skip the folder dialog on macOS or if specific environment variables are present, indicating a possible automated environment where a dialog cannot be displayed. Parameters: - folder_path (str): The initial folder path or an empty string by default. Used as the fallback if no folder is selected. Returns: - str: The path of the folder selected by the user, or the initial `folder_path` if no selection is made. Raises: - TypeError: If `folder_path` is not a string. - EnvironmentError: If there's an issue accessing environment variables. - RuntimeError: If there's an issue initializing the folder dialog. Note: - The function checks the `ENV_EXCLUSION` list against environment variables to determine if the folder dialog should be skipped, aiming to prevent its appearance during automated operations. - The dialog will also be skipped on macOS (`sys.platform != "darwin"`) as a specific behavior adjustment. """ # Validate parameter type if not isinstance(folder_path, str): raise TypeError("folder_path must be a string") try: # Check for environment variable conditions if any(var in os.environ for var in ENV_EXCLUSION) or sys.platform == "darwin": return folder_path or "" root = Tk() root.withdraw() root.wm_attributes("-topmost", 1) selected_folder = filedialog.askdirectory(initialdir=folder_path or ".") root.destroy() return selected_folder or folder_path except Exception as e: raise RuntimeError(f"Error initializing folder dialog: {e}") from e
Opens a folder dialog to select a folder, allowing the user to navigate and choose a folder. If no folder is selected, returns the initially provided folder path or an empty string if not provided. This function is conditioned to skip the folder dialog on macOS or if specific environment variables are present, indicating a possible automated environment where a dialog cannot be displayed. Parameters: - folder_path (str): The initial folder path or an empty string by default. Used as the fallback if no folder is selected. Returns: - str: The path of the folder selected by the user, or the initial `folder_path` if no selection is made. Raises: - TypeError: If `folder_path` is not a string. - EnvironmentError: If there's an issue accessing environment variables. - RuntimeError: If there's an issue initializing the folder dialog. Note: - The function checks the `ENV_EXCLUSION` list against environment variables to determine if the folder dialog should be skipped, aiming to prevent its appearance during automated operations. - The dialog will also be skipped on macOS (`sys.platform != "darwin"`) as a specific behavior adjustment.
get_folder_path
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def get_saveasfilename_path( file_path: str = "", extensions: str = "*", extension_name: str = "Config files", ) -> str: """ Opens a file dialog to select a file name for saving, allowing the user to specify a file name and location. If no file is selected, returns the initially provided file path or an empty string if not provided. This function is conditioned to skip the file dialog on macOS or if specific environment variables are present, indicating a possible automated environment where a dialog cannot be displayed. Parameters: - file_path (str): The initial file path or an empty string by default. Used as the fallback if no file is selected. - extensions (str): The file extensions to filter the file dialog by. Defaults to "*" for all files. - extension_name (str): The name to display for the file extensions in the file dialog. Defaults to "Config files". Returns: - str: The path of the file selected by the user, or the initial `file_path` if no selection is made. Raises: - TypeError: If `file_path` is not a string. - EnvironmentError: If there's an issue accessing environment variables. - RuntimeError: If there's an issue initializing the file dialog. Note: - The function checks the `ENV_EXCLUSION` list against environment variables to determine if the file dialog should be skipped, aiming to prevent its appearance during automated operations. - The dialog will also be skipped on macOS (`sys.platform == "darwin"`) as a specific behavior adjustment. """ # Check if the current environment is not macOS and if the environment variables do not match the exclusion list if not any(var in os.environ for var in ENV_EXCLUSION) and sys.platform != "darwin": # Store the initial file path to use as a fallback in case no file is selected current_file_path: str = file_path # log.info(f'current file path: {current_file_path}') # Split the file path into directory and file name for setting the file dialog start location and filename initial_dir, initial_file = get_dir_and_file(file_path) # Initialize a hidden Tkinter window to act as the parent for the file dialog, ensuring it appears on top root = Tk() root.wm_attributes("-topmost", 1) root.withdraw() # Open the file dialog and capture the selected file path save_file_path = filedialog.asksaveasfilename( filetypes=( (f"{extension_name}", f"{extensions}"), ("All files", "*"), ), defaultextension=extensions, initialdir=initial_dir, initialfile=initial_file, ) # Close the Tkinter root window to clean up the UI root.destroy() # Default to the current file path if no file is selected, ensuring there's always a valid file path if save_file_path == "": file_path = current_file_path else: # Logging the save file path for auditing purposes; useful in confirming the user's file choice # log.info(save_file_path) # Update the file path with the user-selected file name, facilitating the save operation file_path = save_file_path # Return the final file path, either the user-selected file or the fallback path return file_path
Opens a file dialog to select a file name for saving, allowing the user to specify a file name and location. If no file is selected, returns the initially provided file path or an empty string if not provided. This function is conditioned to skip the file dialog on macOS or if specific environment variables are present, indicating a possible automated environment where a dialog cannot be displayed. Parameters: - file_path (str): The initial file path or an empty string by default. Used as the fallback if no file is selected. - extensions (str): The file extensions to filter the file dialog by. Defaults to "*" for all files. - extension_name (str): The name to display for the file extensions in the file dialog. Defaults to "Config files". Returns: - str: The path of the file selected by the user, or the initial `file_path` if no selection is made. Raises: - TypeError: If `file_path` is not a string. - EnvironmentError: If there's an issue accessing environment variables. - RuntimeError: If there's an issue initializing the file dialog. Note: - The function checks the `ENV_EXCLUSION` list against environment variables to determine if the file dialog should be skipped, aiming to prevent its appearance during automated operations. - The dialog will also be skipped on macOS (`sys.platform == "darwin"`) as a specific behavior adjustment.
get_saveasfilename_path
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def add_pre_postfix( folder: str = "", prefix: str = "", postfix: str = "", caption_file_ext: str = ".caption", recursive: bool = False, ) -> None: """ Add prefix and/or postfix to the content of caption files within a folder. If no caption files are found, create one with the requested prefix and/or postfix. Args: folder (str): Path to the folder containing caption files. prefix (str, optional): Prefix to add to the content of the caption files. postfix (str, optional): Postfix to add to the content of the caption files. caption_file_ext (str, optional): Extension of the caption files. recursive (bool, optional): Whether to search for caption files recursively. """ # If neither prefix nor postfix is provided, return early if prefix == "" and postfix == "": return # Define the image file extensions to filter image_extensions = (".jpg", ".jpeg", ".png", ".webp") # If recursive is true, list all image files in the folder and its subfolders if recursive: image_files = [] for root, dirs, files in os.walk(folder): for file in files: if file.lower().endswith(image_extensions): image_files.append(os.path.join(root, file)) else: # List all image files in the folder image_files = [ f for f in os.listdir(folder) if f.lower().endswith(image_extensions) ] # Iterate over the list of image files for image_file in image_files: # Construct the caption file name by appending the caption file extension to the image file name caption_file_name = f"{os.path.splitext(image_file)[0]}{caption_file_ext}" # Construct the full path to the caption file caption_file_path = os.path.join(folder, caption_file_name) # Check if the caption file does not exist if not os.path.exists(caption_file_path): # Create a new caption file with the specified prefix and/or postfix try: with open(caption_file_path, "w", encoding="utf-8") as f: # Determine the separator based on whether both prefix and postfix are provided separator = " " if prefix and postfix else "" f.write(f"{prefix}{separator}{postfix}") except Exception as e: log.error(f"Error writing to file {caption_file_path}: {e}") else: # Open the existing caption file for reading and writing try: with open(caption_file_path, "r+", encoding="utf-8") as f: # Read the content of the caption file, stripping any trailing whitespace content = f.read().rstrip() # Move the file pointer to the beginning of the file f.seek(0, 0) # Determine the separator based on whether only prefix is provided prefix_separator = " " if prefix else "" # Determine the separator based on whether only postfix is provided postfix_separator = " " if postfix else "" # Write the updated content to the caption file, adding prefix and/or postfix f.write( f"{prefix}{prefix_separator}{content}{postfix_separator}{postfix}" ) except Exception as e: log.error(f"Error writing to file {caption_file_path}: {e}")
Add prefix and/or postfix to the content of caption files within a folder. If no caption files are found, create one with the requested prefix and/or postfix. Args: folder (str): Path to the folder containing caption files. prefix (str, optional): Prefix to add to the content of the caption files. postfix (str, optional): Postfix to add to the content of the caption files. caption_file_ext (str, optional): Extension of the caption files. recursive (bool, optional): Whether to search for caption files recursively.
add_pre_postfix
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def has_ext_files(folder_path: str, file_extension: str) -> bool: """ Determines whether any files within a specified folder have a given file extension. This function iterates through each file in the specified folder and checks if its extension matches the provided file_extension argument. The search is case-sensitive and expects file_extension to include the dot ('.') if applicable (e.g., '.txt'). Args: folder_path (str): The absolute or relative path to the folder to search within. file_extension (str): The file extension to search for, including the dot ('.') if applicable. Returns: bool: True if at least one file with the specified extension is found, False otherwise. """ # Iterate directly over files in the specified folder path for file in os.listdir(folder_path): # Return True at the first occurrence of a file with the specified extension if file.endswith(file_extension): return True # If no file with the specified extension is found, return False return False
Determines whether any files within a specified folder have a given file extension. This function iterates through each file in the specified folder and checks if its extension matches the provided file_extension argument. The search is case-sensitive and expects file_extension to include the dot ('.') if applicable (e.g., '.txt'). Args: folder_path (str): The absolute or relative path to the folder to search within. file_extension (str): The file extension to search for, including the dot ('.') if applicable. Returns: bool: True if at least one file with the specified extension is found, False otherwise.
has_ext_files
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def find_replace( folder_path: str = "", caption_file_ext: str = ".caption", search_text: str = "", replace_text: str = "", ) -> None: """ Efficiently finds and replaces specified text across all caption files in a given folder. This function iterates through each caption file matching the specified extension within the given folder path, replacing all occurrences of the search text with the replacement text. It ensures that the operation only proceeds if the search text is provided and there are caption files to process. Args: folder_path (str, optional): The directory path where caption files are located. Defaults to an empty string, which implies the current directory. caption_file_ext (str, optional): The file extension for caption files. Defaults to ".caption". search_text (str, optional): The text to search for within the caption files. Defaults to an empty string. replace_text (str, optional): The text to use as a replacement. Defaults to an empty string. """ # Log the start of the caption find/replace operation log.info("Running caption find/replace") # Validate the presence of caption files and the search text if not search_text or not has_ext_files(folder_path, caption_file_ext): # Display a message box indicating no files were found msgbox( f"No files with extension {caption_file_ext} were found in {folder_path}..." ) log.warning( "No files with extension {caption_file_ext} were found in {folder_path}..." ) # Exit the function early return # Check if the caption file extension is one of the supported extensions if caption_file_ext not in [".caption", ".txt", ".txt2", ".cap"]: log.error( f"Unsupported file extension {caption_file_ext} for caption files. Please use .caption, .txt, .txt2, or .cap." ) # Exit the function early return # Check if the folder path exists if not os.path.exists(folder_path): log.error(f"The provided path '{folder_path}' is not a valid folder.") return # List all caption files in the folder try: caption_files = [ f for f in os.listdir(folder_path) if f.endswith(caption_file_ext) ] except Exception as e: log.error(f"Error accessing folder {folder_path}: {e}") return # Iterate over the list of caption files for caption_file in caption_files: # Construct the full path for each caption file file_path = os.path.join(folder_path, caption_file) # Read and replace text try: with open(file_path, "r", errors="ignore", encoding="utf-8") as f: content = f.read().replace(search_text, replace_text) # Write the updated content back to the file with open(file_path, "w", encoding="utf-8") as f: f.write(content) except Exception as e: log.error(f"Error processing file {file_path}: {e}")
Efficiently finds and replaces specified text across all caption files in a given folder. This function iterates through each caption file matching the specified extension within the given folder path, replacing all occurrences of the search text with the replacement text. It ensures that the operation only proceeds if the search text is provided and there are caption files to process. Args: folder_path (str, optional): The directory path where caption files are located. Defaults to an empty string, which implies the current directory. caption_file_ext (str, optional): The file extension for caption files. Defaults to ".caption". search_text (str, optional): The text to search for within the caption files. Defaults to an empty string. replace_text (str, optional): The text to use as a replacement. Defaults to an empty string.
find_replace
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def color_aug_changed(color_aug): """ Handles the change in color augmentation checkbox. This function is called when the color augmentation checkbox is toggled. If color augmentation is enabled, it disables the cache latent checkbox and returns a new checkbox with the value set to False and interactive set to False. If color augmentation is disabled, it returns a new checkbox with interactive set to True. Args: color_aug (bool): The new state of the color augmentation checkbox. Returns: gr.Checkbox: A new checkbox with the appropriate settings based on the color augmentation state. """ # If color augmentation is enabled, disable cache latent and return a new checkbox if color_aug: msgbox( 'Disabling "Cache latent" because "Color augmentation" has been selected...' ) return gr.Checkbox(value=False, interactive=False) # If color augmentation is disabled, return a new checkbox with interactive set to True else: return gr.Checkbox(interactive=True)
Handles the change in color augmentation checkbox. This function is called when the color augmentation checkbox is toggled. If color augmentation is enabled, it disables the cache latent checkbox and returns a new checkbox with the value set to False and interactive set to False. If color augmentation is disabled, it returns a new checkbox with interactive set to True. Args: color_aug (bool): The new state of the color augmentation checkbox. Returns: gr.Checkbox: A new checkbox with the appropriate settings based on the color augmentation state.
color_aug_changed
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def set_pretrained_model_name_or_path_input( pretrained_model_name_or_path, refresh_method=None ): """ Sets the pretrained model name or path input based on the model type. This function checks the type of the pretrained model and sets the appropriate parameters for the model. It also handles the case where the model list is set to 'custom' and a refresh method is provided. Args: pretrained_model_name_or_path (str): The name or path of the pretrained model. refresh_method (callable, optional): A function to refresh the model list. Returns: tuple: A tuple containing the Dropdown widget, v2 checkbox, v_parameterization checkbox, and sdxl checkbox. """ # Check if the given pretrained_model_name_or_path is in the list of SDXL models if pretrained_model_name_or_path in SDXL_MODELS: log.info("SDXL model selected. Setting sdxl parameters") v2 = gr.Checkbox(value=False, visible=False) v_parameterization = gr.Checkbox(value=False, visible=False) sdxl = gr.Checkbox(value=True, visible=False) sd3 = gr.Checkbox(value=False, visible=False) flux1 = gr.Checkbox(value=False, visible=False) return ( gr.Dropdown(), v2, v_parameterization, sdxl, sd3, flux1, ) # Check if the given pretrained_model_name_or_path is in the list of V2 base models if pretrained_model_name_or_path in V2_BASE_MODELS: log.info("SD v2 base model selected. Setting --v2 parameter") v2 = gr.Checkbox(value=True, visible=False) v_parameterization = gr.Checkbox(value=False, visible=False) sdxl = gr.Checkbox(value=False, visible=False) sd3 = gr.Checkbox(value=False, visible=False) flux1 = gr.Checkbox(value=False, visible=False) return ( gr.Dropdown(), v2, v_parameterization, sdxl, sd3, flux1, ) # Check if the given pretrained_model_name_or_path is in the list of V parameterization models if pretrained_model_name_or_path in V_PARAMETERIZATION_MODELS: log.info( "SD v2 model selected. Setting --v2 and --v_parameterization parameters" ) v2 = gr.Checkbox(value=True, visible=False) v_parameterization = gr.Checkbox(value=True, visible=False) sdxl = gr.Checkbox(value=False, visible=False) sd3 = gr.Checkbox(value=False, visible=False) flux1 = gr.Checkbox(value=False, visible=False) return ( gr.Dropdown(), v2, v_parameterization, sdxl, sd3, flux1, ) # Check if the given pretrained_model_name_or_path is in the list of V1 models if pretrained_model_name_or_path in V1_MODELS: log.info(f"{pretrained_model_name_or_path} model selected.") v2 = gr.Checkbox(value=False, visible=False) v_parameterization = gr.Checkbox(value=False, visible=False) sdxl = gr.Checkbox(value=False, visible=False) sd3 = gr.Checkbox(value=False, visible=False) flux1 = gr.Checkbox(value=False, visible=False) return ( gr.Dropdown(), v2, v_parameterization, sdxl, sd3, flux1, ) # Check if the model_list is set to 'custom' v2 = gr.Checkbox(visible=True) v_parameterization = gr.Checkbox(visible=True) sdxl = gr.Checkbox(visible=True) sd3 = gr.Checkbox(visible=True) flux1 = gr.Checkbox(visible=True) # Auto-detect model type if safetensors file path is given if pretrained_model_name_or_path.lower().endswith(".safetensors"): detect = SDModelType(pretrained_model_name_or_path) v2 = gr.Checkbox(value=detect.Is_SD2(), visible=True) sdxl = gr.Checkbox(value=detect.Is_SDXL(), visible=True) sd3 = gr.Checkbox(value=detect.Is_SD3(), visible=True) flux1 = gr.Checkbox(value=detect.Is_FLUX1(), visible=True) #TODO: v_parameterization # If a refresh method is provided, use it to update the choices for the Dropdown widget if refresh_method is not None: args = dict( choices=refresh_method(pretrained_model_name_or_path), ) else: args = {} return ( gr.Dropdown(**args), v2, v_parameterization, sdxl, sd3, flux1, )
Sets the pretrained model name or path input based on the model type. This function checks the type of the pretrained model and sets the appropriate parameters for the model. It also handles the case where the model list is set to 'custom' and a refresh method is provided. Args: pretrained_model_name_or_path (str): The name or path of the pretrained model. refresh_method (callable, optional): A function to refresh the model list. Returns: tuple: A tuple containing the Dropdown widget, v2 checkbox, v_parameterization checkbox, and sdxl checkbox.
set_pretrained_model_name_or_path_input
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def get_int_or_default(kwargs, key, default_value=0): """ Retrieves an integer value from the provided kwargs dictionary based on the given key. If the key is not found, or the value cannot be converted to an integer, a default value is returned. Args: kwargs (dict): A dictionary of keyword arguments. key (str): The key to retrieve from the kwargs dictionary. default_value (int, optional): The default value to return if the key is not found or the value is not an integer. Returns: int: The integer value if found and valid, otherwise the default value. """ # Try to retrieve the value for the specified key from the kwargs. # Use the provided default_value if the key does not exist. value = kwargs.get(key, default_value) try: # Try to convert the value to a integer. This should works for int, # and strings that represent a valid floating-point number. return int(value) except (ValueError, TypeError): # If the conversion fails (for example, the value is a string that cannot # be converted to an integer), log the issue and return the provided default_value. log.info( f"{key} is not an int or cannot be converted to int, setting value to {default_value}" ) return default_value
Retrieves an integer value from the provided kwargs dictionary based on the given key. If the key is not found, or the value cannot be converted to an integer, a default value is returned. Args: kwargs (dict): A dictionary of keyword arguments. key (str): The key to retrieve from the kwargs dictionary. default_value (int, optional): The default value to return if the key is not found or the value is not an integer. Returns: int: The integer value if found and valid, otherwise the default value.
get_int_or_default
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def get_float_or_default(kwargs, key, default_value=0.0): """ Retrieves a float value from the provided kwargs dictionary based on the given key. If the key is not found, or the value cannot be converted to a float, a default value is returned. This function attempts to convert the value to a float, which works for integers, floats, and strings that represent valid floating-point numbers. If the conversion fails, the issue is logged, and the provided default_value is returned. Args: kwargs (dict): A dictionary of keyword arguments. key (str): The key to retrieve from the kwargs dictionary. default_value (float, optional): The default value to return if the key is not found or the value is not a float. Returns: float: The float value if found and valid, otherwise the default value. """ # Try to retrieve the value for the specified key from the kwargs. # Use the provided default_value if the key does not exist. value = kwargs.get(key, default_value) try: # Try to convert the value to a float. This should works for int, float, # and strings that represent a valid floating-point number. return float(value) except ValueError: # If the conversion fails (for example, the value is a string that cannot # be converted to a float), log the issue and return the provided default_value. log.info( f"{key} is not an int, float or a valid string for conversion, setting value to {default_value}" ) return default_value
Retrieves a float value from the provided kwargs dictionary based on the given key. If the key is not found, or the value cannot be converted to a float, a default value is returned. This function attempts to convert the value to a float, which works for integers, floats, and strings that represent valid floating-point numbers. If the conversion fails, the issue is logged, and the provided default_value is returned. Args: kwargs (dict): A dictionary of keyword arguments. key (str): The key to retrieve from the kwargs dictionary. default_value (float, optional): The default value to return if the key is not found or the value is not a float. Returns: float: The float value if found and valid, otherwise the default value.
get_float_or_default
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def get_str_or_default(kwargs, key, default_value=""): """ Retrieves a string value from the provided kwargs dictionary based on the given key. If the key is not found, or the value is not a string, a default value is returned. Args: kwargs (dict): A dictionary of keyword arguments. key (str): The key to retrieve from the kwargs dictionary. default_value (str, optional): The default value to return if the key is not found or the value is not a string. Returns: str: The string value if found and valid, otherwise the default value. """ # Try to retrieve the value for the specified key from the kwargs. # Use the provided default_value if the key does not exist. value = kwargs.get(key, default_value) # Check if the retrieved value is already a string. if isinstance(value, str): return value else: # If the value is not a string (e.g., int, float, or any other type), # convert it to a string and return the converted value. return str(value)
Retrieves a string value from the provided kwargs dictionary based on the given key. If the key is not found, or the value is not a string, a default value is returned. Args: kwargs (dict): A dictionary of keyword arguments. key (str): The key to retrieve from the kwargs dictionary. default_value (str, optional): The default value to return if the key is not found or the value is not a string. Returns: str: The string value if found and valid, otherwise the default value.
get_str_or_default
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def run_cmd_advanced_training(run_cmd: list = [], **kwargs): """ This function, run_cmd_advanced_training, dynamically constructs a command line string for advanced training configurations based on provided keyword arguments (kwargs). Each argument represents a different training parameter or flag that can be used to customize the training process. The function checks for the presence and validity of arguments, appending them to the command line string with appropriate formatting. Purpose The primary purpose of this function is to enable flexible and customizable training configurations for machine learning models. It allows users to specify a wide range of parameters and flags that control various aspects of the training process, such as learning rates, batch sizes, augmentation options, precision settings, and many more. Args: kwargs (dict): A variable number of keyword arguments that represent different training parameters or flags. Each argument has a specific expected data type and format, which the function checks before appending to the command line string. Returns: str: A command line string constructed based on the provided keyword arguments. This string includes the base command and additional parameters and flags tailored to the user's specifications for the training process """ if "additional_parameters" in kwargs and kwargs["additional_parameters"] != "": additional_parameters = kwargs["additional_parameters"].replace('"', "") for arg in additional_parameters.split(): run_cmd.append(shlex.quote(arg)) if "max_data_loader_n_workers" in kwargs: max_data_loader_n_workers = kwargs.get("max_data_loader_n_workers") if max_data_loader_n_workers != "": run_cmd.append("--max_data_loader_n_workers") run_cmd.append(str(max_data_loader_n_workers)) return run_cmd
This function, run_cmd_advanced_training, dynamically constructs a command line string for advanced training configurations based on provided keyword arguments (kwargs). Each argument represents a different training parameter or flag that can be used to customize the training process. The function checks for the presence and validity of arguments, appending them to the command line string with appropriate formatting. Purpose The primary purpose of this function is to enable flexible and customizable training configurations for machine learning models. It allows users to specify a wide range of parameters and flags that control various aspects of the training process, such as learning rates, batch sizes, augmentation options, precision settings, and many more. Args: kwargs (dict): A variable number of keyword arguments that represent different training parameters or flags. Each argument has a specific expected data type and format, which the function checks before appending to the command line string. Returns: str: A command line string constructed based on the provided keyword arguments. This string includes the base command and additional parameters and flags tailored to the user's specifications for the training process
run_cmd_advanced_training
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def verify_image_folder_pattern(folder_path: str) -> bool: """ Verify the image folder pattern in the given folder path. Args: folder_path (str): The path to the folder containing image folders. Returns: bool: True if the image folder pattern is valid, False otherwise. """ # Initialize the return value to True return_value = True # Log the start of the verification process log.info(f"Verifying image folder pattern of {folder_path}...") # Check if the folder exists if not os.path.isdir(folder_path): # Log an error message if the folder does not exist log.error( f"...the provided path '{folder_path}' is not a valid folder. " "Please follow the folder structure documentation found at docs\image_folder_structure.md ..." ) # Return False to indicate that the folder pattern is not valid return False # Create a regular expression pattern to match the required sub-folder names # The pattern should start with one or more digits (\d+) followed by an underscore (_) # After the underscore, it should match one or more word characters (\w+), which can be letters, numbers, or underscores # Example of a valid pattern matching name: 123_example_folder pattern = r"^\d+_\w+" # Get the list of sub-folders in the directory subfolders = [ os.path.join(folder_path, subfolder) for subfolder in os.listdir(folder_path) if os.path.isdir(os.path.join(folder_path, subfolder)) ] # Check the pattern of each sub-folder matching_subfolders = [ subfolder for subfolder in subfolders if re.match(pattern, os.path.basename(subfolder)) ] # Print non-matching sub-folders non_matching_subfolders = set(subfolders) - set(matching_subfolders) if non_matching_subfolders: # Log an error message if any sub-folders do not match the pattern log.error( f"...the following folders do not match the required pattern <number>_<text>: {', '.join(non_matching_subfolders)}" ) # Log an error message suggesting to follow the folder structure documentation log.error( f"...please follow the folder structure documentation found at docs\image_folder_structure.md ..." ) # Return False to indicate that the folder pattern is not valid return False # Check if no sub-folders exist if not matching_subfolders: # Log an error message if no image folders are found log.error( f"...no image folders found in {folder_path}. " "Please follow the folder structure documentation found at docs\image_folder_structure.md ..." ) # Return False to indicate that the folder pattern is not valid return False # Log the successful verification log.info(f"...valid") # Return True to indicate that the folder pattern is valid return return_value
Verify the image folder pattern in the given folder path. Args: folder_path (str): The path to the folder containing image folders. Returns: bool: True if the image folder pattern is valid, False otherwise.
verify_image_folder_pattern
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def SaveConfigFile( parameters, file_path: str, exclusion: list = ["file_path", "save_as", "headless", "print_only"], ) -> None: """ Saves the configuration parameters to a JSON file, excluding specified keys. This function iterates over a dictionary of parameters, filters out keys listed in the `exclusion` list, and saves the remaining parameters to a JSON file specified by `file_path`. Args: parameters (dict): Dictionary containing the configuration parameters. file_path (str): Path to the file where the filtered parameters should be saved. exclusion (list): List of keys to exclude from saving. Defaults to ["file_path", "save_as", "headless", "print_only"]. """ # Return the values of the variables as a dictionary variables = { name: value for name, value in sorted(parameters, key=lambda x: x[0]) if name not in exclusion } # Check if the folder path for the file_path is valid # Extrach folder path folder_path = os.path.dirname(file_path) # Check if the folder exists if not os.path.exists(folder_path): # If not, create the folder os.makedirs(os.path.dirname(folder_path)) log.info(f"Creating folder {folder_path} for the configuration file...") # Save the data to the specified JSON file with open(file_path, "w", encoding="utf-8") as file: json.dump(variables, file, indent=2)
Saves the configuration parameters to a JSON file, excluding specified keys. This function iterates over a dictionary of parameters, filters out keys listed in the `exclusion` list, and saves the remaining parameters to a JSON file specified by `file_path`. Args: parameters (dict): Dictionary containing the configuration parameters. file_path (str): Path to the file where the filtered parameters should be saved. exclusion (list): List of keys to exclude from saving. Defaults to ["file_path", "save_as", "headless", "print_only"].
SaveConfigFile
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def save_to_file(content): """ Appends the given content to a file named 'print_command.txt' within a 'logs' directory. This function checks for the existence of a 'logs' directory and creates it if it doesn't exist. Then, it appends the provided content along with a newline character to the 'print_command.txt' file within this directory. Args: content (str): The content to be saved to the file. """ logs_directory = "logs" file_path = os.path.join(logs_directory, "print_command.txt") # Ensure the 'logs' directory exists if not os.path.exists(logs_directory): os.makedirs(logs_directory) # Append content to the specified file try: with open(file_path, "a", encoding="utf-8") as file: file.write(content + "\n") except IOError as e: print(f"Error: Could not write to file - {e}") except OSError as e: print(f"Error: Could not create 'logs' directory - {e}")
Appends the given content to a file named 'print_command.txt' within a 'logs' directory. This function checks for the existence of a 'logs' directory and creates it if it doesn't exist. Then, it appends the provided content along with a newline character to the 'print_command.txt' file within this directory. Args: content (str): The content to be saved to the file.
save_to_file
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def check_duplicate_filenames( folder_path: str, image_extension: list = [".gif", ".png", ".jpg", ".jpeg", ".webp"], ) -> None: """ Checks for duplicate image filenames in a given folder path. This function walks through the directory structure of the given folder path, and logs a warning if it finds files with the same name but different image extensions. This can lead to issues during training if not handled properly. Args: folder_path (str): The path to the folder containing image files. image_extension (list, optional): List of image file extensions to consider. Defaults to [".gif", ".png", ".jpg", ".jpeg", ".webp"]. """ # Initialize a flag to track if duplicates are found duplicate = False # Log the start of the duplicate check log.info( f"Checking for duplicate image filenames in training data directory {folder_path}..." ) # Walk through the directory structure for root, dirs, files in os.walk(folder_path): # Initialize a dictionary to store filenames and their paths filenames = {} # Process each file in the current directory for file in files: # Split the filename and extension filename, extension = os.path.splitext(file) # Check if the extension is in the list of image extensions if extension.lower() in image_extension: # Construct the full path to the file full_path = os.path.join(root, file) # Check if the filename is already in the dictionary if filename in filenames: # If it is, compare the existing path with the current path existing_path = filenames[filename] if existing_path != full_path: # Log a warning if the paths are different log.warning( f"...same filename '{filename}' with different image extension found. This will cause training issues. Rename one of the file." ) log.warning(f" Existing file: {existing_path}") log.warning(f" Current file: {full_path}") # Set the duplicate flag to True duplicate = True else: # If not, add the filename and path to the dictionary filenames[filename] = full_path # If no duplicates were found, log a message indicating validation if not duplicate: log.info("...valid")
Checks for duplicate image filenames in a given folder path. This function walks through the directory structure of the given folder path, and logs a warning if it finds files with the same name but different image extensions. This can lead to issues during training if not handled properly. Args: folder_path (str): The path to the folder containing image files. image_extension (list, optional): List of image file extensions to consider. Defaults to [".gif", ".png", ".jpg", ".jpeg", ".webp"].
check_duplicate_filenames
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def validate_model_path(pretrained_model_name_or_path: str) -> bool: """ Validates the pretrained model name or path against Hugging Face models or local paths. Args: pretrained_model_name_or_path (str): The pretrained model name or path to validate. Returns: bool: True if the path is a valid Hugging Face model or exists locally; False otherwise. """ from .class_source_model import default_models msg = f"Validating {pretrained_model_name_or_path} existence..." # Check if it matches the Hugging Face model pattern if re.match(r"^[\w-]+\/[\w-]+$", pretrained_model_name_or_path): log.info(f"{msg} SKIPPING: huggingface.co model") elif pretrained_model_name_or_path in default_models: log.info(f"{msg} SUCCESS") else: # If not one of the default models, check if it's a valid local path if not validate_file_path( pretrained_model_name_or_path ) and not validate_folder_path(pretrained_model_name_or_path): log.info(f"{msg} FAILURE: not a valid file or folder") return False return True
Validates the pretrained model name or path against Hugging Face models or local paths. Args: pretrained_model_name_or_path (str): The pretrained model name or path to validate. Returns: bool: True if the path is a valid Hugging Face model or exists locally; False otherwise.
validate_model_path
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def is_file_writable(file_path: str) -> bool: """ Checks if a file is writable. Args: file_path (str): The path to the file to be checked. Returns: bool: True if the file is writable, False otherwise. """ # If the file does not exist, it is considered writable if not os.path.exists(file_path): return True try: # Attempt to open the file in append mode to check if it can be written to with open(file_path, "a", encoding="utf-8"): pass # If the file can be opened, it is considered writable return True except IOError as e: # If an IOError occurs, the file cannot be written to log.info(f"Error: {e}. File '{file_path}' is not writable.") return False
Checks if a file is writable. Args: file_path (str): The path to the file to be checked. Returns: bool: True if the file is writable, False otherwise.
is_file_writable
python
bmaltais/kohya_ss
kohya_gui/common_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/common_gui.py
Apache-2.0
def gradio_convert_lcm_tab(headless=False): """ Creates a Gradio tab for converting a model to an LCM model. Args: headless (bool): If True, the tab will be created without any visible elements. Returns: None """ current_model_dir = os.path.join(scriptdir, "outputs") current_save_dir = os.path.join(scriptdir, "outputs") def list_models(path): """ Lists all model files in the given directory. Args: path (str): The directory path to search for model files. Returns: list: A list of model file paths. """ nonlocal current_model_dir current_model_dir = path return list(list_files(path, exts=[".safetensors"], all=True)) def list_save_to(path): """ Lists all save-to options for the given directory. Args: path (str): The directory path to search for save-to options. Returns: list: A list of save-to options. """ nonlocal current_save_dir current_save_dir = path return list(list_files(path, exts=[".safetensors"], all=True)) with gr.Tab("Convert to LCM"): gr.Markdown("This utility convert a model to an LCM model.") lora_ext = gr.Textbox(value="*.safetensors", visible=False) lora_ext_name = gr.Textbox(value="LCM model types", visible=False) model_ext = gr.Textbox(value="*.safetensors", visible=False) model_ext_name = gr.Textbox(value="Model types", visible=False) with gr.Group(), gr.Row(): model_path = gr.Dropdown( label="Stable Diffusion model to convert to LCM", interactive=True, choices=[""] + list_models(current_model_dir), value="", allow_custom_value=True, ) create_refresh_button( model_path, lambda: None, lambda: {"choices": list_models(current_model_dir)}, "open_folder_small", ) button_model_path_file = gr.Button( folder_symbol, elem_id="open_folder_small", elem_classes=["tool"], visible=(not headless), ) button_model_path_file.click( get_file_path, inputs=[model_path, model_ext, model_ext_name], outputs=model_path, show_progress=False, ) name = gr.Dropdown( label="Name of the new LCM model", interactive=True, choices=[""] + list_save_to(current_save_dir), value="", allow_custom_value=True, ) create_refresh_button( name, lambda: None, lambda: {"choices": list_save_to(current_save_dir)}, "open_folder_small", ) button_name = gr.Button( folder_symbol, elem_id="open_folder_small", elem_classes=["tool"], visible=(not headless), ) button_name.click( get_saveasfilename_path, inputs=[name, lora_ext, lora_ext_name], outputs=name, show_progress=False, ) model_path.change( fn=lambda path: gr.Dropdown(choices=[""] + list_models(path)), inputs=model_path, outputs=model_path, show_progress=False, ) name.change( fn=lambda path: gr.Dropdown(choices=[""] + list_save_to(path)), inputs=name, outputs=name, show_progress=False, ) with gr.Row(): lora_scale = gr.Slider( label="Strength of the LCM", minimum=0.0, maximum=2.0, step=0.1, value=1.0, interactive=True, ) # with gr.Row(): # no_half = gr.Checkbox(label="Convert the new LCM model to FP32", value=False) model_type = gr.Radio( label="Model type", choices=["SD15", "SDXL", "SD-1B"], value="SD15" ) extract_button = gr.Button("Extract LCM") extract_button.click( convert_lcm, inputs=[ name, model_path, lora_scale, model_type, ], show_progress=False, )
Creates a Gradio tab for converting a model to an LCM model. Args: headless (bool): If True, the tab will be created without any visible elements. Returns: None
gradio_convert_lcm_tab
python
bmaltais/kohya_ss
kohya_gui/convert_lcm_gui.py
https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/convert_lcm_gui.py
Apache-2.0