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 __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 connectio... | 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.
""... |
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 __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 th... |
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 M... | __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... |
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_... |
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.acqu... |
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 fu... |
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:
... |
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 us... |
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 ... | 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.
... |
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 i... |
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 ima... |
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... | 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 representi... |
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(
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 speci... |
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
... | 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 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 vis... | 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: dic... |
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.
... | __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_contro... |
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... |
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,
... |
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",
... |
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)
... |
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.dre... |
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(
... |
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(
lab... |
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... |
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.... |
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 ... | 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 s... |
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 par... |
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.
"""... |
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 "."
... |
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.headl... |
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 o... |
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... |
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"{co... |
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 associat... |
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 i... | 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_loa... |
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.... |
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),
... |
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:
... |
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): Configuratio... | __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 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.
... |
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.
... |
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 (st... |
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, opti... | 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 bo... |
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 logg... | 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 ... |
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 th... | 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 pro... |
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 vari... | 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 mac... |
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,
i... | 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 dia... |
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 pres... | 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 pa... |
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 variable... | 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 ... |
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 captio... | 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... |
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 ('.'... | 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 ... |
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 p... | 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 intera... |
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 augmenta... | 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 c... |
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:
pretraine... | 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 arg... |
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 kwarg... | 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, wh... |
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 va... | 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... |
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.
... | 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 ... |
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 f... | 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.
"""
# In... |
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
i... |
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): Dictio... | 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... |
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 dir... | 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... |
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:... | 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 ... |
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.pat... |
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_d... |
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 |
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
re... |
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.
| list_models | 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 |
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
... |
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.
| list_save_to | 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 |
def _get_caption_path(image_file, images_dir, caption_ext):
"""
Returns the expected path of a caption file for a given image path
"""
caption_file_name = os.path.splitext(image_file)[0] + caption_ext
caption_file_path = os.path.join(images_dir, caption_file_name)
return caption_file_path |
Returns the expected path of a caption file for a given image path
| _get_caption_path | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def _get_quick_tags(quick_tags_text):
"""
Gets a list of tags from the quick tags text box
"""
quick_tags = [t.strip() for t in quick_tags_text.split(",") if t.strip()]
quick_tags_set = set(quick_tags)
return quick_tags, quick_tags_set |
Gets a list of tags from the quick tags text box
| _get_quick_tags | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def _get_tag_checkbox_updates(caption, quick_tags, quick_tags_set):
"""
Updates a list of caption checkboxes to show possible tags and tags
already included in the caption
"""
caption_tags_have = [c.strip() for c in caption.split(",") if c.strip()]
caption_tags_unique = [t for t in caption_tags_... |
Updates a list of caption checkboxes to show possible tags and tags
already included in the caption
| _get_tag_checkbox_updates | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def import_tags_from_captions(
images_dir, caption_ext, quick_tags_text, ignore_load_tags_word_count
):
"""
Scans images directory for all available captions and loads all tags
under a specified word count into the quick tags box
"""
def empty_return():
return gr.Text()
# Check for... |
Scans images directory for all available captions and loads all tags
under a specified word count into the quick tags box
| import_tags_from_captions | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def load_images(images_dir, caption_ext, loaded_images_dir, page, max_page):
"""
Triggered to load a new set of images from the folder to caption
This loads in the total expected image counts to be used by pagination
before running update_images
"""
def empty_return():
return [loaded_im... |
Triggered to load a new set of images from the folder to caption
This loads in the total expected image counts to be used by pagination
before running update_images
| load_images | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def update_images(
images_dir,
caption_ext,
quick_tags_text,
page,
):
"""
Updates the displayed images and captions from the current page and
image directory
"""
# Load Images
images_list = os.listdir(images_dir)
image_files = [f for f in images_list if f.lower().endswith(IM... |
Updates the displayed images and captions from the current page and
image directory
| update_images | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def check_python_version():
"""
Check if the current Python version is within the acceptable range.
Returns:
bool: True if the current Python version is valid, False otherwise.
"""
log.debug("Checking Python version...")
try:
current_version = sys.version_info
log.info(f"... |
Check if the current Python version is within the acceptable range.
Returns:
bool: True if the current Python version is valid, False otherwise.
| check_python_version | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def update_submodule(quiet=True):
"""
Ensure the submodule is initialized and updated.
"""
log.debug("Updating submodule...")
git_command = ["git", "submodule", "update", "--init", "--recursive"]
if quiet:
git_command.append("--quiet")
try:
subprocess.run(git_command, check=... |
Ensure the submodule is initialized and updated.
| update_submodule | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def clone_or_checkout(repo_url, branch_or_tag, directory_name):
"""
Clone a repo or checkout a specific branch or tag if the repo already exists.
"""
log.debug(
f"Cloning or checking out repository: {repo_url}, branch/tag: {branch_or_tag}, directory: {directory_name}"
)
original_dir = os... |
Clone a repo or checkout a specific branch or tag if the repo already exists.
| clone_or_checkout | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def setup_logging():
"""
Set up logging to file and console.
"""
log.debug("Setting up logging...")
from rich.theme import Theme
from rich.logging import RichHandler
from rich.console import Console
console = Console(
log_time=True,
log_time_format="%H:%M:%S-%f",
... |
Set up logging to file and console.
| setup_logging | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def check_repo_version():
"""
This function checks the version of the repository by reading the contents of a file named '.release'
in the current directory. If the file exists, it reads the release version from the file and logs it.
If the file does not exist, it logs a debug message indicating that th... |
This function checks the version of the repository by reading the contents of a file named '.release'
in the current directory. If the file exists, it reads the release version from the file and logs it.
If the file does not exist, it logs a debug message indicating that the release could not be read.
| check_repo_version | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def pip(arg: str, ignore: bool = False, quiet: bool = False, show_stdout: bool = False):
"""
Executes a pip command with the specified arguments.
This function is designed to run pip commands and handle their output.
It can be used to install, upgrade, or uninstall packages using pip.
If an error o... |
Executes a pip command with the specified arguments.
This function is designed to run pip commands and handle their output.
It can be used to install, upgrade, or uninstall packages using pip.
If an error occurs during the pip operation and the 'ignore' flag is not set,
it logs the error message a... | pip | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def installed(package, friendly: str = None):
"""
Checks if the specified package(s) are installed with the correct version.
This function can handle package specifications with or without version constraints,
and can also filter out command-line options and URLs when a 'friendly' string is provided.
... |
Checks if the specified package(s) are installed with the correct version.
This function can handle package specifications with or without version constraints,
and can also filter out command-line options and URLs when a 'friendly' string is provided.
Parameters:
- package: A string that specifies... | installed | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def install(
package,
friendly: str = None,
ignore: bool = False,
reinstall: bool = False,
show_stdout: bool = False,
):
"""
Installs or upgrades a Python package using pip, with options to ignode errors,
reinstall packages, and display outputs.
Parameters:
- package (str): The ... |
Installs or upgrades a Python package using pip, with options to ignode errors,
reinstall packages, and display outputs.
Parameters:
- package (str): The name of the package to be installed or upgraded. Can include
version specifiers. Anything after a '#' in the package name will be ignored.
... | install | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def install_requirements(
requirements_file, check_no_verify_flag=False, show_stdout: bool = False
):
"""
Install or verify modules from a requirements file.
Parameters:
- requirements_file (str): Path to the requirements file.
- check_no_verify_flag (bool): If True, verify modules installation... |
Install or verify modules from a requirements file.
Parameters:
- requirements_file (str): Path to the requirements file.
- check_no_verify_flag (bool): If True, verify modules installation status without installing.
- show_stdout (bool): If True, show the standard output of the installation proce... | install_requirements | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def sync_bits_and_bytes_files():
"""
Check for "different" bitsandbytes Files and copy only if necessary.
This function is specific for Windows OS.
"""
# Only execute on Windows
if os.name != "nt":
print("This function is only applicable to Windows OS.")
return
try:
... |
Check for "different" bitsandbytes Files and copy only if necessary.
This function is specific for Windows OS.
| sync_bits_and_bytes_files | python | bmaltais/kohya_ss | setup/update_bitsandbytes.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/update_bitsandbytes.py | Apache-2.0 |
def check_path_with_space():
"""Check if the current working directory contains a space."""
cwd = os.getcwd()
log.debug(f"Current working directory: {cwd}")
if " " in cwd:
# Log an error if the current working directory contains spaces
log.error(
"The path in which this pytho... | Check if the current working directory contains a space. | check_path_with_space | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def detect_toolkit():
"""Detect the available toolkit (NVIDIA, AMD, or Intel) and log the information."""
log.debug("Detecting available toolkit...")
# Check for NVIDIA toolkit by looking for nvidia-smi executable
if shutil.which("nvidia-smi") or os.path.exists(
os.path.join(
os.envi... | Detect the available toolkit (NVIDIA, AMD, or Intel) and log the information. | detect_toolkit | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def check_torch():
"""Check if torch is available and log the relevant information."""
# Detect the available toolkit (e.g., NVIDIA, AMD, Intel, or CPU)
toolkit = detect_toolkit()
log.info(f"{toolkit} toolkit detected")
try:
# Import PyTorch
log.debug("Importing PyTorch...")
... | Check if torch is available and log the relevant information. | check_torch | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def log_cuda_info(torch):
"""Log information about CUDA-enabled GPUs."""
# Log the CUDA and cuDNN versions if available
if torch.version.cuda:
log.info(
f'Torch backend: nVidia CUDA {torch.version.cuda} cuDNN {torch.backends.cudnn.version() if torch.backends.cudnn.is_available() else "N/... | Log information about CUDA-enabled GPUs. | log_cuda_info | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def log_mps_info(torch):
"""Log information about Apple Silicone (MPS)"""
max_reccomended_mem = round(torch.mps.recommended_max_memory() / 1024**2)
log.info(
f"Torch detected Apple MPS: {max_reccomended_mem}MB Unified Memory Available"
)
log.warning('MPS support is still experimental, procee... | Log information about Apple Silicone (MPS) | log_mps_info | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def log_xpu_info(torch, ipex):
"""Log information about Intel XPU-enabled GPUs."""
# Log the Intel Extension for PyTorch (IPEX) version if available
if ipex:
log.info(f"Torch backend: Intel IPEX {ipex.__version__}")
# Log information about each detected XPU-enabled GPU
for device in range(to... | Log information about Intel XPU-enabled GPUs. | log_xpu_info | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def writable_dir(target_path):
""" Check if a path is a valid directory and that it can be written to. """
path = Path(target_path)
if path.is_dir():
if os.access(path, os.W_OK):
return path
else:
raise argparse.ArgumentTypeError(f"Directory '{path}' is not writable."... | Check if a path is a valid directory and that it can be written to. | writable_dir | python | bmaltais/kohya_ss | tools/caption.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/caption.py | Apache-2.0 |
def create_text_file(image_filename, output_directory, text_extension):
"""Create a text file with the same name as the image file."""
# Extract prompt from filename
prompt = Path(image_filename).stem
# Construct path for the output text file
text_file_path = Path(output_directory) / (prompt + text... | Create a text file with the same name as the image file. | create_text_file | python | bmaltais/kohya_ss | tools/caption_from_filename.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/caption_from_filename.py | Apache-2.0 |
def aspect_ratio(img_path):
"""
Calculate and return the aspect ratio of an image.
Parameters:
img_path: A string representing the path to the input image.
Returns:
float: Aspect ratio of the input image, defined as width / height.
Returns None if the image cannot be read.
... |
Calculate and return the aspect ratio of an image.
Parameters:
img_path: A string representing the path to the input image.
Returns:
float: Aspect ratio of the input image, defined as width / height.
Returns None if the image cannot be read.
| aspect_ratio | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def sort_images_by_aspect_ratio(path):
"""Sort all images in a folder by aspect ratio"""
images = []
for filename in os.listdir(path):
if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png") or filename.endswith(".webp"):
print(filename)
img_pa... | Sort all images in a folder by aspect ratio | sort_images_by_aspect_ratio | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def create_groups(sorted_images, n_groups):
"""
Create groups of images from a sorted list of images.
This function takes a sorted list of images and a group size as input, and returns a list of groups,
where each group contains a specified number of images.
Parameters:
sorted_images (list of ... |
Create groups of images from a sorted list of images.
This function takes a sorted list of images and a group size as input, and returns a list of groups,
where each group contains a specified number of images.
Parameters:
sorted_images (list of tuples): A list of tuples, where each tuple contain... | create_groups | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def average_aspect_ratio(group):
"""
Calculate the average aspect ratio for a given group of images.
Parameters:
group (list of tuples):, A list of tuples, where each tuple contains the path to an image and its aspect ratio.
Returns:
float: The average aspect ratio of the images in the group.
... |
Calculate the average aspect ratio for a given group of images.
Parameters:
group (list of tuples):, A list of tuples, where each tuple contains the path to an image and its aspect ratio.
Returns:
float: The average aspect ratio of the images in the group.
| average_aspect_ratio | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def center_crop_image(image, target_aspect_ratio):
"""Crop the input image to the target aspect ratio.
The function calculates the crop region for the input image based on its current aspect ratio and the target aspect ratio.
Args:
image: A numpy array representing the input image.
target_... | Crop the input image to the target aspect ratio.
The function calculates the crop region for the input image based on its current aspect ratio and the target aspect ratio.
Args:
image: A numpy array representing the input image.
target_aspect_ratio: A float representing the target aspect ratio... | center_crop_image | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def copy_related_files(img_path, save_path):
"""
Copy all files in the same directory as the input image that have the same base name as the input image to the
output directory with the corresponding new filename.
Args:
img_path (str): Path to the input image file.
save_path: Path to th... |
Copy all files in the same directory as the input image that have the same base name as the input image to the
output directory with the corresponding new filename.
Args:
img_path (str): Path to the input image file.
save_path: Path to the output directory where the files should be copied ... | copy_related_files | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.