index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
112 | /home/hieuvd/dung_repo/raw/stars_01/3b1b_manim/manim | /home/hieuvd/dung_repo/raw/stars_01/3b1b_manim/manim/manimlib/utils/tex.py | 8,9 | 1,41 | num_tex_symbols | 15,41 | 9,41 | from __future__ import annotations
import re
from manimlib.utils.tex_to_symbol_count import TEX_TO_SYMBOL_COUNT
def num_tex_symbols(tex: str) -> int:
FILL_FUNC_BODY | from __future__ import annotations
import re
from manimlib.utils.tex_to_symbol_count import TEX_TO_SYMBOL_COUNT
def num_tex_symbols(tex: str) -> int:
"""
This function attempts to estimate the number of symbols that
a given string of tex would produce.
Warning, it may not behave perfectly
"""
F... | # First, remove patterns like \begin{align}, \phantom{thing},
# \begin{array}{cc}, etc.
pattern = "|".join(
rf"(\\{s})" + r"(\{\w+\})?(\{\w+\})?(\[\w+\])?"
for s in ["begin", "end", "phantom"]
)
tex = re.sub(pattern, "", tex)
# Progressively count the symbols associated with cer... | """
This function attempts to estimate the number of symbols that
a given string of tex would produce.
Warning, it may not behave perfectly
"""
# First, remove patterns like \begin{align}, \phantom{thing},
# \begin{array}{cc}, etc.
pattern = "|".join(
rf"(\\{s})" + r"(\{\w+\})?(... | 119 | 108 | 377 | 485 | from __future__ import annotations
import re
from manimlib.utils.tex_to_symbol_count import TEX_TO_SYMBOL_COUNT
def num_tex_symbols(tex: str) -> int:
FILL_FUNC_BODY | from __future__ import annotations
import re
from manimlib.utils.tex_to_symbol_count import TEX_TO_SYMBOL_COUNT
def num_tex_symbols(tex: str) -> int:
"""
This function attempts to estimate the number of symbols that
a given string of tex would produce.
Warning, it may not behave perfectly
"""
F... | |
113 | /home/hieuvd/dung_repo/raw/stars_01/3b1b_manim/manim | /home/hieuvd/dung_repo/raw/stars_01/3b1b_manim/manim/manimlib/utils/tex_file_writing.py | 54,58 | 1,165 | tex_content_to_svg_file | 58,87 | 58,87 | from __future__ import annotations
from contextlib import contextmanager
import os
import re
import yaml
from manimlib.config import get_custom_config
from manimlib.config import get_manim_dir
from manimlib.logger import log
from manimlib.utils.directories import get_tex_dir
from manimlib.utils.simple_functions impor... | from __future__ import annotations
from contextlib import contextmanager
import os
import re
import yaml
from manimlib.config import get_custom_config
from manimlib.config import get_manim_dir
from manimlib.logger import log
from manimlib.utils.directories import get_tex_dir
from manimlib.utils.simple_functions impor... | tex_config = get_tex_config()
if not template or template == tex_config["template"]:
compiler = tex_config["compiler"]
preamble = tex_config["preamble"]
else:
config = get_tex_template_config(template)
compiler = config["compiler"]
preamble = config["preamble"]
i... | tex_config = get_tex_config()
if not template or template == tex_config["template"]:
compiler = tex_config["compiler"]
preamble = tex_config["preamble"]
else:
config = get_tex_template_config(template)
compiler = config["compiler"]
preamble = config["preamble"]
i... | 72 | 1,265 | 318 | 1,583 | from __future__ import annotations
from contextlib import contextmanager
import os
import re
import yaml
from manimlib.config import get_custom_config
from manimlib.config import get_manim_dir
from manimlib.logger import log
from manimlib.utils.directories import get_tex_dir
from manimlib.utils.simple_functions impor... | from __future__ import annotations
from contextlib import contextmanager
import os
import re
import yaml
from manimlib.config import get_custom_config
from manimlib.config import get_manim_dir
from manimlib.logger import log
from manimlib.utils.directories import get_tex_dir
from manimlib.utils.simple_functions impor... | |
114 | /home/hieuvd/dung_repo/raw/stars_01/3b1b_manim/manim | /home/hieuvd/dung_repo/raw/stars_01/3b1b_manim/manim/manimlib/window.py | 57,58 | 19,154 | find_initial_position | Window | 58,79 | 58,79 | class Window(PygletWindow):
fullscreen: bool = False
resizable: bool = True
gl_version: tuple[int, int] = (3, 3)
vsync: bool = True
cursor: bool = True
def __init__(
self,
scene: Scene,
size: tuple[int, int] = (1280, 720),
samples: int = 0
):
scene.wi... | class Window(PygletWindow):
fullscreen: bool = False
resizable: bool = True
gl_version: tuple[int, int] = (3, 3)
vsync: bool = True
cursor: bool = True
def __init__(
self,
scene: Scene,
size: tuple[int, int] = (1280, 720),
samples: int = 0
):
scene.wi... | custom_position = get_customization()["window_position"]
monitors = get_monitors()
mon_index = get_customization()["window_monitor"]
monitor = monitors[min(mon_index, len(monitors) - 1)]
window_width, window_height = size
# Position might be specified with a string of the... | custom_position = get_customization()["window_position"]
monitors = get_monitors()
mon_index = get_customization()["window_monitor"]
monitor = monitors[min(mon_index, len(monitors) - 1)]
window_width, window_height = size
# Position might be specified with a string of the... | 111 | 1,532 | 317 | 1,849 | from __future__ import annotations
import numpy as np
import moderngl_window as mglw
from moderngl_window.context.pyglet.window import Window as PygletWindow
from moderngl_window.timers.clock import Timer
from screeninfo import get_monitors
from manimlib.constants import FRAME_SHAPE
from manimlib.utils.customization... | from __future__ import annotations
import numpy as np
import moderngl_window as mglw
from moderngl_window.context.pyglet.window import Window as PygletWindow
from moderngl_window.timers.clock import Timer
from screeninfo import get_monitors
from manimlib.constants import FRAME_SHAPE
from manimlib.utils.customization... |
117 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/LDSR/ldsr_model_arch.py | 106,107 | 21,157 | super_resolution | LDSR | 107,157 | 107,157 | class LDSR:
def load_model_from_config(self, half_attention):
global cached_ldsr_model
if shared.opts.ldsr_cached and cached_ldsr_model is not None:
print("Loading model from cache")
model: torch.nn.Module = cached_ldsr_model
else:
print(f"Loading model f... | class LDSR:
def load_model_from_config(self, half_attention):
global cached_ldsr_model
if shared.opts.ldsr_cached and cached_ldsr_model is not None:
print("Loading model from cache")
model: torch.nn.Module = cached_ldsr_model
else:
print(f"Loading model f... | model = self.load_model_from_config(half_attention)
# Run settings
diffusion_steps = int(steps)
eta = 1.0
gc.collect()
devices.torch_gc()
im_og = image
width_og, height_og = im_og.size
# If we can adjust the max upscale size, then the 4 below s... | model = self.load_model_from_config(half_attention)
# Run settings
diffusion_steps = int(steps)
eta = 1.0
gc.collect()
devices.torch_gc()
im_og = image
width_og, height_og = im_og.size
# If we can adjust the max upscale size, then the 4 below s... | 186 | 1,047 | 694 | 1,741 | import os
import gc
import time
import numpy as np
import torch
import torchvision
from PIL import Image
from einops import rearrange, repeat
from omegaconf import OmegaConf
import safetensors.torch
from ldm.models.diffusion.ddim import DDIMSampler
from ldm.util import instantiate_from_config, ismap
from modules impo... | import os
import gc
import time
import numpy as np
import torch
import torchvision
from PIL import Image
from einops import rearrange, repeat
from omegaconf import OmegaConf
import safetensors.torch
from ldm.models.diffusion.ddim import DDIMSampler
from ldm.util import instantiate_from_config, ismap
from modules impo... |
118 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/LDSR/preload.py | 5,6 | 1,7 | preload | 6,7 | 6,7 | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | parser.add_argument("--ldsr-models-path", type=str, help="Path to directory with LDSR model file(s).", default=os.path.join(paths.models_path, 'LDSR'))
| parser.add_argument("--ldsr-models-path", type=str, help="Path to directory with LDSR model file(s).", default=os.path.join(paths.models_path, 'LDSR'))
| 11 | 27 | 56 | 83 | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | |
119 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/LDSR/scripts/ldsr_model.py | 61,62 | 1,69 | on_ui_settings | 62,68 | 62,68 | import os
from modules.modelloader import load_file_from_url
from modules.upscaler import Upscaler, UpscalerData
from ldsr_model_arch import LDSR
from modules import shared, script_callbacks, errors
import sd_hijack_autoencoder # noqa: F401
import sd_hijack_ddpm_v1 # noqa: F401
class UpscalerLDSR(Upscaler):
de... | import os
from modules.modelloader import load_file_from_url
from modules.upscaler import Upscaler, UpscalerData
from ldsr_model_arch import LDSR
from modules import shared, script_callbacks, errors
import sd_hijack_autoencoder # noqa: F401
import sd_hijack_ddpm_v1 # noqa: F401
class UpscalerLDSR(Upscaler):
de... | import gradio as gr
shared.opts.add_option("ldsr_steps", shared.OptionInfo(100, "LDSR processing steps. Lower = faster", gr.Slider, {"minimum": 1, "maximum": 200, "step": 1}, section=('upscaling', "Upscaling")))
shared.opts.add_option("ldsr_cached", shared.OptionInfo(False, "Cache LDSR model in memory", gr... | import gradio as gr
shared.opts.add_option("ldsr_steps", shared.OptionInfo(100, "LDSR processing steps. Lower = faster", gr.Slider, {"minimum": 1, "maximum": 200, "step": 1}, section=('upscaling', "Upscaling")))
shared.opts.add_option("ldsr_cached", shared.OptionInfo(False, "Cache LDSR model in memory", gr... | 33 | 999 | 148 | 1,147 | import os
from modules.modelloader import load_file_from_url
from modules.upscaler import Upscaler, UpscalerData
from ldsr_model_arch import LDSR
from modules import shared, script_callbacks, errors
import sd_hijack_autoencoder # noqa: F401
import sd_hijack_ddpm_v1 # noqa: F401
class UpscalerLDSR(Upscaler):
de... | import os
from modules.modelloader import load_file_from_url
from modules.upscaler import Upscaler, UpscalerData
from ldsr_model_arch import LDSR
from modules import shared, script_callbacks, errors
import sd_hijack_autoencoder # noqa: F401
import sd_hijack_ddpm_v1 # noqa: F401
class UpscalerLDSR(Upscaler):
de... | |
120 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/LDSR/scripts/ldsr_model.py | 21,22 | 11,61 | load_model | UpscalerLDSR | 22,51 | 22,51 | class UpscalerLDSR(Upscaler):
def __init__(self, user_path):
self.name = "LDSR"
self.user_path = user_path
self.model_url = "https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1"
self.yaml_url = "https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1"
super().... | class UpscalerLDSR(Upscaler):
def __init__(self, user_path):
self.name = "LDSR"
self.user_path = user_path
self.model_url = "https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1"
self.yaml_url = "https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1"
super().... | # Remove incorrect project.yaml file if too big
yaml_path = os.path.join(self.model_path, "project.yaml")
old_model_path = os.path.join(self.model_path, "model.pth")
new_model_path = os.path.join(self.model_path, "model.ckpt")
local_model_paths = self.find_models(ext_filter=[".c... | # Remove incorrect project.yaml file if too big
yaml_path = os.path.join(self.model_path, "project.yaml")
old_model_path = os.path.join(self.model_path, "model.pth")
new_model_path = os.path.join(self.model_path, "model.ckpt")
local_model_paths = self.find_models(ext_filter=[".c... | 107 | 316 | 575 | 891 | import os
from modules.modelloader import load_file_from_url
from modules.upscaler import Upscaler, UpscalerData
from ldsr_model_arch import LDSR
from modules import shared, script_callbacks, errors
import sd_hijack_autoencoder # noqa: F401
import sd_hijack_ddpm_v1 # noqa: F401
class UpscalerLDSR(Upscaler):
de... | import os
from modules.modelloader import load_file_from_url
from modules.upscaler import Upscaler, UpscalerData
from ldsr_model_arch import LDSR
from modules import shared, script_callbacks, errors
import sd_hijack_autoencoder # noqa: F401
import sd_hijack_ddpm_v1 # noqa: F401
class UpscalerLDSR(Upscaler):
de... |
122 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/LDSR/sd_hijack_autoencoder.py | 282,283 | 272,292 | decode | VQModelInterface | 283,292 | 283,292 | class VQModelInterface(VQModel):
def __init__(self, embed_dim, *args, **kwargs):
super().__init__(*args, embed_dim=embed_dim, **kwargs)
self.embed_dim = embed_dim
def encode(self, x):
h = self.encoder(x)
h = self.quant_conv(h)
return h
def decode(self, h, force_not_... | class VQModelInterface(VQModel):
def __init__(self, embed_dim, *args, **kwargs):
super().__init__(*args, embed_dim=embed_dim, **kwargs)
self.embed_dim = embed_dim
def encode(self, x):
h = self.encoder(x)
h = self.quant_conv(h)
return h
def decode(self, h, force_not_... | # also go through quantization layer
if not force_not_quantize:
quant, emb_loss, info = self.quantize(h)
else:
quant = h
quant = self.post_quant_conv(quant)
dec = self.decoder(quant)
return dec
| # also go through quantization layer
if not force_not_quantize:
quant, emb_loss, info = self.quantize(h)
else:
quant = h
quant = self.post_quant_conv(quant)
dec = self.decoder(quant)
return dec
| 26 | 128 | 85 | 213 | # The content of this file comes from the ldm/models/autoencoder.py file of the compvis/stable-diffusion repo
# The VQModel & VQModelInterface were subsequently removed from ldm/models/autoencoder.py when we moved to the stability-ai/stablediffusion repo
# As the LDSR upscaler relies on VQModel & VQModelInterface, the ... | # The content of this file comes from the ldm/models/autoencoder.py file of the compvis/stable-diffusion repo
# The VQModel & VQModelInterface were subsequently removed from ldm/models/autoencoder.py when we moved to the stability-ai/stablediffusion repo
# As the LDSR upscaler relies on VQModel & VQModelInterface, the ... |
125 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/LDSR/sd_hijack_ddpm_v1.py | 1395,1396 | 1388,1417 | forward | DiffusionWrapperV1 | 1396,1417 | 1396,1417 | class DiffusionWrapperV1(pl.LightningModule):
def __init__(self, diff_model_config, conditioning_key):
super().__init__()
self.diffusion_model = instantiate_from_config(diff_model_config)
self.conditioning_key = conditioning_key
assert self.conditioning_key in [None, 'concat', 'cross... | class DiffusionWrapperV1(pl.LightningModule):
def __init__(self, diff_model_config, conditioning_key):
super().__init__()
self.diffusion_model = instantiate_from_config(diff_model_config)
self.conditioning_key = conditioning_key
assert self.conditioning_key in [None, 'concat', 'cross... | if self.conditioning_key is None:
out = self.diffusion_model(x, t)
elif self.conditioning_key == 'concat':
xc = torch.cat([x] + c_concat, dim=1)
out = self.diffusion_model(xc, t)
elif self.conditioning_key == 'crossattn':
cc = torch.cat(c_crossattn... | if self.conditioning_key is None:
out = self.diffusion_model(x, t)
elif self.conditioning_key == 'concat':
xc = torch.cat([x] + c_concat, dim=1)
out = self.diffusion_model(xc, t)
elif self.conditioning_key == 'crossattn':
cc = torch.cat(c_crossattn... | 71 | 142 | 285 | 427 | # This script is copied from the compvis/stable-diffusion repo (aka the SD V1 repo)
# Original filename: ldm/models/diffusion/ddpm.py
# The purpose to reinstate the old DDPM logic which works with VQ, whereas the V2 one doesn't
# Some models such as LDSR require VQ to work correctly
# The classes are suffixed with "V1"... | # This script is copied from the compvis/stable-diffusion repo (aka the SD V1 repo)
# Original filename: ldm/models/diffusion/ddpm.py
# The purpose to reinstate the old DDPM logic which works with VQ, whereas the V2 one doesn't
# Some models such as LDSR require VQ to work correctly
# The classes are suffixed with "V1"... |
127 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/LDSR/sd_hijack_ddpm_v1.py | 1423,1424 | 1417,1440 | log_images | Layout2ImgDiffusionV1 | 1424,1440 | 1424,1440 | class Layout2ImgDiffusionV1(LatentDiffusionV1):
# TODO: move all layout-specific hacks to this class
def __init__(self, cond_stage_key, *args, **kwargs):
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
super().__init__(*args, cond_sta... | class Layout2ImgDiffusionV1(LatentDiffusionV1):
# TODO: move all layout-specific hacks to this class
def __init__(self, cond_stage_key, *args, **kwargs):
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
super().__init__(*args, cond_sta... | logs = super().log_images(*args, batch=batch, N=N, **kwargs)
key = 'train' if self.training else 'validation'
dset = self.trainer.datamodule.datasets[key]
mapper = dset.conditional_builders[self.cond_stage_key]
bbox_imgs = []
map_fn = lambda catno: dset.get_textual_labe... | logs = super().log_images(*args, batch=batch, N=N, **kwargs)
key = 'train' if self.training else 'validation'
dset = self.trainer.datamodule.datasets[key]
mapper = dset.conditional_builders[self.cond_stage_key]
bbox_imgs = []
map_fn = lambda catno: dset.get_textual_labe... | 47 | 149 | 257 | 406 | # This script is copied from the compvis/stable-diffusion repo (aka the SD V1 repo)
# Original filename: ldm/models/diffusion/ddpm.py
# The purpose to reinstate the old DDPM logic which works with VQ, whereas the V2 one doesn't
# Some models such as LDSR require VQ to work correctly
# The classes are suffixed with "V1"... | # This script is copied from the compvis/stable-diffusion repo (aka the SD V1 repo)
# Original filename: ldm/models/diffusion/ddpm.py
# The purpose to reinstate the old DDPM logic which works with VQ, whereas the V2 one doesn't
# Some models such as LDSR require VQ to work correctly
# The classes are suffixed with "V1"... |
128 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/LDSR/vqvae_quantize.py | 89,90 | 30,148 | forward | VectorQuantizer2 | 90,132 | 90,132 | class VectorQuantizer2(nn.Module):
"""
Improved version over VectorQuantizer, can be used as a drop-in replacement. Mostly
avoids costly matrix multiplications and allows for post-hoc remapping of indices.
"""
# NOTE: due to a bug the beta term was applied to the wrong term. for
# backwards com... | class VectorQuantizer2(nn.Module):
"""
Improved version over VectorQuantizer, can be used as a drop-in replacement. Mostly
avoids costly matrix multiplications and allows for post-hoc remapping of indices.
"""
# NOTE: due to a bug the beta term was applied to the wrong term. for
# backwards com... | assert temp is None or temp == 1.0, "Only for interface compatible with Gumbel"
assert rescale_logits is False, "Only for interface compatible with Gumbel"
assert return_logits is False, "Only for interface compatible with Gumbel"
# reshape z -> (batch, height, width, channel) and flatte... | assert temp is None or temp == 1.0, "Only for interface compatible with Gumbel"
assert rescale_logits is False, "Only for interface compatible with Gumbel"
assert return_logits is False, "Only for interface compatible with Gumbel"
# reshape z -> (batch, height, width, channel) and flatte... | 224 | 1,038 | 737 | 1,775 | # Vendored from https://raw.githubusercontent.com/CompVis/taming-transformers/24268930bf1dce879235a7fddd0b2355b84d7ea6/taming/modules/vqvae/quantize.py,
# where the license is as follows:
#
# Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer
#
# Permission is hereby granted, free of charge, to any pers... | # Vendored from https://raw.githubusercontent.com/CompVis/taming-transformers/24268930bf1dce879235a7fddd0b2355b84d7ea6/taming/modules/vqvae/quantize.py,
# where the license is as follows:
#
# Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer
#
# Permission is hereby granted, free of charge, to any pers... |
129 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/extra_networks_lora.py | 12,13 | 5,68 | activate | ExtraNetworkLora | 13,63 | 13,63 | class ExtraNetworkLora(extra_networks.ExtraNetwork):
def __init__(self):
super().__init__('lora')
self.errors = {}
"""mapping of network names to the number of errors the network had during operation"""
def activate(self, p, params_list):
FILL_FUNC_BODY def deactivate(self, p):
... | class ExtraNetworkLora(extra_networks.ExtraNetwork):
def __init__(self):
super().__init__('lora')
self.errors = {}
"""mapping of network names to the number of errors the network had during operation"""
def activate(self, p, params_list):
FILL_FUNC_BODY def deactivate(self, p):
... | additional = shared.opts.sd_lora
self.errors.clear()
if additional != "None" and additional in networks.available_networks and not any(x for x in params_list if x.items[0] == additional):
p.all_prompts = [x + f"<lora:{additional}:{shared.opts.extra_networks_default_multiplier}>" fo... | additional = shared.opts.sd_lora
self.errors.clear()
if additional != "None" and additional in networks.available_networks and not any(x for x in params_list if x.items[0] == additional):
p.all_prompts = [x + f"<lora:{additional}:{shared.opts.extra_networks_default_multiplier}>" fo... | 141 | 149 | 689 | 838 | from modules import extra_networks, shared
import networks
class ExtraNetworkLora(extra_networks.ExtraNetwork):
def __init__(self):
super().__init__('lora')
self.errors = {}
"""mapping of network names to the number of errors the network had during operation"""
def activate(self, p, ... | from modules import extra_networks, shared
import networks
class ExtraNetworkLora(extra_networks.ExtraNetwork):
def __init__(self):
super().__init__('lora')
self.errors = {}
"""mapping of network names to the number of errors the network had during operation"""
def activate(self, p, ... |
130 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/lora_logger.py | 16,17 | 6,24 | format | ColoredFormatter | 17,24 | 17,24 | class ColoredFormatter(logging.Formatter):
COLORS = {
"DEBUG": "\033[0;36m", # CYAN
"INFO": "\033[0;32m", # GREEN
"WARNING": "\033[0;33m", # YELLOW
"ERROR": "\033[0;31m", # RED
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
"RESET": "\033[0m", # RESET COLOR
}
... | class ColoredFormatter(logging.Formatter):
COLORS = {
"DEBUG": "\033[0;36m", # CYAN
"INFO": "\033[0;32m", # GREEN
"WARNING": "\033[0;33m", # YELLOW
"ERROR": "\033[0;31m", # RED
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
"RESET": "\033[0m", # RESET COLOR
}
... | colored_record = copy.copy(record)
levelname = colored_record.levelname
seq = self.COLORS.get(levelname, self.COLORS["RESET"])
colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
return super().format(colored_record)
| colored_record = copy.copy(record)
levelname = colored_record.levelname
seq = self.COLORS.get(levelname, self.COLORS["RESET"])
colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
return super().format(colored_record)
| 15 | 172 | 94 | 266 | import sys
import copy
import logging
class ColoredFormatter(logging.Formatter):
COLORS = {
"DEBUG": "\033[0;36m", # CYAN
"INFO": "\033[0;32m", # GREEN
"WARNING": "\033[0;33m", # YELLOW
"ERROR": "\033[0;31m", # RED
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
"R... | import sys
import copy
import logging
class ColoredFormatter(logging.Formatter):
COLORS = {
"DEBUG": "\033[0;36m", # CYAN
"INFO": "\033[0;32m", # GREEN
"WARNING": "\033[0;33m", # YELLOW
"ERROR": "\033[0;31m", # RED
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
"R... |
131 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/lora_patches.py | 20,21 | 7,32 | undo | LoraPatches | 21,32 | 21,32 | class LoraPatches:
def __init__(self):
self.Linear_forward = patches.patch(__name__, torch.nn.Linear, 'forward', networks.network_Linear_forward)
self.Linear_load_state_dict = patches.patch(__name__, torch.nn.Linear, '_load_from_state_dict', networks.network_Linear_load_state_dict)
self.Conv... | class LoraPatches:
def __init__(self):
self.Linear_forward = patches.patch(__name__, torch.nn.Linear, 'forward', networks.network_Linear_forward)
self.Linear_load_state_dict = patches.patch(__name__, torch.nn.Linear, '_load_from_state_dict', networks.network_Linear_load_state_dict)
self.Conv... | self.Linear_forward = patches.undo(__name__, torch.nn.Linear, 'forward')
self.Linear_load_state_dict = patches.undo(__name__, torch.nn.Linear, '_load_from_state_dict')
self.Conv2d_forward = patches.undo(__name__, torch.nn.Conv2d, 'forward')
self.Conv2d_load_state_dict = patches.undo(__na... | self.Linear_forward = patches.undo(__name__, torch.nn.Linear, 'forward')
self.Linear_load_state_dict = patches.undo(__name__, torch.nn.Linear, '_load_from_state_dict')
self.Conv2d_forward = patches.undo(__name__, torch.nn.Conv2d, 'forward')
self.Conv2d_load_state_dict = patches.undo(__na... | 50 | 482 | 344 | 826 | import torch
import networks
from modules import patches
class LoraPatches:
def __init__(self):
self.Linear_forward = patches.patch(__name__, torch.nn.Linear, 'forward', networks.network_Linear_forward)
self.Linear_load_state_dict = patches.patch(__name__, torch.nn.Linear, '_load_from_state_dict'... | import torch
import networks
from modules import patches
class LoraPatches:
def __init__(self):
self.Linear_forward = patches.patch(__name__, torch.nn.Linear, 'forward', networks.network_Linear_forward)
self.Linear_load_state_dict = patches.patch(__name__, torch.nn.Linear, '_load_from_state_dict'... |
132 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/lyco_helpers.py | 4,5 | 1,69 | make_weight_cp | 5,9 | 5,9 | import torch
def make_weight_cp(t, wa, wb):
FILL_FUNC_BODYdef rebuild_conventional(up, down, shape, dyn_dim=None):
up = up.reshape(up.size(0), -1)
down = down.reshape(down.size(0), -1)
if dyn_dim is not None:
up = up[:, :dyn_dim]
down = down[:dyn_dim, :]
return (up @ down).reshape(shap... | import torch
def make_weight_cp(t, wa, wb):
FILL_FUNC_BODYdef rebuild_conventional(up, down, shape, dyn_dim=None):
up = up.reshape(up.size(0), -1)
down = down.reshape(down.size(0), -1)
if dyn_dim is not None:
up = up[:, :dyn_dim]
down = down[:dyn_dim, :]
return (up @ down).reshape(shap... | temp = torch.einsum('i j k l, j r -> i r k l', t, wb)
return torch.einsum('i j k l, i r -> r j k l', temp, wa)
| temp = torch.einsum('i j k l, j r -> i r k l', t, wb)
return torch.einsum('i j k l, i r -> r j k l', temp, wa)
| 29 | 967 | 64 | 1,031 | import torch
def make_weight_cp(t, wa, wb):
FILL_FUNC_BODYdef rebuild_conventional(up, down, shape, dyn_dim=None):
up = up.reshape(up.size(0), -1)
down = down.reshape(down.size(0), -1)
if dyn_dim is not None:
up = up[:, :dyn_dim]
down = down[:dyn_dim, :]
return (up @ down).reshape(shap... | import torch
def make_weight_cp(t, wa, wb):
FILL_FUNC_BODYdef rebuild_conventional(up, down, shape, dyn_dim=None):
up = up.reshape(up.size(0), -1)
down = down.reshape(down.size(0), -1)
if dyn_dim is not None:
up = up[:, :dyn_dim]
down = down[:dyn_dim, :]
return (up @ down).reshape(shap... | |
133 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network.py | 106,107 | 105,110 | create_module | ModuleType | 107,110 | 107,110 | class ModuleType:
def create_module(self, net: Network, weights: NetworkWeights) -> Network | None:
FILL_FUNC_BODY | class ModuleType:
def create_module(self, net: Network, weights: NetworkWeights) -> Network | None:
FILL_FUNC_BODY | return None
| return None
| 2 | 40 | 9 | 49 | from __future__ import annotations
import os
from collections import namedtuple
import enum
import torch.nn as nn
import torch.nn.functional as F
from modules import sd_models, cache, errors, hashes, shared
NetworkWeights = namedtuple('NetworkWeights', ['network_key', 'sd_key', 'w', 'sd_module'])
metadata_tags_orde... | from __future__ import annotations
import os
from collections import namedtuple
import enum
import torch.nn as nn
import torch.nn.functional as F
from modules import sd_models, cache, errors, hashes, shared
NetworkWeights = namedtuple('NetworkWeights', ['network_key', 'sd_key', 'w', 'sd_module'])
metadata_tags_orde... |
134 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network.py | 171,172 | 110,223 | apply_weight_decompose | NetworkModule | 172,192 | 172,192 | class NetworkModule:
def __init__(self, net: Network, weights: NetworkWeights):
self.network = net
self.network_key = weights.network_key
self.sd_key = weights.sd_key
self.sd_module = weights.sd_module
if hasattr(self.sd_module, 'weight'):
self.shape = self.sd_mo... | class NetworkModule:
def __init__(self, net: Network, weights: NetworkWeights):
self.network = net
self.network_key = weights.network_key
self.sd_key = weights.sd_key
self.sd_module = weights.sd_module
if hasattr(self.sd_module, 'weight'):
self.shape = self.sd_mo... | # Match the device/dtype
orig_weight = orig_weight.to(updown.dtype)
dora_scale = self.dora_scale.to(device=orig_weight.device, dtype=updown.dtype)
updown = updown.to(orig_weight.device)
merged_scale1 = updown + orig_weight
merged_scale1_norm = (
merged_scale1... | # Match the device/dtype
orig_weight = orig_weight.to(updown.dtype)
dora_scale = self.dora_scale.to(device=orig_weight.device, dtype=updown.dtype)
updown = updown.to(orig_weight.device)
merged_scale1 = updown + orig_weight
merged_scale1_norm = (
merged_scale1... | 51 | 1,084 | 270 | 1,354 | from __future__ import annotations
import os
from collections import namedtuple
import enum
import torch.nn as nn
import torch.nn.functional as F
from modules import sd_models, cache, errors, hashes, shared
NetworkWeights = namedtuple('NetworkWeights', ['network_key', 'sd_key', 'w', 'sd_module'])
metadata_tags_orde... | from __future__ import annotations
import os
from collections import namedtuple
import enum
import torch.nn as nn
import torch.nn.functional as F
from modules import sd_models, cache, errors, hashes, shared
NetworkWeights = namedtuple('NetworkWeights', ['network_key', 'sd_key', 'w', 'sd_module'])
metadata_tags_orde... |
135 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network.py | 78,79 | 23,90 | read_hash | NetworkOnDisk | 79,82 | 79,82 | class NetworkOnDisk:
def __init__(self, name, filename):
self.name = name
self.filename = filename
self.metadata = {}
self.is_safetensors = os.path.splitext(filename)[1].lower() == ".safetensors"
def read_metadata():
metadata = sd_models.read_metadata_from_safete... | class NetworkOnDisk:
def __init__(self, name, filename):
self.name = name
self.filename = filename
self.metadata = {}
self.is_safetensors = os.path.splitext(filename)[1].lower() == ".safetensors"
def read_metadata():
metadata = sd_models.read_metadata_from_safete... | if not self.hash:
self.set_hash(hashes.sha256(self.filename, "lora/" + self.name, use_addnet_hash=self.is_safetensors) or '')
| if not self.hash:
self.set_hash(hashes.sha256(self.filename, "lora/" + self.name, use_addnet_hash=self.is_safetensors) or '')
| 10 | 658 | 61 | 719 | from __future__ import annotations
import os
from collections import namedtuple
import enum
import torch.nn as nn
import torch.nn.functional as F
from modules import sd_models, cache, errors, hashes, shared
NetworkWeights = namedtuple('NetworkWeights', ['network_key', 'sd_key', 'w', 'sd_module'])
metadata_tags_orde... | from __future__ import annotations
import os
from collections import namedtuple
import enum
import torch.nn as nn
import torch.nn.functional as F
from modules import sd_models, cache, errors, hashes, shared
NetworkWeights = namedtuple('NetworkWeights', ['network_key', 'sd_key', 'w', 'sd_module'])
metadata_tags_orde... |
136 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_full.py | 5,6 | 4,12 | create_module | ModuleTypeFull | 6,12 | 6,12 | class ModuleTypeFull(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | class ModuleTypeFull(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | if all(x in weights.w for x in ["diff"]):
return NetworkModuleFull(net, weights)
return None
| if all(x in weights.w for x in ["diff"]):
return NetworkModuleFull(net, weights)
return None
| 13 | 44 | 41 | 85 | import network
class ModuleTypeFull(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleFull(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weigh... | import network
class ModuleTypeFull(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleFull(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weigh... |
137 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_full.py | 19,20 | 12,28 | calc_updown | NetworkModuleFull | 20,28 | 20,28 | class NetworkModuleFull(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.weight = weights.w.get("diff")
self.ex_bias = weights.w.get("diff_b")
def calc_updown(self, orig_weight):
FILL_FUNC_BODY | class NetworkModuleFull(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.weight = weights.w.get("diff")
self.ex_bias = weights.w.get("diff_b")
def calc_updown(self, orig_weight):
FILL_FUNC_BODY | output_shape = self.weight.shape
updown = self.weight.to(orig_weight.device)
if self.ex_bias is not None:
ex_bias = self.ex_bias.to(orig_weight.device)
else:
ex_bias = None
return self.finalize_updown(updown, orig_weight, output_shape, ex_bias)
| output_shape = self.weight.shape
updown = self.weight.to(orig_weight.device)
if self.ex_bias is not None:
ex_bias = self.ex_bias.to(orig_weight.device)
else:
ex_bias = None
return self.finalize_updown(updown, orig_weight, output_shape, ex_bias)
| 23 | 104 | 111 | 215 | import network
class ModuleTypeFull(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["diff"]):
return NetworkModuleFull(net, weights)
return None
class NetworkModuleFull(network.NetworkModule):
d... | import network
class ModuleTypeFull(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["diff"]):
return NetworkModuleFull(net, weights)
return None
class NetworkModuleFull(network.NetworkModule):
d... |
138 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_glora.py | 5,6 | 4,12 | create_module | ModuleTypeGLora | 6,12 | 6,12 | class ModuleTypeGLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | class ModuleTypeGLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | if all(x in weights.w for x in ["a1.weight", "a2.weight", "alpha", "b1.weight", "b2.weight"]):
return NetworkModuleGLora(net, weights)
return None
# adapted from https://github.com/KohakuBlueleaf/LyCORIS
| if all(x in weights.w for x in ["a1.weight", "a2.weight", "alpha", "b1.weight", "b2.weight"]):
return NetworkModuleGLora(net, weights)
return None
# adapted from https://github.com/KohakuBlueleaf/LyCORIS
| 21 | 45 | 87 | 132 |
import network
class ModuleTypeGLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleGLora(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, wei... |
import network
class ModuleTypeGLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleGLora(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, wei... |
139 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_glora.py | 24,25 | 12,34 | calc_updown | NetworkModuleGLora | 25,34 | 25,34 | class NetworkModuleGLora(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
if hasattr(self.sd_module, 'weight'):
self.shape = self.sd_module.weight.shape
self.w1a = weights.w["a1.weight"]
s... | class NetworkModuleGLora(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
if hasattr(self.sd_module, 'weight'):
self.shape = self.sd_module.weight.shape
self.w1a = weights.w["a1.weight"]
s... | w1a = self.w1a.to(orig_weight.device)
w1b = self.w1b.to(orig_weight.device)
w2a = self.w2a.to(orig_weight.device)
w2b = self.w2b.to(orig_weight.device)
output_shape = [w1a.size(0), w1b.size(1)]
updown = ((w2b @ w1b) + ((orig_weight.to(dtype = w1a.dtype) @ w2a) @ w1a))
... | w1a = self.w1a.to(orig_weight.device)
w1b = self.w1b.to(orig_weight.device)
w2a = self.w2a.to(orig_weight.device)
w2b = self.w2b.to(orig_weight.device)
output_shape = [w1a.size(0), w1b.size(1)]
updown = ((w2b @ w1b) + ((orig_weight.to(dtype = w1a.dtype) @ w2a) @ w1a))
... | 33 | 172 | 178 | 350 |
import network
class ModuleTypeGLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["a1.weight", "a2.weight", "alpha", "b1.weight", "b2.weight"]):
return NetworkModuleGLora(net, weights)
return None
... |
import network
class ModuleTypeGLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["a1.weight", "a2.weight", "alpha", "b1.weight", "b2.weight"]):
return NetworkModuleGLora(net, weights)
return None
... |
140 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_hada.py | 6,7 | 5,13 | create_module | ModuleTypeHada | 7,13 | 7,13 | class ModuleTypeHada(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | class ModuleTypeHada(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | if all(x in weights.w for x in ["hada_w1_a", "hada_w1_b", "hada_w2_a", "hada_w2_b"]):
return NetworkModuleHada(net, weights)
return None
| if all(x in weights.w for x in ["hada_w1_a", "hada_w1_b", "hada_w2_a", "hada_w2_b"]):
return NetworkModuleHada(net, weights)
return None
| 16 | 45 | 75 | 120 | import lyco_helpers
import network
class ModuleTypeHada(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleHada(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super()... | import lyco_helpers
import network
class ModuleTypeHada(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleHada(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super()... |
141 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_hada.py | 29,30 | 13,56 | calc_updown | NetworkModuleHada | 30,56 | 30,56 | class NetworkModuleHada(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
if hasattr(self.sd_module, 'weight'):
self.shape = self.sd_module.weight.shape
self.w1a = weights.w["hada_w1_a"]
se... | class NetworkModuleHada(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
if hasattr(self.sd_module, 'weight'):
self.shape = self.sd_module.weight.shape
self.w1a = weights.w["hada_w1_a"]
se... | w1a = self.w1a.to(orig_weight.device)
w1b = self.w1b.to(orig_weight.device)
w2a = self.w2a.to(orig_weight.device)
w2b = self.w2b.to(orig_weight.device)
output_shape = [w1a.size(0), w1b.size(1)]
if self.t1 is not None:
output_shape = [w1a.size(1), w1b.size(1)... | w1a = self.w1a.to(orig_weight.device)
w1b = self.w1b.to(orig_weight.device)
w2a = self.w2a.to(orig_weight.device)
w2b = self.w2b.to(orig_weight.device)
output_shape = [w1a.size(0), w1b.size(1)]
if self.t1 is not None:
output_shape = [w1a.size(1), w1b.size(1)... | 77 | 239 | 418 | 657 | import lyco_helpers
import network
class ModuleTypeHada(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["hada_w1_a", "hada_w1_b", "hada_w2_a", "hada_w2_b"]):
return NetworkModuleHada(net, weights)
ret... | import lyco_helpers
import network
class ModuleTypeHada(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["hada_w1_a", "hada_w1_b", "hada_w2_a", "hada_w2_b"]):
return NetworkModuleHada(net, weights)
ret... |
142 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_ia3.py | 5,6 | 4,12 | create_module | ModuleTypeIa3 | 6,12 | 6,12 | class ModuleTypeIa3(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | class ModuleTypeIa3(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | if all(x in weights.w for x in ["weight"]):
return NetworkModuleIa3(net, weights)
return None
| if all(x in weights.w for x in ["weight"]):
return NetworkModuleIa3(net, weights)
return None
| 13 | 46 | 43 | 89 | import network
class ModuleTypeIa3(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleIa3(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights... | import network
class ModuleTypeIa3(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleIa3(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights... |
143 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_ia3.py | 19,20 | 12,31 | calc_updown | NetworkModuleIa3 | 20,31 | 20,31 | class NetworkModuleIa3(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.w = weights.w["weight"]
self.on_input = weights.w["on_input"].item()
def calc_updown(self, orig_weight):
FILL_FUNC_BODY | class NetworkModuleIa3(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.w = weights.w["weight"]
self.on_input = weights.w["on_input"].item()
def calc_updown(self, orig_weight):
FILL_FUNC_BODY | w = self.w.to(orig_weight.device)
output_shape = [w.size(0), orig_weight.size(1)]
if self.on_input:
output_shape.reverse()
else:
w = w.reshape(-1, 1)
updown = orig_weight * w
return self.finalize_updown(updown, orig_weight, output_shape)
| w = self.w.to(orig_weight.device)
output_shape = [w.size(0), orig_weight.size(1)]
if self.on_input:
output_shape.reverse()
else:
w = w.reshape(-1, 1)
updown = orig_weight * w
return self.finalize_updown(updown, orig_weight, output_shape)
| 24 | 103 | 119 | 222 | import network
class ModuleTypeIa3(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["weight"]):
return NetworkModuleIa3(net, weights)
return None
class NetworkModuleIa3(network.NetworkModule):
de... | import network
class ModuleTypeIa3(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["weight"]):
return NetworkModuleIa3(net, weights)
return None
class NetworkModuleIa3(network.NetworkModule):
de... |
144 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_lokr.py | 17,18 | 1,65 | make_kron | 18,24 | 18,24 | import torch
import lyco_helpers
import network
class ModuleTypeLokr(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
has_2 = "lokr_w2" in weights.w or ("l... | import torch
import lyco_helpers
import network
class ModuleTypeLokr(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
has_2 = "lokr_w2" in weights.w or ("l... | if len(w2.shape) == 4:
w1 = w1.unsqueeze(2).unsqueeze(2)
w2 = w2.contiguous()
return torch.kron(w1, w2).reshape(orig_shape)
| if len(w2.shape) == 4:
w1 = w1.unsqueeze(2).unsqueeze(2)
w2 = w2.contiguous()
return torch.kron(w1, w2).reshape(orig_shape)
| 13 | 856 | 77 | 933 | import torch
import lyco_helpers
import network
class ModuleTypeLokr(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
has_2 = "lokr_w2" in weights.w or ("l... | import torch
import lyco_helpers
import network
class ModuleTypeLokr(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
has_2 = "lokr_w2" in weights.w or ("l... | |
145 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_lokr.py | 8,9 | 7,17 | create_module | ModuleTypeLokr | 9,17 | 9,17 | class ModuleTypeLokr(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | class ModuleTypeLokr(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
has_2 = "lokr_w2" in weights.w or ("lokr_w2_a" in weights.w and "lokr_w2_b" in weights.w)
if has_1 and has_2:
return NetworkModuleLokr(net, weights)
return None
| has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
has_2 = "lokr_w2" in weights.w or ("lokr_w2_a" in weights.w and "lokr_w2_b" in weights.w)
if has_1 and has_2:
return NetworkModuleLokr(net, weights)
return None
| 35 | 46 | 137 | 183 | import torch
import lyco_helpers
import network
class ModuleTypeLokr(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYdef make_kron(orig_shape, w1, w2):
if len(w2.shape) == 4:
w1 = w1.unsqueeze(2).unsqueeze(2)
w2 = w2.contiguous()
... | import torch
import lyco_helpers
import network
class ModuleTypeLokr(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYdef make_kron(orig_shape, w1, w2):
if len(w2.shape) == 4:
w1 = w1.unsqueeze(2).unsqueeze(2)
w2 = w2.contiguous()
... |
146 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_lokr.py | 38,39 | 24,65 | calc_updown | NetworkModuleLokr | 39,65 | 39,65 | class NetworkModuleLokr(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.w1 = weights.w.get("lokr_w1")
self.w1a = weights.w.get("lokr_w1_a")
self.w1b = weights.w.get("lokr_w1_b")
self.dim ... | class NetworkModuleLokr(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.w1 = weights.w.get("lokr_w1")
self.w1a = weights.w.get("lokr_w1_a")
self.w1b = weights.w.get("lokr_w1_b")
self.dim ... | if self.w1 is not None:
w1 = self.w1.to(orig_weight.device)
else:
w1a = self.w1a.to(orig_weight.device)
w1b = self.w1b.to(orig_weight.device)
w1 = w1a @ w1b
if self.w2 is not None:
w2 = self.w2.to(orig_weight.device)
elif self.... | if self.w1 is not None:
w1 = self.w1.to(orig_weight.device)
else:
w1a = self.w1a.to(orig_weight.device)
w1b = self.w1b.to(orig_weight.device)
w1 = w1a @ w1b
if self.w2 is not None:
w2 = self.w2.to(orig_weight.device)
elif self.... | 82 | 283 | 400 | 683 | import torch
import lyco_helpers
import network
class ModuleTypeLokr(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
has_2 = "lokr_w2" in weights.w or ("l... | import torch
import lyco_helpers
import network
class ModuleTypeLokr(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
has_2 = "lokr_w2" in weights.w or ("l... |
147 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_lora.py | 9,10 | 8,16 | create_module | ModuleTypeLora | 10,16 | 10,16 | class ModuleTypeLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | class ModuleTypeLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | if all(x in weights.w for x in ["lora_up.weight", "lora_down.weight"]):
return NetworkModuleLora(net, weights)
return None
| if all(x in weights.w for x in ["lora_up.weight", "lora_down.weight"]):
return NetworkModuleLora(net, weights)
return None
| 14 | 45 | 55 | 100 | import torch
import lyco_helpers
import network
from modules import devices
class ModuleTypeLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleLora(network.NetworkModule):
def __init__(self, net: network.Network, weights... | import torch
import lyco_helpers
import network
from modules import devices
class ModuleTypeLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleLora(network.NetworkModule):
def __init__(self, net: network.Network, weights... |
148 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_lora.py | 26,27 | 16,87 | create_module | NetworkModuleLora | 27,63 | 27,63 | class NetworkModuleLora(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.up_model = self.create_module(weights.w, "lora_up.weight")
self.down_model = self.create_module(weights.w, "lora_down.weight")
... | class NetworkModuleLora(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.up_model = self.create_module(weights.w, "lora_up.weight")
self.down_model = self.create_module(weights.w, "lora_down.weight")
... | weight = weights.get(key)
if weight is None and none_ok:
return None
is_linear = type(self.sd_module) in [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear, torch.nn.MultiheadAttention]
is_conv = type(self.sd_module) in [torch.nn.Conv2d]
if i... | weight = weights.get(key)
if weight is None and none_ok:
return None
is_linear = type(self.sd_module) in [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear, torch.nn.MultiheadAttention]
is_conv = type(self.sd_module) in [torch.nn.Conv2d]
if i... | 136 | 505 | 646 | 1,151 | import torch
import lyco_helpers
import network
from modules import devices
class ModuleTypeLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["lora_up.weight", "lora_down.weight"]):
return NetworkModuleLor... | import torch
import lyco_helpers
import network
from modules import devices
class ModuleTypeLora(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["lora_up.weight", "lora_down.weight"]):
return NetworkModuleLor... |
149 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_norm.py | 5,6 | 4,12 | create_module | ModuleTypeNorm | 6,12 | 6,12 | class ModuleTypeNorm(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | class ModuleTypeNorm(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | if all(x in weights.w for x in ["w_norm", "b_norm"]):
return NetworkModuleNorm(net, weights)
return None
| if all(x in weights.w for x in ["w_norm", "b_norm"]):
return NetworkModuleNorm(net, weights)
return None
| 14 | 44 | 48 | 92 | import network
class ModuleTypeNorm(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleNorm(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weigh... | import network
class ModuleTypeNorm(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleNorm(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weigh... |
150 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_norm.py | 19,20 | 12,29 | calc_updown | NetworkModuleNorm | 20,29 | 20,29 | class NetworkModuleNorm(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.w_norm = weights.w.get("w_norm")
self.b_norm = weights.w.get("b_norm")
def calc_updown(self, orig_weight):
FILL_FUNC_BODY | class NetworkModuleNorm(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.w_norm = weights.w.get("w_norm")
self.b_norm = weights.w.get("b_norm")
def calc_updown(self, orig_weight):
FILL_FUNC_BODY | output_shape = self.w_norm.shape
updown = self.w_norm.to(orig_weight.device)
if self.b_norm is not None:
ex_bias = self.b_norm.to(orig_weight.device)
else:
ex_bias = None
return self.finalize_updown(updown, orig_weight, output_shape, ex_bias)
| output_shape = self.w_norm.shape
updown = self.w_norm.to(orig_weight.device)
if self.b_norm is not None:
ex_bias = self.b_norm.to(orig_weight.device)
else:
ex_bias = None
return self.finalize_updown(updown, orig_weight, output_shape, ex_bias)
| 23 | 107 | 115 | 222 | import network
class ModuleTypeNorm(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["w_norm", "b_norm"]):
return NetworkModuleNorm(net, weights)
return None
class NetworkModuleNorm(network.NetworkMo... | import network
class ModuleTypeNorm(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["w_norm", "b_norm"]):
return NetworkModuleNorm(net, weights)
return None
class NetworkModuleNorm(network.NetworkMo... |
151 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_oft.py | 7,8 | 6,15 | create_module | ModuleTypeOFT | 8,15 | 8,15 | class ModuleTypeOFT(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | class ModuleTypeOFT(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODY | if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
return NetworkModuleOFT(net, weights)
return None
# Supports both kohya-ss' implementation of COFT https://github.com/kohya-ss/sd-scripts/blob/main/networks/oft.py
# and KohakuBlueleaf's implement... | if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
return NetworkModuleOFT(net, weights)
return None
# Supports both kohya-ss' implementation of COFT https://github.com/kohya-ss/sd-scripts/blob/main/networks/oft.py
# and KohakuBlueleaf's implement... | 36 | 45 | 157 | 202 | import torch
import network
from einops import rearrange
class ModuleTypeOFT(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleOFT(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeigh... | import torch
import network
from einops import rearrange
class ModuleTypeOFT(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
FILL_FUNC_BODYclass NetworkModuleOFT(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeigh... |
152 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/network_oft.py | 70,71 | 15,119 | calc_updown | NetworkModuleOFT | 71,119 | 71,119 | class NetworkModuleOFT(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.lin_module = None
self.org_module: list[torch.Module] = [self.sd_module]
self.scale = 1.0
self.is_R = False
... | class NetworkModuleOFT(network.NetworkModule):
def __init__(self, net: network.Network, weights: network.NetworkWeights):
super().__init__(net, weights)
self.lin_module = None
self.org_module: list[torch.Module] = [self.sd_module]
self.scale = 1.0
self.is_R = False
... | oft_blocks = self.oft_blocks.to(orig_weight.device)
eye = torch.eye(self.block_size, device=oft_blocks.device)
if not self.is_R:
block_Q = oft_blocks - oft_blocks.transpose(-1, -2) # ensure skew-symmetric orthogonal matrix
if self.constraint != 0:
norm_Q ... | oft_blocks = self.oft_blocks.to(orig_weight.device)
eye = torch.eye(self.block_size, device=oft_blocks.device)
if not self.is_R:
block_Q = oft_blocks - oft_blocks.transpose(-1, -2) # ensure skew-symmetric orthogonal matrix
if self.constraint != 0:
norm_Q ... | 261 | 788 | 828 | 1,616 | import torch
import network
from einops import rearrange
class ModuleTypeOFT(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
return NetworkModuleOFT... | import torch
import network
from einops import rearrange
class ModuleTypeOFT(network.ModuleType):
def create_module(self, net: network.Network, weights: network.NetworkWeights):
if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
return NetworkModuleOFT... |
153 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/Lora/preload.py | 6,7 | 1,9 | preload | 7,9 | 7,9 | import os
from modules import paths
from modules.paths_internal import normalized_filepath
def preload(parser):
FILL_FUNC_BODY | import os
from modules import paths
from modules.paths_internal import normalized_filepath
def preload(parser):
FILL_FUNC_BODY | parser.add_argument("--lora-dir", type=normalized_filepath, help="Path to directory with Lora networks.", default=os.path.join(paths.models_path, 'Lora'))
parser.add_argument("--lyco-dir-backcompat", type=normalized_filepath, help="Path to directory with LyCORIS networks (for backawards compatibility; can also ... | parser.add_argument("--lora-dir", type=normalized_filepath, help="Path to directory with Lora networks.", default=os.path.join(paths.models_path, 'Lora'))
parser.add_argument("--lyco-dir-backcompat", type=normalized_filepath, help="Path to directory with LyCORIS networks (for backawards compatibility; can also ... | 27 | 39 | 128 | 167 | import os
from modules import paths
from modules.paths_internal import normalized_filepath
def preload(parser):
FILL_FUNC_BODY | import os
from modules import paths
from modules.paths_internal import normalized_filepath
def preload(parser):
FILL_FUNC_BODY | |
154 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/ScuNET/preload.py | 5,6 | 1,7 | preload | 6,7 | 6,7 | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | parser.add_argument("--scunet-models-path", type=str, help="Path to directory with ScuNET model file(s).", default=os.path.join(paths.models_path, 'ScuNET'))
| parser.add_argument("--scunet-models-path", type=str, help="Path to directory with ScuNET model file(s).", default=os.path.join(paths.models_path, 'ScuNET'))
| 11 | 27 | 57 | 84 | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | |
155 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/ScuNET/scripts/scunet_model.py | 67,68 | 1,75 | on_ui_settings | 68,74 | 68,74 | import sys
import PIL.Image
import modules.upscaler
from modules import devices, errors, modelloader, script_callbacks, shared, upscaler_utils
class UpscalerScuNET(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "ScuNET"
self.model_name = "ScuNET GAN"
self.model_name... | import sys
import PIL.Image
import modules.upscaler
from modules import devices, errors, modelloader, script_callbacks, shared, upscaler_utils
class UpscalerScuNET(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "ScuNET"
self.model_name = "ScuNET GAN"
self.model_name... | import gradio as gr
shared.opts.add_option("SCUNET_tile", shared.OptionInfo(256, "Tile size for SCUNET upscalers.", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")).info("0 = no tiling"))
shared.opts.add_option("SCUNET_tile_overlap", shared.OptionInfo(8, "Tile over... | import gradio as gr
shared.opts.add_option("SCUNET_tile", shared.OptionInfo(256, "Tile size for SCUNET upscalers.", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")).info("0 = no tiling"))
shared.opts.add_option("SCUNET_tile_overlap", shared.OptionInfo(8, "Tile over... | 43 | 877 | 187 | 1,064 | import sys
import PIL.Image
import modules.upscaler
from modules import devices, errors, modelloader, script_callbacks, shared, upscaler_utils
class UpscalerScuNET(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "ScuNET"
self.model_name = "ScuNET GAN"
self.model_name... | import sys
import PIL.Image
import modules.upscaler
from modules import devices, errors, modelloader, script_callbacks, shared, upscaler_utils
class UpscalerScuNET(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "ScuNET"
self.model_name = "ScuNET GAN"
self.model_name... | |
156 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/ScuNET/scripts/scunet_model.py | 38,39 | 9,67 | do_upscale | UpscalerScuNET | 39,57 | 39,57 | class UpscalerScuNET(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "ScuNET"
self.model_name = "ScuNET GAN"
self.model_name2 = "ScuNET PSNR"
self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/scunet_color_real_gan.pth"
self.model_url2 ... | class UpscalerScuNET(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "ScuNET"
self.model_name = "ScuNET GAN"
self.model_name2 = "ScuNET PSNR"
self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/scunet_color_real_gan.pth"
self.model_url2 ... | devices.torch_gc()
try:
model = self.load_model(selected_file)
except Exception as e:
print(f"ScuNET: Unable to load model from {selected_file}: {e}", file=sys.stderr)
return img
img = upscaler_utils.upscale_2(
img,
model,
... | devices.torch_gc()
try:
model = self.load_model(selected_file)
except Exception as e:
print(f"ScuNET: Unable to load model from {selected_file}: {e}", file=sys.stderr)
return img
img = upscaler_utils.upscale_2(
img,
model,
... | 42 | 624 | 200 | 824 | import sys
import PIL.Image
import modules.upscaler
from modules import devices, errors, modelloader, script_callbacks, shared, upscaler_utils
class UpscalerScuNET(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "ScuNET"
self.model_name = "ScuNET GAN"
self.model_name... | import sys
import PIL.Image
import modules.upscaler
from modules import devices, errors, modelloader, script_callbacks, shared, upscaler_utils
class UpscalerScuNET(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "ScuNET"
self.model_name = "ScuNET GAN"
self.model_name... |
157 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/SwinIR/preload.py | 5,6 | 1,7 | preload | 6,7 | 6,7 | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | parser.add_argument("--swinir-models-path", type=str, help="Path to directory with SwinIR model file(s).", default=os.path.join(paths.models_path, 'SwinIR'))
| parser.add_argument("--swinir-models-path", type=str, help="Path to directory with SwinIR model file(s).", default=os.path.join(paths.models_path, 'SwinIR'))
| 11 | 27 | 57 | 84 | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | import os
from modules import paths
def preload(parser):
FILL_FUNC_BODY | |
158 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/SwinIR/scripts/swinir_model.py | 87,88 | 1,96 | on_ui_settings | 88,95 | 88,95 | import logging
import sys
import torch
from PIL import Image
from modules import devices, modelloader, script_callbacks, shared, upscaler_utils
from modules.upscaler import Upscaler, UpscalerData
SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-... | import logging
import sys
import torch
from PIL import Image
from modules import devices, modelloader, script_callbacks, shared, upscaler_utils
from modules.upscaler import Upscaler, UpscalerData
SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-... | import gradio as gr
shared.opts.add_option("SWIN_tile", shared.OptionInfo(192, "Tile size for all SwinIR.", gr.Slider, {"minimum": 16, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")))
shared.opts.add_option("SWIN_tile_overlap", shared.OptionInfo(8, "Tile overlap, in pixels for SwinIR. Low ... | import gradio as gr
shared.opts.add_option("SWIN_tile", shared.OptionInfo(192, "Tile size for all SwinIR.", gr.Slider, {"minimum": 16, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")))
shared.opts.add_option("SWIN_tile_overlap", shared.OptionInfo(8, "Tile overlap, in pixels for SwinIR. Low ... | 58 | 982 | 247 | 1,229 | import logging
import sys
import torch
from PIL import Image
from modules import devices, modelloader, script_callbacks, shared, upscaler_utils
from modules.upscaler import Upscaler, UpscalerData
SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-... | import logging
import sys
import torch
from PIL import Image
from modules import devices, modelloader, script_callbacks, shared, upscaler_utils
from modules.upscaler import Upscaler, UpscalerData
SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-... | |
159 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/SwinIR/scripts/swinir_model.py | 35,36 | 15,87 | do_upscale | UpscalerSwinIR | 36,60 | 36,60 | class UpscalerSwinIR(Upscaler):
def __init__(self, dirname):
self._cached_model = None # keep the model when SWIN_torch_compile is on to prevent re-compile every runs
self._cached_model_config = None # to clear '_cached_model' when changing model (v1/v2) or settings
self.name = ... | class UpscalerSwinIR(Upscaler):
def __init__(self, dirname):
self._cached_model = None # keep the model when SWIN_torch_compile is on to prevent re-compile every runs
self._cached_model_config = None # to clear '_cached_model' when changing model (v1/v2) or settings
self.name = ... | current_config = (model_file, shared.opts.SWIN_tile)
if self._cached_model_config == current_config:
model = self._cached_model
else:
try:
model = self.load_model(model_file)
except Exception as e:
print(f"Failed loading SwinIR... | current_config = (model_file, shared.opts.SWIN_tile)
if self._cached_model_config == current_config:
model = self._cached_model
else:
try:
model = self.load_model(model_file)
except Exception as e:
print(f"Failed loading SwinIR... | 48 | 581 | 252 | 833 | import logging
import sys
import torch
from PIL import Image
from modules import devices, modelloader, script_callbacks, shared, upscaler_utils
from modules.upscaler import Upscaler, UpscalerData
SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-... | import logging
import sys
import torch
from PIL import Image
from modules import devices, modelloader, script_callbacks, shared, upscaler_utils
from modules.upscaler import Upscaler, UpscalerData
SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-... |
160 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/extra-options-section/scripts/extra_options_section.py | 21,22 | 8,72 | ui | ExtraOptionsSection | 22,66 | 22,66 | class ExtraOptionsSection(scripts.Script):
section = "extra_options"
def __init__(self):
self.comps = None
self.setting_names = None
def title(self):
return "Extra options"
def show(self, is_img2img):
return scripts.AlwaysVisible
def ui(self, is_img2img):
FILL_FUN... | class ExtraOptionsSection(scripts.Script):
section = "extra_options"
def __init__(self):
self.comps = None
self.setting_names = None
def title(self):
return "Extra options"
def show(self, is_img2img):
return scripts.AlwaysVisible
def ui(self, is_img2img):
FILL_FUN... | self.comps = []
self.setting_names = []
self.infotext_fields = []
extra_options = shared.opts.extra_options_img2img if is_img2img else shared.opts.extra_options_txt2img
elem_id_tabname = "extra_options_" + ("img2img" if is_img2img else "txt2img")
mapping = {k: v for v, k... | self.comps = []
self.setting_names = []
self.infotext_fields = []
extra_options = shared.opts.extra_options_img2img if is_img2img else shared.opts.extra_options_txt2img
elem_id_tabname = "extra_options_" + ("img2img" if is_img2img else "txt2img")
mapping = {k: v for v, k... | 131 | 165 | 593 | 758 | import math
import gradio as gr
from modules import scripts, shared, ui_components, ui_settings, infotext_utils, errors
from modules.ui_components import FormColumn
class ExtraOptionsSection(scripts.Script):
section = "extra_options"
def __init__(self):
self.comps = None
self.setting_names =... | import math
import gradio as gr
from modules import scripts, shared, ui_components, ui_settings, infotext_utils, errors
from modules.ui_components import FormColumn
class ExtraOptionsSection(scripts.Script):
section = "extra_options"
def __init__(self):
self.comps = None
self.setting_names =... |
161 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/hypertile/scripts/hypertile_script.py | 81,82 | 1,110 | on_ui_settings | 82,108 | 82,108 | import hypertile
from modules import scripts, script_callbacks, shared
from scripts.hypertile_xyz import add_axis_options
class ScriptHypertile(scripts.Script):
name = "Hypertile"
def title(self):
return self.name
def show(self, is_img2img):
return scripts.AlwaysVisible
def process(... | import hypertile
from modules import scripts, script_callbacks, shared
from scripts.hypertile_xyz import add_axis_options
class ScriptHypertile(scripts.Script):
name = "Hypertile"
def title(self):
return self.name
def show(self, is_img2img):
return scripts.AlwaysVisible
def process(... | import gradio as gr
options = {
"hypertile_explanation": shared.OptionHTML("""
<a href='https://github.com/tfernd/HyperTile'>Hypertile</a> optimizes the self-attention layer within U-Net and VAE models,
resulting in a reduction in computation time ranging from 1 to 4 times. The larger the gener... | import gradio as gr
options = {
"hypertile_explanation": shared.OptionHTML("""
<a href='https://github.com/tfernd/HyperTile'>Hypertile</a> optimizes the self-attention layer within U-Net and VAE models,
resulting in a reduction in computation time ranging from 1 to 4 times. The larger the gener... | 242 | 1,068 | 826 | 1,894 | import hypertile
from modules import scripts, script_callbacks, shared
from scripts.hypertile_xyz import add_axis_options
class ScriptHypertile(scripts.Script):
name = "Hypertile"
def title(self):
return self.name
def show(self, is_img2img):
return scripts.AlwaysVisible
def process(... | import hypertile
from modules import scripts, script_callbacks, shared
from scripts.hypertile_xyz import add_axis_options
class ScriptHypertile(scripts.Script):
name = "Hypertile"
def title(self):
return self.name
def show(self, is_img2img):
return scripts.AlwaysVisible
def process(... | |
162 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/hypertile/scripts/hypertile_script.py | 22,23 | 6,58 | before_hr | ScriptHypertile | 23,37 | 23,37 | class ScriptHypertile(scripts.Script):
name = "Hypertile"
def title(self):
return self.name
def show(self, is_img2img):
return scripts.AlwaysVisible
def process(self, p, *args):
hypertile.set_hypertile_seed(p.all_seeds[0])
configure_hypertile(p.width, p.height, enable... | class ScriptHypertile(scripts.Script):
name = "Hypertile"
def title(self):
return self.name
def show(self, is_img2img):
return scripts.AlwaysVisible
def process(self, p, *args):
hypertile.set_hypertile_seed(p.all_seeds[0])
configure_hypertile(p.width, p.height, enable... |
enable = shared.opts.hypertile_enable_unet_secondpass or shared.opts.hypertile_enable_unet
# exclusive hypertile seed for the second pass
if enable:
hypertile.set_hypertile_seed(p.all_seeds[0])
configure_hypertile(p.hr_upscale_to_x, p.hr_upscale_to_y, enable_unet=enable)
... |
enable = shared.opts.hypertile_enable_unet_secondpass or shared.opts.hypertile_enable_unet
# exclusive hypertile seed for the second pass
if enable:
hypertile.set_hypertile_seed(p.all_seeds[0])
configure_hypertile(p.hr_upscale_to_x, p.hr_upscale_to_y, enable_unet=enable)
... | 32 | 539 | 191 | 730 | import hypertile
from modules import scripts, script_callbacks, shared
from scripts.hypertile_xyz import add_axis_options
class ScriptHypertile(scripts.Script):
name = "Hypertile"
def title(self):
return self.name
def show(self, is_img2img):
return scripts.AlwaysVisible
def process(... | import hypertile
from modules import scripts, script_callbacks, shared
from scripts.hypertile_xyz import add_axis_options
class ScriptHypertile(scripts.Script):
name = "Hypertile"
def title(self):
return self.name
def show(self, is_img2img):
return scripts.AlwaysVisible
def process(... |
163 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/hypertile/scripts/hypertile_xyz.py | 6,7 | 1,52 | int_applier | 10,22 | 7,22 | from modules import scripts
from modules.shared import opts
xyz_grid = [x for x in scripts.scripts_data if x.script_class.__module__ == "xyz_grid.py"][0].module
def int_applier(value_name:str, min_range:int = -1, max_range:int = -1):
FILL_FUNC_BODYdef bool_applier(value_name:str):
"""
Returns a function that ... | from modules import scripts
from modules.shared import opts
xyz_grid = [x for x in scripts.scripts_data if x.script_class.__module__ == "xyz_grid.py"][0].module
def int_applier(value_name:str, min_range:int = -1, max_range:int = -1):
"""
Returns a function that applies the given value to the given value_name ... | def validate(value_name:str, value:str):
value = int(value)
# validate value
if not min_range == -1:
assert value >= min_range, f"Value {value} for {value_name} must be greater than or equal to {min_range}"
if not max_range == -1:
assert value <= max_range, f"... | """
Returns a function that applies the given value to the given value_name in opts.data.
"""
def validate(value_name:str, value:str):
value = int(value)
# validate value
if not min_range == -1:
assert value >= min_range, f"Value {value} for {value_name} must be great... | 62 | 853 | 174 | 1,027 | from modules import scripts
from modules.shared import opts
xyz_grid = [x for x in scripts.scripts_data if x.script_class.__module__ == "xyz_grid.py"][0].module
def int_applier(value_name:str, min_range:int = -1, max_range:int = -1):
FILL_FUNC_BODYdef bool_applier(value_name:str):
"""
Returns a function that ... | from modules import scripts
from modules.shared import opts
xyz_grid = [x for x in scripts.scripts_data if x.script_class.__module__ == "xyz_grid.py"][0].module
def int_applier(value_name:str, min_range:int = -1, max_range:int = -1):
"""
Returns a function that applies the given value to the given value_name ... | |
164 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/postprocessing-for-training/scripts/postprocessing_autosized_crop.py | 18,19 | 1,65 | multicrop_pic | 19,29 | 19,29 | from PIL import Image
from modules import scripts_postprocessing, ui_components
import gradio as gr
def center_crop(image: Image, w: int, h: int):
iw, ih = image.size
if ih / h < iw / w:
sw = w * ih / h
box = (iw - sw) / 2, 0, iw - (iw - sw) / 2, ih
else:
sh = h * iw / w
b... | from PIL import Image
from modules import scripts_postprocessing, ui_components
import gradio as gr
def center_crop(image: Image, w: int, h: int):
iw, ih = image.size
if ih / h < iw / w:
sw = w * ih / h
box = (iw - sw) / 2, 0, iw - (iw - sw) / 2, ih
else:
sh = h * iw / w
b... | iw, ih = image.size
err = lambda w, h: 1 - (lambda x: x if x < 1 else 1 / x)(iw / ih / (w / h))
wh = max(((w, h) for w in range(mindim, maxdim + 1, 64) for h in range(mindim, maxdim + 1, 64)
if minarea <= w * h <= maxarea and err(w, h) <= threshold),
key=lambda wh: (wh[0] * wh[1],... | iw, ih = image.size
err = lambda w, h: 1 - (lambda x: x if x < 1 else 1 / x)(iw / ih / (w / h))
wh = max(((w, h) for w in range(mindim, maxdim + 1, 64) for h in range(mindim, maxdim + 1, 64)
if minarea <= w * h <= maxarea and err(w, h) <= threshold),
key=lambda wh: (wh[0] * wh[1],... | 81 | 887 | 190 | 1,077 | from PIL import Image
from modules import scripts_postprocessing, ui_components
import gradio as gr
def center_crop(image: Image, w: int, h: int):
iw, ih = image.size
if ih / h < iw / w:
sw = w * ih / h
box = (iw - sw) / 2, 0, iw - (iw - sw) / 2, ih
else:
sh = h * iw / w
b... | from PIL import Image
from modules import scripts_postprocessing, ui_components
import gradio as gr
def center_crop(image: Image, w: int, h: int):
iw, ih = image.size
if ih / h < iw / w:
sw = w * ih / h
box = (iw - sw) / 2, 0, iw - (iw - sw) / 2, ih
else:
sh = h * iw / w
b... | |
165 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/postprocessing-for-training/scripts/postprocessing_autosized_crop.py | 33,34 | 29,65 | ui | ScriptPostprocessingAutosizedCrop | 34,56 | 34,56 | class ScriptPostprocessingAutosizedCrop(scripts_postprocessing.ScriptPostprocessing):
name = "Auto-sized crop"
order = 4020
def ui(self):
FILL_FUNC_BODY def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, mindim, maxdim, minarea, maxarea, objective, threshold):
if not enable... | class ScriptPostprocessingAutosizedCrop(scripts_postprocessing.ScriptPostprocessing):
name = "Auto-sized crop"
order = 4020
def ui(self):
FILL_FUNC_BODY def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, mindim, maxdim, minarea, maxarea, objective, threshold):
if not enable... | with ui_components.InputAccordion(False, label="Auto-sized crop") as enable:
gr.Markdown('Each image is center-cropped with an automatically chosen width and height.')
with gr.Row():
mindim = gr.Slider(minimum=64, maximum=2048, step=8, label="Dimension lower bound", value... | with ui_components.InputAccordion(False, label="Auto-sized crop") as enable:
gr.Markdown('Each image is center-cropped with an automatically chosen width and height.')
with gr.Row():
mindim = gr.Slider(minimum=64, maximum=2048, step=8, label="Dimension lower bound", value... | 112 | 191 | 508 | 699 | from PIL import Image
from modules import scripts_postprocessing, ui_components
import gradio as gr
def center_crop(image: Image, w: int, h: int):
iw, ih = image.size
if ih / h < iw / w:
sw = w * ih / h
box = (iw - sw) / 2, 0, iw - (iw - sw) / 2, ih
else:
sh = h * iw / w
b... | from PIL import Image
from modules import scripts_postprocessing, ui_components
import gradio as gr
def center_crop(image: Image, w: int, h: int):
iw, ih = image.size
if ih / h < iw / w:
sw = w * ih / h
box = (iw - sw) / 2, 0, iw - (iw - sw) / 2, ih
else:
sh = h * iw / w
b... |
166 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/postprocessing-for-training/scripts/postprocessing_caption.py | 9,10 | 5,31 | ui | ScriptPostprocessingCeption | 10,18 | 10,18 | class ScriptPostprocessingCeption(scripts_postprocessing.ScriptPostprocessing):
name = "Caption"
order = 4040
def ui(self):
FILL_FUNC_BODY def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, option):
if not enable:
return
captions = [pp.caption]
... | class ScriptPostprocessingCeption(scripts_postprocessing.ScriptPostprocessing):
name = "Caption"
order = 4040
def ui(self):
FILL_FUNC_BODY def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, option):
if not enable:
return
captions = [pp.caption]
... | with ui_components.InputAccordion(False, label="Caption") as enable:
option = gr.CheckboxGroup(value=["Deepbooru"], choices=["Deepbooru", "BLIP"], show_label=False)
return {
"enable": enable,
"option": option,
}
| with ui_components.InputAccordion(False, label="Caption") as enable:
option = gr.CheckboxGroup(value=["Deepbooru"], choices=["Deepbooru", "BLIP"], show_label=False)
return {
"enable": enable,
"option": option,
}
| 18 | 188 | 93 | 281 | from modules import scripts_postprocessing, ui_components, deepbooru, shared
import gradio as gr
class ScriptPostprocessingCeption(scripts_postprocessing.ScriptPostprocessing):
name = "Caption"
order = 4040
def ui(self):
FILL_FUNC_BODY def process(self, pp: scripts_postprocessing.PostprocessedImage, e... | from modules import scripts_postprocessing, ui_components, deepbooru, shared
import gradio as gr
class ScriptPostprocessingCeption(scripts_postprocessing.ScriptPostprocessing):
name = "Caption"
order = 4040
def ui(self):
FILL_FUNC_BODY def process(self, pp: scripts_postprocessing.PostprocessedImage, e... |
167 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/postprocessing-for-training/scripts/postprocessing_create_flipped_copies.py | 11,12 | 7,33 | ui | ScriptPostprocessingCreateFlippedCopies | 12,21 | 12,21 | class ScriptPostprocessingCreateFlippedCopies(scripts_postprocessing.ScriptPostprocessing):
name = "Create flipped copies"
order = 4030
def ui(self):
FILL_FUNC_BODY def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, option):
if not enable:
return
if "Ho... | class ScriptPostprocessingCreateFlippedCopies(scripts_postprocessing.ScriptPostprocessing):
name = "Create flipped copies"
order = 4030
def ui(self):
FILL_FUNC_BODY def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, option):
if not enable:
return
if "Ho... | with ui_components.InputAccordion(False, label="Create flipped copies") as enable:
with gr.Row():
option = gr.CheckboxGroup(value=["Horizontal"], choices=["Horizontal", "Vertical", "Both"], show_label=False)
return {
"enable": enable,
"option": option... | with ui_components.InputAccordion(False, label="Create flipped copies") as enable:
with gr.Row():
option = gr.CheckboxGroup(value=["Horizontal"], choices=["Horizontal", "Vertical", "Both"], show_label=False)
return {
"enable": enable,
"option": option... | 23 | 223 | 99 | 322 | from PIL import ImageOps, Image
from modules import scripts_postprocessing, ui_components
import gradio as gr
class ScriptPostprocessingCreateFlippedCopies(scripts_postprocessing.ScriptPostprocessing):
name = "Create flipped copies"
order = 4030
def ui(self):
FILL_FUNC_BODY def process(self, pp: scri... | from PIL import ImageOps, Image
from modules import scripts_postprocessing, ui_components
import gradio as gr
class ScriptPostprocessingCreateFlippedCopies(scripts_postprocessing.ScriptPostprocessing):
name = "Create flipped copies"
order = 4030
def ui(self):
FILL_FUNC_BODY def process(self, pp: scri... |
168 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/postprocessing-for-training/scripts/postprocessing_focal_crop.py | 12,13 | 8,55 | ui | ScriptPostprocessingFocalCrop | 13,27 | 13,27 | class ScriptPostprocessingFocalCrop(scripts_postprocessing.ScriptPostprocessing):
name = "Auto focal point crop"
order = 4010
def ui(self):
FILL_FUNC_BODY def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, face_weight, entropy_weight, edges_weight, debug):
if not enable:
... | class ScriptPostprocessingFocalCrop(scripts_postprocessing.ScriptPostprocessing):
name = "Auto focal point crop"
order = 4010
def ui(self):
FILL_FUNC_BODY def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, face_weight, entropy_weight, edges_weight, debug):
if not enable:
... | with ui_components.InputAccordion(False, label="Auto focal point crop") as enable:
face_weight = gr.Slider(label='Focal point face weight', value=0.9, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_focal_crop_face_weight")
entropy_weight = gr.Slider(label='Focal point entropy ... | with ui_components.InputAccordion(False, label="Auto focal point crop") as enable:
face_weight = gr.Slider(label='Focal point face weight', value=0.9, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_focal_crop_face_weight")
entropy_weight = gr.Slider(label='Focal point entropy ... | 60 | 385 | 322 | 707 |
from modules import scripts_postprocessing, ui_components, errors
import gradio as gr
from modules.textual_inversion import autocrop
class ScriptPostprocessingFocalCrop(scripts_postprocessing.ScriptPostprocessing):
name = "Auto focal point crop"
order = 4010
def ui(self):
FILL_FUNC_BODY def process(... |
from modules import scripts_postprocessing, ui_components, errors
import gradio as gr
from modules.textual_inversion import autocrop
class ScriptPostprocessingFocalCrop(scripts_postprocessing.ScriptPostprocessing):
name = "Auto focal point crop"
order = 4010
def ui(self):
FILL_FUNC_BODY def process(... |
169 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/postprocessing-for-training/scripts/postprocessing_split_oversized.py | 7,8 | 1,72 | split_pic | 8,31 | 8,31 | import math
from modules import scripts_postprocessing, ui_components
import gradio as gr
def split_pic(image, inverse_xy, width, height, overlap_ratio):
FILL_FUNC_BODYclass ScriptPostprocessingSplitOversized(scripts_postprocessing.ScriptPostprocessing):
name = "Split oversized images"
order = 4000
def ... | import math
from modules import scripts_postprocessing, ui_components
import gradio as gr
def split_pic(image, inverse_xy, width, height, overlap_ratio):
FILL_FUNC_BODYclass ScriptPostprocessingSplitOversized(scripts_postprocessing.ScriptPostprocessing):
name = "Split oversized images"
order = 4000
def ... | if inverse_xy:
from_w, from_h = image.height, image.width
to_w, to_h = height, width
else:
from_w, from_h = image.width, image.height
to_w, to_h = width, height
h = from_h * to_w // from_w
if inverse_xy:
image = image.resize((h, to_w))
else:
image = im... | if inverse_xy:
from_w, from_h = image.height, image.width
to_w, to_h = height, width
else:
from_w, from_h = image.width, image.height
to_w, to_h = width, height
h = from_h * to_w // from_w
if inverse_xy:
image = image.resize((h, to_w))
else:
image = im... | 93 | 518 | 296 | 814 | import math
from modules import scripts_postprocessing, ui_components
import gradio as gr
def split_pic(image, inverse_xy, width, height, overlap_ratio):
FILL_FUNC_BODYclass ScriptPostprocessingSplitOversized(scripts_postprocessing.ScriptPostprocessing):
name = "Split oversized images"
order = 4000
def ... | import math
from modules import scripts_postprocessing, ui_components
import gradio as gr
def split_pic(image, inverse_xy, width, height, overlap_ratio):
FILL_FUNC_BODYclass ScriptPostprocessingSplitOversized(scripts_postprocessing.ScriptPostprocessing):
name = "Split oversized images"
order = 4000
def ... | |
170 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/postprocessing-for-training/scripts/postprocessing_split_oversized.py | 47,48 | 31,72 | process | ScriptPostprocessingSplitOversized | 48,72 | 48,72 | class ScriptPostprocessingSplitOversized(scripts_postprocessing.ScriptPostprocessing):
name = "Split oversized images"
order = 4000
def ui(self):
with ui_components.InputAccordion(False, label="Split oversized images") as enable:
with gr.Row():
split_threshold = gr.Slide... | class ScriptPostprocessingSplitOversized(scripts_postprocessing.ScriptPostprocessing):
name = "Split oversized images"
order = 4000
def ui(self):
with ui_components.InputAccordion(False, label="Split oversized images") as enable:
with gr.Row():
split_threshold = gr.Slide... | if not enable:
return
width = pp.shared.target_width
height = pp.shared.target_height
if not width or not height:
return
if pp.image.height > pp.image.width:
ratio = (pp.image.width * height) / (pp.image.height * width)
inverse_x... | if not enable:
return
width = pp.shared.target_width
height = pp.shared.target_height
if not width or not height:
return
if pp.image.height > pp.image.width:
ratio = (pp.image.width * height) / (pp.image.height * width)
inverse_x... | 73 | 270 | 228 | 498 | import math
from modules import scripts_postprocessing, ui_components
import gradio as gr
def split_pic(image, inverse_xy, width, height, overlap_ratio):
if inverse_xy:
from_w, from_h = image.height, image.width
to_w, to_h = height, width
else:
from_w, from_h = image.width, image.heig... | import math
from modules import scripts_postprocessing, ui_components
import gradio as gr
def split_pic(image, inverse_xy, width, height, overlap_ratio):
if inverse_xy:
from_w, from_h = image.height, image.width
to_w, to_h = height, width
else:
from_w, from_h = image.width, image.heig... |
173 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/extensions-builtin/soft-inpainting/scripts/soft_inpainting.py | 23,24 | 8,35 | add_generation_params | SoftInpaintingSettings | 24,35 | 24,35 | class SoftInpaintingSettings:
def __init__(self,
mask_blend_power,
mask_blend_scale,
inpaint_detail_preservation,
composite_mask_influence,
composite_difference_threshold,
composite_difference_contrast):
se... | class SoftInpaintingSettings:
def __init__(self,
mask_blend_power,
mask_blend_scale,
inpaint_detail_preservation,
composite_mask_influence,
composite_difference_threshold,
composite_difference_contrast):
se... | dest[enabled_gen_param_label] = True
dest[gen_param_labels.mask_blend_power] = self.mask_blend_power
dest[gen_param_labels.mask_blend_scale] = self.mask_blend_scale
dest[gen_param_labels.inpaint_detail_preservation] = self.inpaint_detail_preservation
dest[gen_param_labels.composi... | dest[enabled_gen_param_label] = True
dest[gen_param_labels.mask_blend_power] = self.mask_blend_power
dest[gen_param_labels.mask_blend_scale] = self.mask_blend_scale
dest[gen_param_labels.inpaint_detail_preservation] = self.inpaint_detail_preservation
dest[gen_param_labels.composi... | 25 | 213 | 207 | 420 | import numpy as np
import gradio as gr
import math
from modules.ui_components import InputAccordion
import modules.scripts as scripts
class SoftInpaintingSettings:
def __init__(self,
mask_blend_power,
mask_blend_scale,
inpaint_detail_preservation,
... | import numpy as np
import gradio as gr
import math
from modules.ui_components import InputAccordion
import modules.scripts as scripts
class SoftInpaintingSettings:
def __init__(self,
mask_blend_power,
mask_blend_scale,
inpaint_detail_preservation,
... |
174 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/launch.py | 27,28 | 1,49 | main | 28,47 | 28,47 | from modules import launch_utils
args = launch_utils.args
python = launch_utils.python
git = launch_utils.git
index_url = launch_utils.index_url
dir_repos = launch_utils.dir_repos
commit_hash = launch_utils.commit_hash
git_tag = launch_utils.git_tag
run = launch_utils.run
is_installed = launch_utils.is_installed
rep... | from modules import launch_utils
args = launch_utils.args
python = launch_utils.python
git = launch_utils.git
index_url = launch_utils.index_url
dir_repos = launch_utils.dir_repos
commit_hash = launch_utils.commit_hash
git_tag = launch_utils.git_tag
run = launch_utils.run
is_installed = launch_utils.is_installed
rep... | if args.dump_sysinfo:
filename = launch_utils.dump_sysinfo()
print(f"Sysinfo saved as {filename}. Exiting...")
exit(0)
launch_utils.startup_timer.record("initial startup")
with launch_utils.startup_timer.subcategory("prepare environment"):
if not args.skip_prepare_environ... | if args.dump_sysinfo:
filename = launch_utils.dump_sysinfo()
print(f"Sysinfo saved as {filename}. Exiting...")
exit(0)
launch_utils.startup_timer.record("initial startup")
with launch_utils.startup_timer.subcategory("prepare environment"):
if not args.skip_prepare_environ... | 24 | 274 | 148 | 422 | from modules import launch_utils
args = launch_utils.args
python = launch_utils.python
git = launch_utils.git
index_url = launch_utils.index_url
dir_repos = launch_utils.dir_repos
commit_hash = launch_utils.commit_hash
git_tag = launch_utils.git_tag
run = launch_utils.run
is_installed = launch_utils.is_installed
rep... | from modules import launch_utils
args = launch_utils.args
python = launch_utils.python
git = launch_utils.git
index_url = launch_utils.index_url
dir_repos = launch_utils.dir_repos
commit_hash = launch_utils.commit_hash
git_tag = launch_utils.git_tag
run = launch_utils.run
is_installed = launch_utils.is_installed
rep... | |
175 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/api/models.py | 87,88 | 37,100 | generate_model | PydanticModelGenerator | 92,100 | 88,100 | class PydanticModelGenerator:
"""
Takes in created classes and stubs them out in a way FastAPI/Pydantic is happy about:
source_data is a snapshot of the default values produced by the class
params are the names of the actual keys required by __init__
"""
def __init__(
self,
mode... | class PydanticModelGenerator:
"""
Takes in created classes and stubs them out in a way FastAPI/Pydantic is happy about:
source_data is a snapshot of the default values produced by the class
params are the names of the actual keys required by __init__
"""
def __init__(
self,
mode... | fields = {
d.field: (d.field_type, Field(default=d.field_value, alias=d.field_alias, exclude=d.field_exclude)) for d in self._model_def
}
DynamicModel = create_model(self._model_name, **fields)
DynamicModel.__config__.allow_population_by_field_name = True
DynamicModel... | """
Creates a pydantic BaseModel
from the json and overrides provided at initialization
"""
fields = {
d.field: (d.field_type, Field(default=d.field_value, alias=d.field_alias, exclude=d.field_exclude)) for d in self._model_def
}
DynamicModel = create_... | 25 | 522 | 126 | 648 | import inspect
from pydantic import BaseModel, Field, create_model
from typing import Any, Optional, Literal
from inflection import underscore
from modules.processing import StableDiffusionProcessingTxt2Img, StableDiffusionProcessingImg2Img
from modules.shared import sd_upscalers, opts, parser
API_NOT_ALLOWED = [
... | import inspect
from pydantic import BaseModel, Field, create_model
from typing import Any, Optional, Literal
from inflection import underscore
from modules.processing import StableDiffusionProcessingTxt2Img, StableDiffusionProcessingImg2Img
from modules.shared import sd_upscalers, opts, parser
API_NOT_ALLOWED = [
... |
176 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/cache.py | 23,24 | 1,124 | make_cache | 24,31 | 24,31 | import json
import os
import os.path
import threading
import diskcache
import tqdm
from modules.paths import data_path, script_path
cache_filename = os.environ.get('SD_WEBUI_CACHE_FILE', os.path.join(data_path, "cache.json"))
cache_dir = os.environ.get('SD_WEBUI_CACHE_DIR', os.path.join(data_path, "cache"))
caches =... | import json
import os
import os.path
import threading
import diskcache
import tqdm
from modules.paths import data_path, script_path
cache_filename = os.environ.get('SD_WEBUI_CACHE_FILE', os.path.join(data_path, "cache.json"))
cache_dir = os.environ.get('SD_WEBUI_CACHE_DIR', os.path.join(data_path, "cache"))
caches =... | return diskcache.Cache(
os.path.join(cache_dir, subsection),
size_limit=2**32, # 4 GB, culling oldest first
disk_min_file_size=2**18, # keep up to 256KB in Sqlite
)
| return diskcache.Cache(
os.path.join(cache_dir, subsection),
size_limit=2**32, # 4 GB, culling oldest first
disk_min_file_size=2**18, # keep up to 256KB in Sqlite
)
| 20 | 1,072 | 84 | 1,156 | import json
import os
import os.path
import threading
import diskcache
import tqdm
from modules.paths import data_path, script_path
cache_filename = os.environ.get('SD_WEBUI_CACHE_FILE', os.path.join(data_path, "cache.json"))
cache_dir = os.environ.get('SD_WEBUI_CACHE_DIR', os.path.join(data_path, "cache"))
caches =... | import json
import os
import os.path
import threading
import diskcache
import tqdm
from modules.paths import data_path, script_path
cache_filename = os.environ.get('SD_WEBUI_CACHE_FILE', os.path.join(data_path, "cache.json"))
cache_dir = os.environ.get('SD_WEBUI_CACHE_DIR', os.path.join(data_path, "cache"))
caches =... | |
177 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/call_queue.py | 48,49 | 1,120 | wrap_gradio_call | 49,120 | 49,120 | from functools import wraps
import html
import time
from modules import shared, progress, errors, devices, fifo_lock
queue_lock = fifo_lock.FIFOLock()
def wrap_queued_call(func):
def f(*args, **kwargs):
with queue_lock:
res = func(*args, **kwargs)
return res
return f
def wrap... | from functools import wraps
import html
import time
from modules import shared, progress, errors, devices, fifo_lock
queue_lock = fifo_lock.FIFOLock()
def wrap_queued_call(func):
def f(*args, **kwargs):
with queue_lock:
res = func(*args, **kwargs)
return res
return f
def wrap... | @wraps(func)
def f(*args, extra_outputs_array=extra_outputs, **kwargs):
run_memmon = shared.opts.memmon_poll_rate > 0 and not shared.mem_mon.disabled and add_stats
if run_memmon:
shared.mem_mon.monitor()
t = time.perf_counter()
try:
res = list(func(*args,... | @wraps(func)
def f(*args, extra_outputs_array=extra_outputs, **kwargs):
run_memmon = shared.opts.memmon_poll_rate > 0 and not shared.mem_mon.disabled and add_stats
if run_memmon:
shared.mem_mon.monitor()
t = time.perf_counter()
try:
res = list(func(*args,... | 272 | 396 | 1,160 | 1,556 | from functools import wraps
import html
import time
from modules import shared, progress, errors, devices, fifo_lock
queue_lock = fifo_lock.FIFOLock()
def wrap_queued_call(func):
def f(*args, **kwargs):
with queue_lock:
res = func(*args, **kwargs)
return res
return f
def wrap... | from functools import wraps
import html
import time
from modules import shared, progress, errors, devices, fifo_lock
queue_lock = fifo_lock.FIFOLock()
def wrap_queued_call(func):
def f(*args, **kwargs):
with queue_lock:
res = func(*args, **kwargs)
return res
return f
def wrap... | |
178 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/codeformer_model.py | 58,59 | 1,65 | setup_model | 59,65 | 59,65 | from __future__ import annotations
import logging
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.p... | from __future__ import annotations
import logging
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.p... | global codeformer
try:
codeformer = FaceRestorerCodeFormer(dirname)
shared.face_restorers.append(codeformer)
except Exception:
errors.report("Error setting up CodeFormer", exc_info=True)
| global codeformer
try:
codeformer = FaceRestorerCodeFormer(dirname)
shared.face_restorers.append(codeformer)
except Exception:
errors.report("Error setting up CodeFormer", exc_info=True)
| 14 | 524 | 69 | 593 | from __future__ import annotations
import logging
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.p... | from __future__ import annotations
import logging
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.p... | |
179 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/codeformer_model.py | 47,48 | 25,58 | restore | FaceRestorerCodeFormer | 48,58 | 48,58 | class FaceRestorerCodeFormer(face_restoration_utils.CommonFaceRestoration):
def name(self):
return "CodeFormer"
def load_net(self) -> torch.Module:
for model_path in modelloader.load_models(
model_path=self.model_path,
model_url=model_url,
command_path=self.m... | class FaceRestorerCodeFormer(face_restoration_utils.CommonFaceRestoration):
def name(self):
return "CodeFormer"
def load_net(self) -> torch.Module:
for model_path in modelloader.load_models(
model_path=self.model_path,
model_url=model_url,
command_path=self.m... | if w is None:
w = getattr(shared.opts, "code_former_weight", 0.5)
def restore_face(cropped_face_t):
assert self.net is not None
return self.net(cropped_face_t, weight=w, adain=True)[0]
return self.restore_with_helper(np_image, restore_face)
| if w is None:
w = getattr(shared.opts, "code_former_weight", 0.5)
def restore_face(cropped_face_t):
assert self.net is not None
return self.net(cropped_face_t, weight=w, adain=True)[0]
return self.restore_with_helper(np_image, restore_face)
| 23 | 240 | 114 | 354 | from __future__ import annotations
import logging
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.p... | from __future__ import annotations
import logging
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.p... |
180 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/config_states.py | 115,116 | 1,199 | restore_webui_config | 116,146 | 116,146 | """
Supports saving and restoring webui and extensions from a known working set of commits
"""
import os
import json
import tqdm
from datetime import datetime
import git
from modules import shared, extensions, errors
from modules.paths_internal import script_path, config_states_dir
all_config_states = {}
def list... | """
Supports saving and restoring webui and extensions from a known working set of commits
"""
import os
import json
import tqdm
from datetime import datetime
import git
from modules import shared, extensions, errors
from modules.paths_internal import script_path, config_states_dir
all_config_states = {}
def list... | print("* Restoring webui state...")
if "webui" not in config:
print("Error: No webui data saved to config")
return
webui_config = config["webui"]
if "commit_hash" not in webui_config:
print("Error: No commit saved to webui config")
return
webui_commit_hash = webui... | print("* Restoring webui state...")
if "webui" not in config:
print("Error: No webui data saved to config")
return
webui_config = config["webui"]
if "commit_hash" not in webui_config:
print("Error: No commit saved to webui config")
return
webui_commit_hash = webui... | 75 | 1,529 | 341 | 1,870 | """
Supports saving and restoring webui and extensions from a known working set of commits
"""
import os
import json
import tqdm
from datetime import datetime
import git
from modules import shared, extensions, errors
from modules.paths_internal import script_path, config_states_dir
all_config_states = {}
def list... | """
Supports saving and restoring webui and extensions from a known working set of commits
"""
import os
import json
import tqdm
from datetime import datetime
import git
from modules import shared, extensions, errors
from modules.paths_internal import script_path, config_states_dir
all_config_states = {}
def list... | |
181 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/dat_model.py | 59,60 | 1,80 | get_dat_models | 60,80 | 60,80 | import os
from modules import modelloader, errors
from modules.shared import cmd_opts, opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerDAT(Upscaler):
def __init__(self, user_path):
self.name = "DAT"
self.user_path = user... | import os
from modules import modelloader, errors
from modules.shared import cmd_opts, opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerDAT(Upscaler):
def __init__(self, user_path):
self.name = "DAT"
self.user_path = user... | return [
UpscalerData(
name="DAT x2",
path="https://github.com/n0kovo/dat_upscaler_models/raw/main/DAT/DAT_x2.pth",
scale=2,
upscaler=scaler,
),
UpscalerData(
name="DAT x3",
path="https://github.com/n0kovo/dat_upscaler_m... | return [
UpscalerData(
name="DAT x2",
path="https://github.com/n0kovo/dat_upscaler_models/raw/main/DAT/DAT_x2.pth",
scale=2,
upscaler=scaler,
),
UpscalerData(
name="DAT x3",
path="https://github.com/n0kovo/dat_upscaler_m... | 24 | 641 | 255 | 896 | import os
from modules import modelloader, errors
from modules.shared import cmd_opts, opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerDAT(Upscaler):
def __init__(self, user_path):
self.name = "DAT"
self.user_path = user... | import os
from modules import modelloader, errors
from modules.shared import cmd_opts, opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerDAT(Upscaler):
def __init__(self, user_path):
self.name = "DAT"
self.user_path = user... | |
182 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/dat_model.py | 45,46 | 9,59 | load_model | UpscalerDAT | 46,59 | 46,59 | class UpscalerDAT(Upscaler):
def __init__(self, user_path):
self.name = "DAT"
self.user_path = user_path
self.scalers = []
super().__init__()
for file in self.find_models(ext_filter=[".pt", ".pth"]):
name = modelloader.friendly_name(file)
scaler_data ... | class UpscalerDAT(Upscaler):
def __init__(self, user_path):
self.name = "DAT"
self.user_path = user_path
self.scalers = []
super().__init__()
for file in self.find_models(ext_filter=[".pt", ".pth"]):
name = modelloader.friendly_name(file)
scaler_data ... | for scaler in self.scalers:
if scaler.data_path == path:
if scaler.local_data_path.startswith("http"):
scaler.local_data_path = modelloader.load_file_from_url(
scaler.data_path,
model_dir=self.model_download_path,
... | for scaler in self.scalers:
if scaler.data_path == path:
if scaler.local_data_path.startswith("http"):
scaler.local_data_path = modelloader.load_file_from_url(
scaler.data_path,
model_dir=self.model_download_path,
... | 33 | 407 | 175 | 582 | import os
from modules import modelloader, errors
from modules.shared import cmd_opts, opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerDAT(Upscaler):
def __init__(self, user_path):
self.name = "DAT"
self.user_path = user... | import os
from modules import modelloader, errors
from modules.shared import cmd_opts, opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerDAT(Upscaler):
def __init__(self, user_path):
self.name = "DAT"
self.user_path = user... |
183 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/deepbooru.py | 16,17 | 12,98 | load | DeepDanbooru | 17,33 | 17,33 | class DeepDanbooru:
def __init__(self):
self.model = None
def load(self):
FILL_FUNC_BODY def start(self):
self.load()
self.model.to(devices.device)
def stop(self):
if not shared.opts.interrogate_keep_models_in_memory:
self.model.to(devices.cpu)
de... | class DeepDanbooru:
def __init__(self):
self.model = None
def load(self):
FILL_FUNC_BODY def start(self):
self.load()
self.model.to(devices.device)
def stop(self):
if not shared.opts.interrogate_keep_models_in_memory:
self.model.to(devices.cpu)
de... | if self.model is not None:
return
files = modelloader.load_models(
model_path=os.path.join(paths.models_path, "torch_deepdanbooru"),
model_url='https://github.com/AUTOMATIC1111/TorchDeepDanbooru/releases/download/v1/model-resnet_custom_v3.pt',
ext_filter=... | if self.model is not None:
return
files = modelloader.load_models(
model_path=os.path.join(paths.models_path, "torch_deepdanbooru"),
model_url='https://github.com/AUTOMATIC1111/TorchDeepDanbooru/releases/download/v1/model-resnet_custom_v3.pt',
ext_filter=... | 23 | 721 | 233 | 954 | import os
import re
import torch
import numpy as np
from modules import modelloader, paths, deepbooru_model, devices, images, shared
re_special = re.compile(r'([\\()])')
class DeepDanbooru:
def __init__(self):
self.model = None
def load(self):
FILL_FUNC_BODY def start(self):
self.load()... | import os
import re
import torch
import numpy as np
from modules import modelloader, paths, deepbooru_model, devices, images, shared
re_special = re.compile(r'([\\()])')
class DeepDanbooru:
def __init__(self):
self.model = None
def load(self):
FILL_FUNC_BODY def start(self):
self.load()... |
186 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/errors.py | 85,86 | 1,151 | display_once | 86,96 | 86,96 | import sys
import textwrap
import traceback
exception_records = []
def format_traceback(tb):
return [[f"{x.filename}, line {x.lineno}, {x.name}", x.line] for x in traceback.extract_tb(tb)]
def format_exception(e, tb):
return {"exception": str(e), "traceback": format_traceback(tb)}
def get_exceptions():
... | import sys
import textwrap
import traceback
exception_records = []
def format_traceback(tb):
return [[f"{x.filename}, line {x.lineno}, {x.name}", x.line] for x in traceback.extract_tb(tb)]
def format_exception(e, tb):
return {"exception": str(e), "traceback": format_traceback(tb)}
def get_exceptions():
... | record_exception()
if task in already_displayed:
return
display(e, task)
already_displayed[task] = 1
| record_exception()
if task in already_displayed:
return
display(e, task)
already_displayed[task] = 1
| 11 | 1,363 | 53 | 1,416 | import sys
import textwrap
import traceback
exception_records = []
def format_traceback(tb):
return [[f"{x.filename}, line {x.lineno}, {x.name}", x.line] for x in traceback.extract_tb(tb)]
def format_exception(e, tb):
return {"exception": str(e), "traceback": format_traceback(tb)}
def get_exceptions():
... | import sys
import textwrap
import traceback
exception_records = []
def format_traceback(tb):
return [[f"{x.filename}, line {x.lineno}, {x.name}", x.line] for x in traceback.extract_tb(tb)]
def format_exception(e, tb):
return {"exception": str(e), "traceback": format_traceback(tb)}
def get_exceptions():
... | |
187 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/esrgan_model.py | 56,57 | 1,63 | esrgan_upscale | 57,63 | 57,63 | from modules import modelloader, devices, errors
from modules.shared import opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerESRGAN(Upscaler):
def __init__(self, dirname):
self.name = "ESRGAN"
self.model_url = "https://git... | from modules import modelloader, devices, errors
from modules.shared import opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerESRGAN(Upscaler):
def __init__(self, dirname):
self.name = "ESRGAN"
self.model_url = "https://git... | return upscale_with_model(
model,
img,
tile_size=opts.ESRGAN_tile,
tile_overlap=opts.ESRGAN_tile_overlap,
)
| return upscale_with_model(
model,
img,
tile_size=opts.ESRGAN_tile,
tile_overlap=opts.ESRGAN_tile_overlap,
)
| 7 | 644 | 61 | 705 | from modules import modelloader, devices, errors
from modules.shared import opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerESRGAN(Upscaler):
def __init__(self, dirname):
self.name = "ESRGAN"
self.model_url = "https://git... | from modules import modelloader, devices, errors
from modules.shared import opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerESRGAN(Upscaler):
def __init__(self, dirname):
self.name = "ESRGAN"
self.model_url = "https://git... | |
188 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/esrgan_model.py | 38,39 | 7,56 | load_model | UpscalerESRGAN | 39,56 | 39,56 | class UpscalerESRGAN(Upscaler):
def __init__(self, dirname):
self.name = "ESRGAN"
self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/ESRGAN.pth"
self.model_name = "ESRGAN_4x"
self.scalers = []
self.user_path = dirname
super().__init__()
mode... | class UpscalerESRGAN(Upscaler):
def __init__(self, dirname):
self.name = "ESRGAN"
self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/ESRGAN.pth"
self.model_name = "ESRGAN_4x"
self.scalers = []
self.user_path = dirname
super().__init__()
mode... | if path.startswith("http"):
# TODO: this doesn't use `path` at all?
filename = modelloader.load_file_from_url(
url=self.model_url,
model_dir=self.model_download_path,
file_name=f"{self.model_name}.pth",
)
else:
... | if path.startswith("http"):
# TODO: this doesn't use `path` at all?
filename = modelloader.load_file_from_url(
url=self.model_url,
model_dir=self.model_download_path,
file_name=f"{self.model_name}.pth",
)
else:
... | 33 | 414 | 179 | 593 | from modules import modelloader, devices, errors
from modules.shared import opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerESRGAN(Upscaler):
def __init__(self, dirname):
self.name = "ESRGAN"
self.model_url = "https://git... | from modules import modelloader, devices, errors
from modules.shared import opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerESRGAN(Upscaler):
def __init__(self, dirname):
self.name = "ESRGAN"
self.model_url = "https://git... |
190 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/extensions.py | 192,193 | 105,225 | check_updates | Extension | 193,216 | 193,216 | class Extension:
lock = threading.Lock()
cached_fields = ['remote', 'commit_date', 'branch', 'commit_hash', 'version']
metadata: ExtensionMetadata
def __init__(self, name, path, enabled=True, is_builtin=False, metadata=None):
self.name = name
self.path = path
self.enabled = enab... | class Extension:
lock = threading.Lock()
cached_fields = ['remote', 'commit_date', 'branch', 'commit_hash', 'version']
metadata: ExtensionMetadata
def __init__(self, name, path, enabled=True, is_builtin=False, metadata=None):
self.name = name
self.path = path
self.enabled = enab... | repo = Repo(self.path)
for fetch in repo.remote().fetch(dry_run=True):
if self.branch and fetch.name != f'{repo.remote().name}/{self.branch}':
continue
if fetch.flags != fetch.HEAD_UPTODATE:
self.can_update = True
self.status = "new... | repo = Repo(self.path)
for fetch in repo.remote().fetch(dry_run=True):
if self.branch and fetch.name != f'{repo.remote().name}/{self.branch}':
continue
if fetch.flags != fetch.HEAD_UPTODATE:
self.can_update = True
self.status = "new... | 59 | 1,014 | 224 | 1,238 | from __future__ import annotations
import configparser
import dataclasses
import os
import threading
import re
from modules import shared, errors, cache, scripts
from modules.gitpython_hack import Repo
from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401
extensions: li... | from __future__ import annotations
import configparser
import dataclasses
import os
import threading
import re
from modules import shared, errors, cache, scripts
from modules.gitpython_hack import Repo
from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401
extensions: li... |
191 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/extensions.py | 88,89 | 37,105 | list_callback_order_instructions | ExtensionMetadata | 89,105 | 89,105 | class ExtensionMetadata:
filename = "metadata.ini"
config: configparser.ConfigParser
canonical_name: str
requires: list
def __init__(self, path, canonical_name):
self.config = configparser.ConfigParser()
filepath = os.path.join(path, self.filename)
# `self.config.read()` wi... | class ExtensionMetadata:
filename = "metadata.ini"
config: configparser.ConfigParser
canonical_name: str
requires: list
def __init__(self, path, canonical_name):
self.config = configparser.ConfigParser()
filepath = os.path.join(path, self.filename)
# `self.config.read()` wi... | for section in self.config.sections():
if not section.startswith("callbacks/"):
continue
callback_name = section[10:]
if not callback_name.startswith(self.canonical_name):
errors.report(f"Callback order section for extension {self.canonical_n... | for section in self.config.sections():
if not section.startswith("callbacks/"):
continue
callback_name = section[10:]
if not callback_name.startswith(self.canonical_name):
errors.report(f"Callback order section for extension {self.canonical_n... | 41 | 590 | 183 | 773 | from __future__ import annotations
import configparser
import dataclasses
import os
import threading
import re
from modules import shared, errors, cache, scripts
from modules.gitpython_hack import Repo
from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401
extensions: li... | from __future__ import annotations
import configparser
import dataclasses
import os
import threading
import re
from modules import shared, errors, cache, scripts
from modules.gitpython_hack import Repo
from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401
extensions: li... |
193 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/extra_networks.py | 52,53 | 48,90 | activate | ExtraNetwork | 80,82 | 53,82 | class ExtraNetwork:
def __init__(self, name):
self.name = name
def activate(self, p, params_list):
FILL_FUNC_BODY def deactivate(self, p):
"""
Called at the end of processing for housekeeping. No need to do anything here.
"""
raise NotImplementedError
| class ExtraNetwork:
def __init__(self, name):
self.name = name
def activate(self, p, params_list):
"""
Called by processing on every run. Whatever the extra network is meant to do should be activated here.
Passes arguments related to this extra network in params_list.
Us... | raise NotImplementedError
| """
Called by processing on every run. Whatever the extra network is meant to do should be activated here.
Passes arguments related to this extra network in params_list.
User passes arguments by specifying this in his prompt:
<name:arg1:arg2:arg3>
Where name matches the... | 2 | 385 | 11 | 396 | import json
import os
import re
import logging
from collections import defaultdict
from modules import errors
extra_network_registry = {}
extra_network_aliases = {}
def initialize():
extra_network_registry.clear()
extra_network_aliases.clear()
def register_extra_network(extra_network):
extra_network_r... | import json
import os
import re
import logging
from collections import defaultdict
from modules import errors
extra_network_registry = {}
extra_network_aliases = {}
def initialize():
extra_network_registry.clear()
extra_network_aliases.clear()
def register_extra_network(extra_network):
extra_network_r... |
194 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/extra_networks_hypernet.py | 9,10 | 5,29 | activate | ExtraNetworkHypernet | 10,27 | 10,27 | class ExtraNetworkHypernet(extra_networks.ExtraNetwork):
def __init__(self):
super().__init__('hypernet')
def activate(self, p, params_list):
FILL_FUNC_BODY def deactivate(self, p):
pass
| class ExtraNetworkHypernet(extra_networks.ExtraNetwork):
def __init__(self):
super().__init__('hypernet')
def activate(self, p, params_list):
FILL_FUNC_BODY def deactivate(self, p):
pass
| additional = shared.opts.sd_hypernetwork
if additional != "None" and additional in shared.hypernetworks and not any(x for x in params_list if x.items[0] == additional):
hypernet_prompt_text = f"<hypernet:{additional}:{shared.opts.extra_networks_default_multiplier}>"
p.all_prompt... | additional = shared.opts.sd_hypernetwork
if additional != "None" and additional in shared.hypernetworks and not any(x for x in params_list if x.items[0] == additional):
hypernet_prompt_text = f"<hypernet:{additional}:{shared.opts.extra_networks_default_multiplier}>"
p.all_prompt... | 56 | 73 | 271 | 344 | from modules import extra_networks, shared
from modules.hypernetworks import hypernetwork
class ExtraNetworkHypernet(extra_networks.ExtraNetwork):
def __init__(self):
super().__init__('hypernet')
def activate(self, p, params_list):
FILL_FUNC_BODY def deactivate(self, p):
pass
| from modules import extra_networks, shared
from modules.hypernetworks import hypernetwork
class ExtraNetworkHypernet(extra_networks.ExtraNetwork):
def __init__(self):
super().__init__('hypernet')
def activate(self, p, params_list):
FILL_FUNC_BODY def deactivate(self, p):
pass
|
195 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/face_restoration.py | 12,13 | 1,20 | restore_faces | 13,20 | 13,20 | from modules import shared
class FaceRestoration:
def name(self):
return "None"
def restore(self, np_image):
return np_image
def restore_faces(np_image):
FILL_FUNC_BODY | from modules import shared
class FaceRestoration:
def name(self):
return "None"
def restore(self, np_image):
return np_image
def restore_faces(np_image):
FILL_FUNC_BODY | face_restorers = [x for x in shared.face_restorers if x.name() == shared.opts.face_restoration_model or shared.opts.face_restoration_model is None]
if len(face_restorers) == 0:
return np_image
face_restorer = face_restorers[0]
return face_restorer.restore(np_image)
| face_restorers = [x for x in shared.face_restorers if x.name() == shared.opts.face_restoration_model or shared.opts.face_restoration_model is None]
if len(face_restorers) == 0:
return np_image
face_restorer = face_restorers[0]
return face_restorer.restore(np_image)
| 26 | 66 | 109 | 175 | from modules import shared
class FaceRestoration:
def name(self):
return "None"
def restore(self, np_image):
return np_image
def restore_faces(np_image):
FILL_FUNC_BODY | from modules import shared
class FaceRestoration:
def name(self):
return "None"
def restore(self, np_image):
return np_image
def restore_faces(np_image):
FILL_FUNC_BODY | |
196 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/face_restoration.py | 8,9 | 4,12 | restore | FaceRestoration | 9,12 | 9,12 | class FaceRestoration:
def name(self):
return "None"
def restore(self, np_image):
FILL_FUNC_BODY | class FaceRestoration:
def name(self):
return "None"
def restore(self, np_image):
FILL_FUNC_BODY | return np_image
| return np_image
| 2 | 41 | 11 | 52 | from modules import shared
class FaceRestoration:
def name(self):
return "None"
def restore(self, np_image):
FILL_FUNC_BODYdef restore_faces(np_image):
face_restorers = [x for x in shared.face_restorers if x.name() == shared.opts.face_restoration_model or shared.opts.face_restoration_model is Non... | from modules import shared
class FaceRestoration:
def name(self):
return "None"
def restore(self, np_image):
FILL_FUNC_BODYdef restore_faces(np_image):
face_restorers = [x for x in shared.face_restorers if x.name() == shared.opts.face_restoration_model or shared.opts.face_restoration_model is Non... |
198 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/face_restoration_utils.py | 128,129 | 113,163 | send_model_to | CommonFaceRestoration | 129,137 | 129,137 | class CommonFaceRestoration(face_restoration.FaceRestoration):
net: torch.Module | None
model_url: str
model_download_name: str
def __init__(self, model_path: str):
super().__init__()
self.net = None
self.model_path = model_path
os.makedirs(model_path, exist_ok=True)
... | class CommonFaceRestoration(face_restoration.FaceRestoration):
net: torch.Module | None
model_url: str
model_download_name: str
def __init__(self, model_path: str):
super().__init__()
self.net = None
self.model_path = model_path
os.makedirs(model_path, exist_ok=True)
... | if self.net:
logger.debug("Sending %s to %s", self.net, device)
self.net.to(device)
if self.face_helper:
logger.debug("Sending face helper to %s", device)
self.face_helper.face_det.to(device)
self.face_helper.face_parse.to(device)
| if self.net:
logger.debug("Sending %s to %s", self.net, device)
self.net.to(device)
if self.face_helper:
logger.debug("Sending face helper to %s", device)
self.face_helper.face_det.to(device)
self.face_helper.face_parse.to(device)
| 19 | 423 | 103 | 526 | from __future__ import annotations
import logging
import os
from functools import cached_property
from typing import TYPE_CHECKING, Callable
import cv2
import numpy as np
import torch
from modules import devices, errors, face_restoration, shared
if TYPE_CHECKING:
from facexlib.utils.face_restoration_helper impo... | from __future__ import annotations
import logging
import os
from functools import cached_property
from typing import TYPE_CHECKING, Callable
import cv2
import numpy as np
import torch
from modules import devices, errors, face_restoration, shared
if TYPE_CHECKING:
from facexlib.utils.face_restoration_helper impo... |
199 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/fifo_lock.py | 12,13 | 6,38 | acquire | FIFOLock | 13,26 | 13,26 | class FIFOLock(object):
def __init__(self):
self._lock = threading.Lock()
self._inner_lock = threading.Lock()
self._pending_threads = collections.deque()
def acquire(self, blocking=True):
FILL_FUNC_BODY def release(self):
with self._inner_lock:
if self._pending_th... | class FIFOLock(object):
def __init__(self):
self._lock = threading.Lock()
self._inner_lock = threading.Lock()
self._pending_threads = collections.deque()
def acquire(self, blocking=True):
FILL_FUNC_BODY def release(self):
with self._inner_lock:
if self._pending_th... | with self._inner_lock:
lock_acquired = self._lock.acquire(False)
if lock_acquired:
return True
elif not blocking:
return False
release_event = threading.Event()
self._pending_threads.append(release_event)
relea... | with self._inner_lock:
lock_acquired = self._lock.acquire(False)
if lock_acquired:
return True
elif not blocking:
return False
release_event = threading.Event()
self._pending_threads.append(release_event)
relea... | 21 | 167 | 107 | 274 | import threading
import collections
# reference: https://gist.github.com/vitaliyp/6d54dd76ca2c3cdfc1149d33007dc34a
class FIFOLock(object):
def __init__(self):
self._lock = threading.Lock()
self._inner_lock = threading.Lock()
self._pending_threads = collections.deque()
def acquire(self... | import threading
import collections
# reference: https://gist.github.com/vitaliyp/6d54dd76ca2c3cdfc1149d33007dc34a
class FIFOLock(object):
def __init__(self):
self._lock = threading.Lock()
self._inner_lock = threading.Lock()
self._pending_threads = collections.deque()
def acquire(self... |
200 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/gfpgan_model.py | 63,64 | 1,72 | setup_model | 64,72 | 64,72 | from __future__ import annotations
import logging
import os
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFP... | from __future__ import annotations
import logging
import os
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFP... | global gfpgan_face_restorer
try:
face_restoration_utils.patch_facexlib(dirname)
gfpgan_face_restorer = FaceRestorerGFPGAN(model_path=dirname)
shared.face_restorers.append(gfpgan_face_restorer)
except Exception:
errors.report("Error setting up GFPGAN", exc_info=True)
| global gfpgan_face_restorer
try:
face_restoration_utils.patch_facexlib(dirname)
gfpgan_face_restorer = FaceRestorerGFPGAN(model_path=dirname)
shared.face_restorers.append(gfpgan_face_restorer)
except Exception:
errors.report("Error setting up GFPGAN", exc_info=True)
| 15 | 609 | 113 | 722 | from __future__ import annotations
import logging
import os
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFP... | from __future__ import annotations
import logging
import os
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFP... | |
201 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/gfpgan_model.py | 48,49 | 23,56 | restore | FaceRestorerGFPGAN | 49,56 | 49,56 | class FaceRestorerGFPGAN(face_restoration_utils.CommonFaceRestoration):
def name(self):
return "GFPGAN"
def get_device(self):
return devices.device_gfpgan
def load_net(self) -> torch.Module:
for model_path in modelloader.load_models(
model_path=self.model_path,
... | class FaceRestorerGFPGAN(face_restoration_utils.CommonFaceRestoration):
def name(self):
return "GFPGAN"
def get_device(self):
return devices.device_gfpgan
def load_net(self) -> torch.Module:
for model_path in modelloader.load_models(
model_path=self.model_path,
... | def restore_face(cropped_face_t):
assert self.net is not None
return self.net(cropped_face_t, return_rgb=False)[0]
return self.restore_with_helper(np_image, restore_face)
| def restore_face(cropped_face_t):
assert self.net is not None
return self.net(cropped_face_t, return_rgb=False)[0]
return self.restore_with_helper(np_image, restore_face)
| 13 | 292 | 78 | 370 | from __future__ import annotations
import logging
import os
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFP... | from __future__ import annotations
import logging
import os
import torch
from modules import (
devices,
errors,
face_restoration,
face_restoration_utils,
modelloader,
shared,
)
logger = logging.getLogger(__name__)
model_url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFP... |
202 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/gitpython_hack.py | 26,27 | 9,41 | stream_object_data | Git | 27,41 | 27,41 | class Git(git.Git):
"""
Git subclassed to never use persistent processes.
"""
def _get_persistent_cmd(self, attr_name, cmd_name, *args, **kwargs):
raise NotImplementedError(f"Refusing to use persistent process: {attr_name} ({cmd_name} {args} {kwargs})")
def get_object_header(self, ref: str... | class Git(git.Git):
"""
Git subclassed to never use persistent processes.
"""
def _get_persistent_cmd(self, attr_name, cmd_name, *args, **kwargs):
raise NotImplementedError(f"Refusing to use persistent process: {attr_name} ({cmd_name} {args} {kwargs})")
def get_object_header(self, ref: str... | # Not really streaming, per se; this buffers the entire object in memory.
# Shouldn't be a problem for our use case, since we're only using this for
# object headers (commit objects).
ret = subprocess.check_output(
[self.GIT_PYTHON_GIT_EXECUTABLE, "cat-file", "--batch"],
... | # Not really streaming, per se; this buffers the entire object in memory.
# Shouldn't be a problem for our use case, since we're only using this for
# object headers (commit objects).
ret = subprocess.check_output(
[self.GIT_PYTHON_GIT_EXECUTABLE, "cat-file", "--batch"],
... | 57 | 249 | 196 | 445 | from __future__ import annotations
import io
import subprocess
import git
class Git(git.Git):
"""
Git subclassed to never use persistent processes.
"""
def _get_persistent_cmd(self, attr_name, cmd_name, *args, **kwargs):
raise NotImplementedError(f"Refusing to use persistent process: {attr_... | from __future__ import annotations
import io
import subprocess
import git
class Git(git.Git):
"""
Git subclassed to never use persistent processes.
"""
def _get_persistent_cmd(self, attr_name, cmd_name, *args, **kwargs):
raise NotImplementedError(f"Refusing to use persistent process: {attr_... |
203 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/hashes.py | 11,12 | 1,85 | calculate_sha256 | 12,22 | 12,22 | import hashlib
import os.path
from modules import shared
import modules.cache
dump_cache = modules.cache.dump_cache
cache = modules.cache.cache
def calculate_sha256(filename):
FILL_FUNC_BODYdef sha256_from_cache(filename, title, use_addnet_hash=False):
hashes = cache("hashes-addnet") if use_addnet_hash else cac... | import hashlib
import os.path
from modules import shared
import modules.cache
dump_cache = modules.cache.dump_cache
cache = modules.cache.cache
def calculate_sha256(filename):
FILL_FUNC_BODYdef sha256_from_cache(filename, title, use_addnet_hash=False):
hashes = cache("hashes-addnet") if use_addnet_hash else cac... | hash_sha256 = hashlib.sha256()
blksize = 1024 * 1024
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(blksize), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()
| hash_sha256 = hashlib.sha256()
blksize = 1024 * 1024
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(blksize), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()
| 22 | 720 | 108 | 828 | import hashlib
import os.path
from modules import shared
import modules.cache
dump_cache = modules.cache.dump_cache
cache = modules.cache.cache
def calculate_sha256(filename):
FILL_FUNC_BODYdef sha256_from_cache(filename, title, use_addnet_hash=False):
hashes = cache("hashes-addnet") if use_addnet_hash else cac... | import hashlib
import os.path
from modules import shared
import modules.cache
dump_cache = modules.cache.dump_cache
cache = modules.cache.cache
def calculate_sha256(filename):
FILL_FUNC_BODYdef sha256_from_cache(filename, title, use_addnet_hash=False):
hashes = cache("hashes-addnet") if use_addnet_hash else cac... | |
204 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/hat_model.py | 22,23 | 10,44 | do_upscale | UpscalerHAT | 23,36 | 23,36 | class UpscalerHAT(Upscaler):
def __init__(self, dirname):
self.name = "HAT"
self.scalers = []
self.user_path = dirname
super().__init__()
for file in self.find_models(ext_filter=[".pt", ".pth"]):
name = modelloader.friendly_name(file)
scale = 4 # TODO... | class UpscalerHAT(Upscaler):
def __init__(self, dirname):
self.name = "HAT"
self.scalers = []
self.user_path = dirname
super().__init__()
for file in self.find_models(ext_filter=[".pt", ".pth"]):
name = modelloader.friendly_name(file)
scale = 4 # TODO... | try:
model = self.load_model(selected_model)
except Exception as e:
print(f"Unable to load HAT model {selected_model}: {e}", file=sys.stderr)
return img
model.to(devices.device_esrgan) # TODO: should probably be device_hat
return upscale_with_model(
... | try:
model = self.load_model(selected_model)
except Exception as e:
print(f"Unable to load HAT model {selected_model}: {e}", file=sys.stderr)
return img
model.to(devices.device_esrgan) # TODO: should probably be device_hat
return upscale_with_model(
... | 44 | 293 | 178 | 471 | import os
import sys
from modules import modelloader, devices
from modules.shared import opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerHAT(Upscaler):
def __init__(self, dirname):
self.name = "HAT"
self.scalers = []
... | import os
import sys
from modules import modelloader, devices
from modules.shared import opts
from modules.upscaler import Upscaler, UpscalerData
from modules.upscaler_utils import upscale_with_model
class UpscalerHAT(Upscaler):
def __init__(self, dirname):
self.name = "HAT"
self.scalers = []
... |
205 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/hypernetworks/ui.py | 11,12 | 1,39 | create_hypernetwork | 12,17 | 12,17 | import html
import gradio as gr
import modules.hypernetworks.hypernetwork
from modules import devices, sd_hijack, shared
not_available = ["hardswish", "multiheadattention"]
keys = [x for x in modules.hypernetworks.hypernetwork.HypernetworkModule.activation_dict if x not in not_available]
def create_hypernetwork(nam... | import html
import gradio as gr
import modules.hypernetworks.hypernetwork
from modules import devices, sd_hijack, shared
not_available = ["hardswish", "multiheadattention"]
keys = [x for x in modules.hypernetworks.hypernetwork.HypernetworkModule.activation_dict if x not in not_available]
def create_hypernetwork(nam... | filename = modules.hypernetworks.hypernetwork.create_hypernetwork(name, enable_sizes, overwrite_old, layer_structure, activation_func, weight_init, add_layer_norm, use_dropout, dropout_structure)
return gr.Dropdown.update(choices=sorted(shared.hypernetworks)), f"Created: {filename}", ""
| filename = modules.hypernetworks.hypernetwork.create_hypernetwork(name, enable_sizes, overwrite_old, layer_structure, activation_func, weight_init, add_layer_norm, use_dropout, dropout_structure)
return gr.Dropdown.update(choices=sorted(shared.hypernetworks)), f"Created: {filename}", ""
| 16 | 367 | 97 | 464 | import html
import gradio as gr
import modules.hypernetworks.hypernetwork
from modules import devices, sd_hijack, shared
not_available = ["hardswish", "multiheadattention"]
keys = [x for x in modules.hypernetworks.hypernetwork.HypernetworkModule.activation_dict if x not in not_available]
def create_hypernetwork(nam... | import html
import gradio as gr
import modules.hypernetworks.hypernetwork
from modules import devices, sd_hijack, shared
not_available = ["hardswish", "multiheadattention"]
keys = [x for x in modules.hypernetworks.hypernetwork.HypernetworkModule.activation_dict if x not in not_available]
def create_hypernetwork(nam... | |
208 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/images.py | 67,69 | 66,75 | tile_count | Grid | 72,75 | 69,75 | class Grid(namedtuple("_Grid", ["tiles", "tile_w", "tile_h", "image_w", "image_h", "overlap"])):
@property
def tile_count(self) -> int:
FILL_FUNC_BODY | class Grid(namedtuple("_Grid", ["tiles", "tile_w", "tile_h", "image_w", "image_h", "overlap"])):
@property
def tile_count(self) -> int:
"""
The total number of tiles in the grid.
"""
FILL_FUNC_BODY | return sum(len(row[2]) for row in self.tiles)
| """
The total number of tiles in the grid.
"""
return sum(len(row[2]) for row in self.tiles)
| 6 | 87 | 24 | 111 | from __future__ import annotations
import datetime
import functools
import pytz
import io
import math
import os
from collections import namedtuple
import re
import numpy as np
import piexif
import piexif.helper
from PIL import Image, ImageFont, ImageDraw, ImageColor, PngImagePlugin, ImageOps
# pillow_avif needs to be... | from __future__ import annotations
import datetime
import functools
import pytz
import io
import math
import os
from collections import namedtuple
import re
import numpy as np
import piexif
import piexif.helper
from PIL import Image, ImageFont, ImageDraw, ImageColor, PngImagePlugin, ImageOps
# pillow_avif needs to be... |
210 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/infotext_versions.py | 26,27 | 1,47 | backcompat | 28,47 | 27,47 | from modules import shared
from packaging import version
import re
v160 = version.parse("1.6.0")
v170_tsnr = version.parse("v1.7.0-225")
v180 = version.parse("1.8.0")
v180_hr_styles = version.parse("1.8.0-139")
def parse_version(text):
if text is None:
return None
m = re.match(r'([^-]+-[^-]+)-.*', ... | from modules import shared
from packaging import version
import re
v160 = version.parse("1.6.0")
v170_tsnr = version.parse("v1.7.0-225")
v180 = version.parse("1.8.0")
v180_hr_styles = version.parse("1.8.0-139")
def parse_version(text):
if text is None:
return None
m = re.match(r'([^-]+-[^-]+)-.*', ... |
if not shared.opts.auto_backcompat:
return
ver = parse_version(d.get("Version"))
if ver is None:
return
if ver < v160 and '[' in d.get('Prompt', ''):
d["Old prompt editing timelines"] = True
if ver < v160 and d.get('Sampler', '') in ('DDIM', 'PLMS'):
d["Pad conds ... | """Checks infotext Version field, and enables backwards compatibility options according to it."""
if not shared.opts.auto_backcompat:
return
ver = parse_version(d.get("Version"))
if ver is None:
return
if ver < v160 and '[' in d.get('Prompt', ''):
d["Old prompt editing tim... | 63 | 221 | 201 | 422 | from modules import shared
from packaging import version
import re
v160 = version.parse("1.6.0")
v170_tsnr = version.parse("v1.7.0-225")
v180 = version.parse("1.8.0")
v180_hr_styles = version.parse("1.8.0-139")
def parse_version(text):
if text is None:
return None
m = re.match(r'([^-]+-[^-]+)-.*', ... | from modules import shared
from packaging import version
import re
v160 = version.parse("1.6.0")
v170_tsnr = version.parse("v1.7.0-225")
v180 = version.parse("1.8.0")
v180_hr_styles = version.parse("1.8.0-139")
def parse_version(text):
if text is None:
return None
m = re.match(r'([^-]+-[^-]+)-.*', ... | |
211 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/initialize.py | 78,79 | 1,170 | initialize_rest | 82,170 | 79,170 | import importlib
import logging
import os
import sys
import warnings
from threading import Thread
from modules.timer import startup_timer
def imports():
logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR) # sshh...
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is no... | import importlib
import logging
import os
import sys
import warnings
from threading import Thread
from modules.timer import startup_timer
def imports():
logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR) # sshh...
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is no... | from modules.shared_cmd_options import cmd_opts
from modules import sd_samplers
sd_samplers.set_samplers()
startup_timer.record("set samplers")
from modules import extensions
extensions.list_extensions()
startup_timer.record("list extensions")
from modules import initialize_util
i... | """
Called both from initialize() and when reloading the webui.
"""
from modules.shared_cmd_options import cmd_opts
from modules import sd_samplers
sd_samplers.set_samplers()
startup_timer.record("set samplers")
from modules import extensions
extensions.list_extensions()
startu... | 205 | 834 | 1,004 | 1,838 | import importlib
import logging
import os
import sys
import warnings
from threading import Thread
from modules.timer import startup_timer
def imports():
logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR) # sshh...
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is no... | import importlib
import logging
import os
import sys
import warnings
from threading import Thread
from modules.timer import startup_timer
def imports():
logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR) # sshh...
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is no... | |
213 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/initialize_util.py | 61,62 | 54,72 | get_event_loop | AnyThreadEventLoopPolicy | 62,72 | 62,72 | class AnyThreadEventLoopPolicy(_BasePolicy): # type: ignore
"""Event loop policy that allows loop creation on any thread.
Usage::
asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
"""
def get_event_loop(self) -> asyncio.AbstractEventLoop:
FILL_FUNC_BODY | class AnyThreadEventLoopPolicy(_BasePolicy): # type: ignore
"""Event loop policy that allows loop creation on any thread.
Usage::
asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
"""
def get_event_loop(self) -> asyncio.AbstractEventLoop:
FILL_FUNC_BODY | try:
return super().get_event_loop()
except (RuntimeError, AssertionError):
# This was an AssertionError in python 3.4.2 (which ships with debian jessie)
# and changed to a RuntimeError in 3.4.3.
# "There is no current event loop in... | try:
return super().get_event_loop()
except (RuntimeError, AssertionError):
# This was an AssertionError in python 3.4.2 (which ships with debian jessie)
# and changed to a RuntimeError in 3.4.3.
# "There is no current event loop in... | 43 | 90 | 124 | 214 | import json
import os
import signal
import sys
import re
from modules.timer import startup_timer
def gradio_server_name():
from modules.shared_cmd_options import cmd_opts
if cmd_opts.server_name:
return cmd_opts.server_name
else:
return "0.0.0.0" if cmd_opts.listen else None
def fix_to... | import json
import os
import signal
import sys
import re
from modules.timer import startup_timer
def gradio_server_name():
from modules.shared_cmd_options import cmd_opts
if cmd_opts.server_name:
return cmd_opts.server_name
else:
return "0.0.0.0" if cmd_opts.listen else None
def fix_to... |
217 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/localization.py | 26,27 | 1,38 | localization_js | 27,38 | 27,38 | import json
import os
from modules import errors, scripts
localizations = {}
def list_localizations(dirname):
localizations.clear()
for file in os.listdir(dirname):
fn, ext = os.path.splitext(file)
if ext.lower() != ".json":
continue
localizations[fn] = [os.path.join(di... | import json
import os
from modules import errors, scripts
localizations = {}
def list_localizations(dirname):
localizations.clear()
for file in os.listdir(dirname):
fn, ext = os.path.splitext(file)
if ext.lower() != ".json":
continue
localizations[fn] = [os.path.join(di... | fns = localizations.get(current_localization_name, None)
data = {}
if fns is not None:
for fn in fns:
try:
with open(fn, "r", encoding="utf8") as file:
data.update(json.load(file))
except Exception:
errors.report(f"Error loa... | fns = localizations.get(current_localization_name, None)
data = {}
if fns is not None:
for fn in fns:
try:
with open(fn, "r", encoding="utf8") as file:
data.update(json.load(file))
except Exception:
errors.report(f"Error loa... | 36 | 205 | 135 | 340 | import json
import os
from modules import errors, scripts
localizations = {}
def list_localizations(dirname):
localizations.clear()
for file in os.listdir(dirname):
fn, ext = os.path.splitext(file)
if ext.lower() != ".json":
continue
localizations[fn] = [os.path.join(di... | import json
import os
from modules import errors, scripts
localizations = {}
def list_localizations(dirname):
localizations.clear()
for file in os.listdir(dirname):
fn, ext = os.path.splitext(file)
if ext.lower() != ".json":
continue
localizations[fn] = [os.path.join(di... | |
218 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/logging_config.py | 28,29 | 1,59 | setup_logging | 29,59 | 29,59 | import logging
import os
try:
from tqdm import tqdm
class TqdmLoggingHandler(logging.Handler):
def __init__(self, fallback_handler: logging.Handler):
super().__init__()
self.fallback_handler = fallback_handler
def emit(self, record):
try:
#... | import logging
import os
try:
from tqdm import tqdm
class TqdmLoggingHandler(logging.Handler):
def __init__(self, fallback_handler: logging.Handler):
super().__init__()
self.fallback_handler = fallback_handler
def emit(self, record):
try:
#... | if loglevel is None:
loglevel = os.environ.get("SD_WEBUI_LOG_LEVEL")
if not loglevel:
return
if logging.root.handlers:
# Already configured, do not interfere
return
formatter = logging.Formatter(
'%(asctime)s %(levelname)s [%(name)s] %(message)s',
'%Y-%... | if loglevel is None:
loglevel = os.environ.get("SD_WEBUI_LOG_LEVEL")
if not loglevel:
return
if logging.root.handlers:
# Already configured, do not interfere
return
formatter = logging.Formatter(
'%(asctime)s %(levelname)s [%(name)s] %(message)s',
'%Y-%... | 59 | 207 | 303 | 510 | import logging
import os
try:
from tqdm import tqdm
class TqdmLoggingHandler(logging.Handler):
def __init__(self, fallback_handler: logging.Handler):
super().__init__()
self.fallback_handler = fallback_handler
def emit(self, record):
try:
#... | import logging
import os
try:
from tqdm import tqdm
class TqdmLoggingHandler(logging.Handler):
def __init__(self, fallback_handler: logging.Handler):
super().__init__()
self.fallback_handler = fallback_handler
def emit(self, record):
try:
#... | |
219 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/logging_config.py | 13,14 | 8,24 | emit | TqdmLoggingHandler | 14,24 | 14,24 | class TqdmLoggingHandler(logging.Handler):
def __init__(self, fallback_handler: logging.Handler):
super().__init__()
self.fallback_handler = fallback_handler
def emit(self, record):
FILL_FUNC_BODY | class TqdmLoggingHandler(logging.Handler):
def __init__(self, fallback_handler: logging.Handler):
super().__init__()
self.fallback_handler = fallback_handler
def emit(self, record):
FILL_FUNC_BODY | try:
# If there are active tqdm progress bars,
# attempt to not interfere with them.
if tqdm._instances:
tqdm.write(self.format(record))
else:
self.fallback_handler.emit(record)
except Excepti... | try:
# If there are active tqdm progress bars,
# attempt to not interfere with them.
if tqdm._instances:
tqdm.write(self.format(record))
else:
self.fallback_handler.emit(record)
except Excepti... | 24 | 72 | 97 | 169 | import logging
import os
try:
from tqdm import tqdm
class TqdmLoggingHandler(logging.Handler):
def __init__(self, fallback_handler: logging.Handler):
super().__init__()
self.fallback_handler = fallback_handler
def emit(self, record):
FILL_FUNC_BODYexcept ImportError:
... | import logging
import os
try:
from tqdm import tqdm
class TqdmLoggingHandler(logging.Handler):
def __init__(self, fallback_handler: logging.Handler):
super().__init__()
self.fallback_handler = fallback_handler
def emit(self, record):
FILL_FUNC_BODYexcept ImportError:
... |
220 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/lowvram.py | 31,32 | 1,148 | setup_for_low_vram | 32,146 | 32,146 | import torch
from modules import devices, shared
module_in_gpu = None
cpu = torch.device("cpu")
def send_everything_to_cpu():
global module_in_gpu
if module_in_gpu is not None:
module_in_gpu.to(cpu)
module_in_gpu = None
def is_needed(sd_model):
return shared.cmd_opts.lowvram or shared.cmd... | import torch
from modules import devices, shared
module_in_gpu = None
cpu = torch.device("cpu")
def send_everything_to_cpu():
global module_in_gpu
if module_in_gpu is not None:
module_in_gpu.to(cpu)
module_in_gpu = None
def is_needed(sd_model):
return shared.cmd_opts.lowvram or shared.cmd... | if getattr(sd_model, 'lowvram', False):
return
sd_model.lowvram = True
parents = {}
def send_me_to_gpu(module, _):
"""send this module to GPU; send whatever tracked module was previous in GPU to CPU;
we add this as forward_pre_hook to a lot of modules and this way all but one ... | if getattr(sd_model, 'lowvram', False):
return
sd_model.lowvram = True
parents = {}
def send_me_to_gpu(module, _):
"""send this module to GPU; send whatever tracked module was previous in GPU to CPU;
we add this as forward_pre_hook to a lot of modules and this way all but one ... | 338 | 283 | 1,646 | 1,929 | import torch
from modules import devices, shared
module_in_gpu = None
cpu = torch.device("cpu")
def send_everything_to_cpu():
global module_in_gpu
if module_in_gpu is not None:
module_in_gpu.to(cpu)
module_in_gpu = None
def is_needed(sd_model):
return shared.cmd_opts.lowvram or shared.cmd... | import torch
from modules import devices, shared
module_in_gpu = None
cpu = torch.device("cpu")
def send_everything_to_cpu():
global module_in_gpu
if module_in_gpu is not None:
module_in_gpu.to(cpu)
module_in_gpu = None
def is_needed(sd_model):
return shared.cmd_opts.lowvram or shared.cmd... | |
221 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/mac_specific.py | 33,34 | 1,99 | torch_mps_gc | 34,45 | 34,45 | import logging
import torch
from torch import Tensor
import platform
from modules.sd_hijack_utils import CondFunc
from packaging import version
from modules import shared
log = logging.getLogger(__name__)
# before torch version 1.13, has_mps is only available in nightly pytorch and macOS 12.3+,
# use check `getattr... | import logging
import torch
from torch import Tensor
import platform
from modules.sd_hijack_utils import CondFunc
from packaging import version
from modules import shared
log = logging.getLogger(__name__)
# before torch version 1.13, has_mps is only available in nightly pytorch and macOS 12.3+,
# use check `getattr... | try:
if shared.state.current_latent is not None:
log.debug("`current_latent` is set, skipping MPS garbage collection")
return
from torch.mps import empty_cache
empty_cache()
except Exception:
log.warning("MPS garbage collection failed", exc_info=True)
# ... | try:
if shared.state.current_latent is not None:
log.debug("`current_latent` is set, skipping MPS garbage collection")
return
from torch.mps import empty_cache
empty_cache()
except Exception:
log.warning("MPS garbage collection failed", exc_info=True)
# ... | 31 | 1,906 | 125 | 2,031 | import logging
import torch
from torch import Tensor
import platform
from modules.sd_hijack_utils import CondFunc
from packaging import version
from modules import shared
log = logging.getLogger(__name__)
# before torch version 1.13, has_mps is only available in nightly pytorch and macOS 12.3+,
# use check `getattr... | import logging
import torch
from torch import Tensor
import platform
from modules.sd_hijack_utils import CondFunc
from packaging import version
from modules import shared
log = logging.getLogger(__name__)
# before torch version 1.13, has_mps is only available in nightly pytorch and macOS 12.3+,
# use check `getattr... | |
222 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/memmon.py | 75,76 | 8,93 | read | MemUsageMonitor | 76,90 | 76,90 | class MemUsageMonitor(threading.Thread):
run_flag = None
device = None
disabled = False
opts = None
data = None
def __init__(self, name, device, opts):
threading.Thread.__init__(self)
self.name = name
self.device = device
self.opts = opts
self.daemon = T... | class MemUsageMonitor(threading.Thread):
run_flag = None
device = None
disabled = False
opts = None
data = None
def __init__(self, name, device, opts):
threading.Thread.__init__(self)
self.name = name
self.device = device
self.opts = opts
self.daemon = T... | if not self.disabled:
free, total = self.cuda_mem_get_info()
self.data["free"] = free
self.data["total"] = total
torch_stats = torch.cuda.memory_stats(self.device)
self.data["active"] = torch_stats["active.all.current"]
self.data["active_p... | if not self.disabled:
free, total = self.cuda_mem_get_info()
self.data["free"] = free
self.data["total"] = total
torch_stats = torch.cuda.memory_stats(self.device)
self.data["active"] = torch_stats["active.all.current"]
self.data["active_p... | 35 | 661 | 204 | 865 | import threading
import time
from collections import defaultdict
import torch
class MemUsageMonitor(threading.Thread):
run_flag = None
device = None
disabled = False
opts = None
data = None
def __init__(self, name, device, opts):
threading.Thread.__init__(self)
self.name = na... | import threading
import time
from collections import defaultdict
import torch
class MemUsageMonitor(threading.Thread):
run_flag = None
device = None
disabled = False
opts = None
data = None
def __init__(self, name, device, opts):
threading.Thread.__init__(self)
self.name = na... |
223 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/modelloader.py | 20,27 | 1,170 | load_file_from_url | 31,43 | 27,43 | from __future__ import annotations
import importlib
import logging
import os
from typing import TYPE_CHECKING
from urllib.parse import urlparse
import torch
from modules import shared
from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone
if TYPE_CHECKING:
import spandrel
logger ... | from __future__ import annotations
import importlib
import logging
import os
from typing import TYPE_CHECKING
from urllib.parse import urlparse
import torch
from modules import shared
from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone
if TYPE_CHECKING:
import spandrel
logger ... | os.makedirs(model_dir, exist_ok=True)
if not file_name:
parts = urlparse(url)
file_name = os.path.basename(parts.path)
cached_file = os.path.abspath(os.path.join(model_dir, file_name))
if not os.path.exists(cached_file):
print(f'Downloading: "{url}" to {cached_file}\n')
f... | """Download a file from `url` into `model_dir`, using the file present if possible.
Returns the path to the downloaded file.
"""
os.makedirs(model_dir, exist_ok=True)
if not file_name:
parts = urlparse(url)
file_name = os.path.basename(parts.path)
cached_file = os.path.abspath(o... | 31 | 1,711 | 173 | 1,884 | from __future__ import annotations
import importlib
import logging
import os
from typing import TYPE_CHECKING
from urllib.parse import urlparse
import torch
from modules import shared
from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone
if TYPE_CHECKING:
import spandrel
logger ... | from __future__ import annotations
import importlib
import logging
import os
from typing import TYPE_CHECKING
from urllib.parse import urlparse
import torch
from modules import shared
from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone
if TYPE_CHECKING:
import spandrel
logger ... | |
226 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/models/diffusion/ddpm_edit.py | 1417,1418 | 1410,1439 | forward | DiffusionWrapper | 1418,1439 | 1418,1439 | class DiffusionWrapper(pl.LightningModule):
def __init__(self, diff_model_config, conditioning_key):
super().__init__()
self.diffusion_model = instantiate_from_config(diff_model_config)
self.conditioning_key = conditioning_key
assert self.conditioning_key in [None, 'concat', 'crossat... | class DiffusionWrapper(pl.LightningModule):
def __init__(self, diff_model_config, conditioning_key):
super().__init__()
self.diffusion_model = instantiate_from_config(diff_model_config)
self.conditioning_key = conditioning_key
assert self.conditioning_key in [None, 'concat', 'crossat... | if self.conditioning_key is None:
out = self.diffusion_model(x, t)
elif self.conditioning_key == 'concat':
xc = torch.cat([x] + c_concat, dim=1)
out = self.diffusion_model(xc, t)
elif self.conditioning_key == 'crossattn':
cc = torch.cat(c_crossattn... | if self.conditioning_key is None:
out = self.diffusion_model(x, t)
elif self.conditioning_key == 'concat':
xc = torch.cat([x] + c_concat, dim=1)
out = self.diffusion_model(xc, t)
elif self.conditioning_key == 'crossattn':
cc = torch.cat(c_crossattn... | 71 | 140 | 285 | 425 | """
wild mixture of
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
https... | """
wild mixture of
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
https... |
228 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/models/diffusion/ddpm_edit.py | 1445,1446 | 1439,1461 | log_images | Layout2ImgDiffusion | 1446,1461 | 1446,1461 | class Layout2ImgDiffusion(LatentDiffusion):
# TODO: move all layout-specific hacks to this class
def __init__(self, cond_stage_key, *args, **kwargs):
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
super().__init__(*args, cond_stage_k... | class Layout2ImgDiffusion(LatentDiffusion):
# TODO: move all layout-specific hacks to this class
def __init__(self, cond_stage_key, *args, **kwargs):
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
super().__init__(*args, cond_stage_k... | logs = super().log_images(*args, batch=batch, N=N, **kwargs)
key = 'train' if self.training else 'validation'
dset = self.trainer.datamodule.datasets[key]
mapper = dset.conditional_builders[self.cond_stage_key]
bbox_imgs = []
map_fn = lambda catno: dset.get_textual_labe... | logs = super().log_images(*args, batch=batch, N=N, **kwargs)
key = 'train' if self.training else 'validation'
dset = self.trainer.datamodule.datasets[key]
mapper = dset.conditional_builders[self.cond_stage_key]
bbox_imgs = []
map_fn = lambda catno: dset.get_textual_labe... | 47 | 145 | 255 | 400 | """
wild mixture of
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
https... | """
wild mixture of
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
https... |
229 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/models/diffusion/uni_pc/sampler.py | 18,19 | 9,102 | register_buffer | UniPCSampler | 19,24 | 19,24 | class UniPCSampler(object):
def __init__(self, model, **kwargs):
super().__init__()
self.model = model
to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device)
self.before_sample = None
self.after_sample = None
self.register_buffer('alphas_cumprod', ... | class UniPCSampler(object):
def __init__(self, model, **kwargs):
super().__init__()
self.model = model
to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device)
self.before_sample = None
self.after_sample = None
self.register_buffer('alphas_cumprod', ... | if type(attr) == torch.Tensor:
if attr.device != devices.device:
attr = attr.to(devices.device)
setattr(self, name, attr)
| if type(attr) == torch.Tensor:
if attr.device != devices.device:
attr = attr.to(devices.device)
setattr(self, name, attr)
| 14 | 1,076 | 55 | 1,131 | """SAMPLING ONLY."""
import torch
from .uni_pc import NoiseScheduleVP, model_wrapper, UniPC
from modules import shared, devices
class UniPCSampler(object):
def __init__(self, model, **kwargs):
super().__init__()
self.model = model
to_torch = lambda x: x.clone().detach().to(torch.float32)... | """SAMPLING ONLY."""
import torch
from .uni_pc import NoiseScheduleVP, model_wrapper, UniPC
from modules import shared, devices
class UniPCSampler(object):
def __init__(self, model, **kwargs):
super().__init__()
self.model = model
to_torch = lambda x: x.clone().detach().to(torch.float32)... |
233 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/ngrok.py | 4,5 | 1,31 | connect | 5,31 | 5,31 | import ngrok
# Connect to ngrok for ingress
def connect(token, port, options):
FILL_FUNC_BODY | import ngrok
# Connect to ngrok for ingress
def connect(token, port, options):
FILL_FUNC_BODY | account = None
if token is None:
token = 'None'
else:
if ':' in token:
# token = authtoken:username:password
token, username, password = token.split(':', 2)
account = f"{username}:{password}"
# For all options see: https://github.com/ngrok/ngrok-py/bl... | account = None
if token is None:
token = 'None'
else:
if ':' in token:
# token = authtoken:username:password
token, username, password = token.split(':', 2)
account = f"{username}:{password}"
# For all options see: https://github.com/ngrok/ngrok-py/bl... | 95 | 36 | 368 | 404 | import ngrok
# Connect to ngrok for ingress
def connect(token, port, options):
FILL_FUNC_BODY | import ngrok
# Connect to ngrok for ingress
def connect(token, port, options):
FILL_FUNC_BODY | |
234 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/npu_specific.py | 7,8 | 1,32 | check_for_npu | 8,20 | 8,20 | import importlib
import torch
from modules import shared
def check_for_npu():
FILL_FUNC_BODYdef get_npu_device_string():
if shared.cmd_opts.device_id is not None:
return f"npu:{shared.cmd_opts.device_id}"
return "npu:0"
def torch_npu_gc():
with torch.npu.device(get_npu_device_string()):
... | import importlib
import torch
from modules import shared
def check_for_npu():
FILL_FUNC_BODYdef get_npu_device_string():
if shared.cmd_opts.device_id is not None:
return f"npu:{shared.cmd_opts.device_id}"
return "npu:0"
def torch_npu_gc():
with torch.npu.device(get_npu_device_string()):
... | if importlib.util.find_spec("torch_npu") is None:
return False
import torch_npu
try:
# Will raise a RuntimeError if no NPU is found
_ = torch_npu.npu.device_count()
return torch.npu.is_available()
except RuntimeError:
return False
| if importlib.util.find_spec("torch_npu") is None:
return False
import torch_npu
try:
# Will raise a RuntimeError if no NPU is found
_ = torch_npu.npu.device_count()
return torch.npu.is_available()
except RuntimeError:
return False
| 28 | 151 | 106 | 257 | import importlib
import torch
from modules import shared
def check_for_npu():
FILL_FUNC_BODYdef get_npu_device_string():
if shared.cmd_opts.device_id is not None:
return f"npu:{shared.cmd_opts.device_id}"
return "npu:0"
def torch_npu_gc():
with torch.npu.device(get_npu_device_string()):
... | import importlib
import torch
from modules import shared
def check_for_npu():
FILL_FUNC_BODYdef get_npu_device_string():
if shared.cmd_opts.device_id is not None:
return f"npu:{shared.cmd_opts.device_id}"
return "npu:0"
def torch_npu_gc():
with torch.npu.device(get_npu_device_string()):
... | |
236 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/options.py | 56,57 | 13,61 | needs_reload_ui | OptionInfo | 57,61 | 57,61 | class OptionInfo:
def __init__(self, default=None, label="", component=None, component_args=None, onchange=None, section=None, refresh=None, comment_before='', comment_after='', infotext=None, restrict_api=False, category_id=None):
self.default = default
self.label = label
self.component = c... | class OptionInfo:
def __init__(self, default=None, label="", component=None, component_args=None, onchange=None, section=None, refresh=None, comment_before='', comment_after='', infotext=None, restrict_api=False, category_id=None):
self.default = default
self.label = label
self.component = c... | self.comment_after += " <span class='info'>(requires Reload UI)</span>"
return self
| self.comment_after += " <span class='info'>(requires Reload UI)</span>"
return self
| 9 | 470 | 39 | 509 | import os
import json
import sys
from dataclasses import dataclass
import gradio as gr
from modules import errors
from modules.shared_cmd_options import cmd_opts
from modules.paths_internal import script_path
class OptionInfo:
def __init__(self, default=None, label="", component=None, component_args=None, oncha... | import os
import json
import sys
from dataclasses import dataclass
import gradio as gr
from modules import errors
from modules.shared_cmd_options import cmd_opts
from modules.paths_internal import script_path
class OptionInfo:
def __init__(self, default=None, label="", component=None, component_args=None, oncha... |
238 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/options.py | 329,330 | 325,336 | register_category | OptionsCategories | 330,336 | 330,336 | class OptionsCategories:
def __init__(self):
self.mapping = {}
def register_category(self, category_id, label):
FILL_FUNC_BODY | class OptionsCategories:
def __init__(self):
self.mapping = {}
def register_category(self, category_id, label):
FILL_FUNC_BODY | if category_id in self.mapping:
return category_id
self.mapping[category_id] = OptionsCategory(category_id, label)
| if category_id in self.mapping:
return category_id
self.mapping[category_id] = OptionsCategory(category_id, label)
| 10 | 47 | 46 | 93 | import os
import json
import sys
from dataclasses import dataclass
import gradio as gr
from modules import errors
from modules.shared_cmd_options import cmd_opts
from modules.paths_internal import script_path
class OptionInfo:
def __init__(self, default=None, label="", component=None, component_args=None, oncha... | import os
import json
import sys
from dataclasses import dataclass
import gradio as gr
from modules import errors
from modules.shared_cmd_options import cmd_opts
from modules.paths_internal import script_path
class OptionInfo:
def __init__(self, default=None, label="", component=None, component_args=None, oncha... |
239 | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui | /home/hieuvd/dung_repo/raw/stars_01/AUTOMATIC1111_stable-diffusion-webui/stable-diffusion-webui/modules/patches.py | 4,5 | 1,65 | patch | 19,32 | 5,32 | from collections import defaultdict
def patch(key, obj, field, replacement):
FILL_FUNC_BODYdef undo(key, obj, field):
"""Undoes the peplacement by the patch().
If the function is not replaced, raises an exception.
Arguments:
key: identifying information for who is doing the replacement. You can ... | from collections import defaultdict
def patch(key, obj, field, replacement):
"""Replaces a function in a module or a class.
Also stores the original function in this module, possible to be retrieved via original(key, obj, field).
If the function is already replaced by this caller (key), an exception is r... |
patch_key = (obj, field)
if patch_key in originals[key]:
raise RuntimeError(f"patch for {field} is already applied")
original_func = getattr(obj, field)
originals[key][patch_key] = original_func
setattr(obj, field, replacement)
return original_func
| """Replaces a function in a module or a class.
Also stores the original function in this module, possible to be retrieved via original(key, obj, field).
If the function is already replaced by this caller (key), an exception is raised -- use undo() before that.
Arguments:
key: identifying infor... | 27 | 409 | 104 | 513 | from collections import defaultdict
def patch(key, obj, field, replacement):
FILL_FUNC_BODYdef undo(key, obj, field):
"""Undoes the peplacement by the patch().
If the function is not replaced, raises an exception.
Arguments:
key: identifying information for who is doing the replacement. You can ... | from collections import defaultdict
def patch(key, obj, field, replacement):
"""Replaces a function in a module or a class.
Also stores the original function in this module, possible to be retrieved via original(key, obj, field).
If the function is already replaced by this caller (key), an exception is r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.