Linaqruf / sd-notebook-collection

210 stars 43 forks source link

list index out of range problem happened plz help #82

Open andersenryu opened 11 months ago

andersenryu commented 11 months ago

@title ## Start Cagliostro Colab UI

import random import string from pydantic import BaseModel from typing import List, Optional from colablib.utils import config_utils from colablib.colored_print import cprint, print_line from colablib.utils.git_utils import validate_repo

%store -r

################################

COLAB ARGUMENTS GOES HERE

################################

@markdown ### Alternative Tunnel

@markdown > Recommended Tunnels: ngrok > gradio > cloudflared > remotemoe > localhostrun > googleusercontent

select_tunnel = "multiple" # @param ['gradio', 'multiple','cloudflared', 'localhostrun', 'remotemoe', "googleusercontent"]

@markdown > Get your ngrok_token here

ngrok_token = "2RZ1hgOyiVHaNK4X4aY6dxu23pH_kAuj6owhSMV9j8dP32rw" # @param {type: 'string'} ngrok_region = "us" # @param ["us", "eu", "au", "ap", "sa", "jp", "in"]

@markdown ### UI/UX Config

select_theme = "minimal_orange" # @param ['moonlight', 'ogxRed', 'fun', 'ogxCyan', 'ogxCyanInvert', 'ogxBGreen', 'default_orange', 'tron2', 'd-230-52-94', 'minimal', 'ogxRedYellow', 'retrog', 'ogxRedPurple', 'ogxGreen', 'tron', 'default_cyan', 'default', 'backup', 'minimal_orange', 'Golde']

@markdown Set use_preset for using default prompt, resolution, sampler, and other settings

use_presets = True # @param {type: 'boolean'}

@markdown ### Arguments

use_gradio_auth = False # @param {type: 'boolean'} accelerator = "opt-sdp-attention" # @param ['xformers', 'opt-sdp-attention', 'opt-sdp-no-mem-attention', 'opt-split-attention'] auto_select_model = False # @param {type: 'boolean'} auto_select_vae = True # @param {type: 'boolean'} additional_arguments = "--lowram --theme dark --no-half-vae" #@param {type: 'string'}

GRADIO AUTH

user = "cagliostro" password = "".join(random.choices(string.ascii_letters + string.digits, k=6))

def change_theme(filename): themes_folder = os.path.join(repo_dir, "extensions-builtin", "sd_theme_editor", "themes") themes_file = os.path.join(themes_folder, f"{filename}.css")

style_config    = config_utils.read_config(style_path)
style_contents  = style_config.split("/*BREAKPOINT_CSS_CONTENT*/")[1]

theme_config    = config_utils.read_config(themes_file)
style_data      = ":host{" + theme_config + "}" + "/*BREAKPOINT_CSS_CONTENT*/" + style_contents
config_utils.write_config(style_path, style_data)

def is_valid(valid_dir, file_types): return [f for f in os.listdir(valid_dir) if f.endswith(file_types)]

def auto_select_file(valid_dir, config_key, file_types): valid_files = is_valid(valid_dir, file_types) if valid_files: file_path = random.choice(valid_files) if os.path.exists(os.path.join(valid_dir, file_path)): config = config_utils.read_config(config_file) config[config_key] = file_path config_utils.write_config(config_file, config) return file_path else: return None

def ui_preset_config(): global default_upscaler, default_sampler_v2

default_prompt        = "masterpiece, best quality,"
default_neg_prompt    = "(worst quality, low quality:1.4)"
default_sampler       = "DPM++ 2M Karras"
default_steps         = 20
default_width         = 512
default_height        = 768
default_strength      = 0.55
default_cfg_scale     = 7
default_upscaler       = "Latent (nearest-exact)"

config = {
    "Prompt/value"              : default_prompt,
    "Negative prompt/value"     : default_neg_prompt,
    "Sampling method/value"     : default_sampler,
    "Sampling steps/value"      : default_steps,
    "Width/value"               : default_width,
    "Height/value"              : default_height,
    "Denoising strength/value"  : default_strength,
    "CFG Scale/value"           : default_cfg_scale
}

return config

def configure_main_settings(config_file: str, lora_dir: str, use_presets: bool, ui_config_file: str): config = config_utils.read_config(config_file)

config["additional_networks_extra_lora_path"] = lora_dir
config["CLIP_stop_at_last_layers"] = 2
config["eta_noise_seed_delta"] = 0
config["show_progress_every_n_steps"] = 10
config["show_progressbar"] = True
config["samples_filename_pattern"] = "[model_name]_[seed]"
config["show_progress_type"] = "Approx NN" # Full, Approx NN, TAESD, Approx cheap
config["live_preview_content"] = "Prompt" # Combined, Prompt, Negative Prompt
config["hires_fix_show_sampler"] = True
config["hires_fix_show_prompts"] = True
config["state"] = ["tabs"]
config["state_txt2img"] = ["prompt", "negative_prompt", "styles", "sampling", "sampling_steps", "width", "height", "batch_count", "batch_size", "hires_resize_y", "hires_resize_x", "hires_scale", "hires_steps", "hires_upscaler", "hires_fix", "tiling", "restore_faces", "cfg_scale", "hires_denoising_strength"]
config["state_img2img"] = ["prompt", "negative_prompt", "styles", "sampling", "resize_mode", "sampling_steps", "tiling", "restore_faces", "width", "height", "batch_count", "batch_size", "cfg_scale", "denoising_strength"]
config["state_extensions"] = ["control-net"]

quicksettings_values = ["sd_model_checkpoint", "sd_vae", "CLIP_stop_at_last_layers",
                        "use_old_karras_scheduler_sigmas", "always_discard_next_to_last_sigma",
                        "token_merging_ratio", "s_min_uncond"]

if "quicksettings" in config:
    config["quicksettings"] = ", ".join(quicksettings_values)
elif "quicksettings_list" in config:
    config["quicksettings_list"] = quicksettings_values

config_utils.write_config(config_file, config)

if use_presets:
    configure_ui_settings(ui_config_file)

def configure_ui_settings(ui_config_file: str): config = config_utils.read_config(ui_config_file) preset_config = ui_preset_config() for key in ["txt2img", "img2img"]: for subkey, value in preset_config.items(): config[f"{key}/{subkey}"] = value

config["txt2img/Upscaler/value"] = default_upscaler
config_utils.write_config(ui_config_file, config)

def is_dir_exist(cloned_dir, original_dir): if os.path.exists(cloned_dir): return cloned_dir else: return original_dir

def parseargs(config): args = "" for k, v in config.items(): if k.startswith(""): args += f'"{v}" ' elif isinstance(v, str): args += f'--{k}="{v}" ' elif isinstance(v, bool) and v: args += f"--{k} " elif isinstance(v, float) and not isinstance(v, bool): args += f"--{k}={v} " elif isinstance(v, int) and not isinstance(v, bool): args += f"--{k}={v} "

return args

def main(): global auto_select_model, auto_select_vae

repo_name, _, _ = validate_repo(repo_dir)
if "anapnoe" in repo_name:
    change_theme(select_theme)

valid_ckpt_dir          = is_dir_exist(os.path.join(fused_dir, "model"), models_dir)
valid_vae_dir           = is_dir_exist(os.path.join(fused_dir, "vae"), vaes_dir)
valid_embedding_dir     = is_dir_exist(os.path.join(fused_dir, "embedding"), embeddings_dir)
valid_lora_dir          = is_dir_exist(os.path.join(fused_dir, "lora"), lora_dir)
valid_hypernetwork_dir  = is_dir_exist(os.path.join(fused_dir, "hypernetwork"), hypernetworks_dir)

print_line(80, color="green")
cprint(f"Launching '{repo_name}'", color="flat_yellow")
print_line(80, color="green")

if not is_valid(valid_ckpt_dir, ('.ckpt', '.safetensors')):
    cprint(f"No checkpoints were found in the directory '{valid_ckpt_dir}'.", color="yellow")
    url = "https://huggingface.co/Linaqruf/stolen/resolve/main/fp16/aamAnyloraAnimeMixAnime_v10-fp16-pruned.safetensors"
    filename = "AnyLoRA_Anime_mix.safetensors"
    aria2_download(url=url, download_dir=valid_ckpt_dir, filename=filename)
    print_line(80, color="green")
    auto_select_model = True

if not is_valid(valid_vae_dir, ('.vae.pt', '.vae.safetensors', '.pt', '.ckpt')):
    cprint(f"No VAEs were found in the directory '{valid_vae_dir}'.", color="yellow")
    url = "https://huggingface.co/NoCrypt/resources/resolve/main/any.vae.safetensors"
    filename = "Anime.vae.safetensors"
    aria2_download(url=url, download_dir=valid_vae_dir, filename=filename)
    print_line(80, color="green")
    auto_select_vae = True

if auto_select_model:
    selected_model  = auto_select_file(valid_ckpt_dir, "sd_model_checkpoint", ('.ckpt', '.safetensors'))
    cprint(f"Selected Model: {selected_model}", color="green")

if auto_select_vae:
    selected_vae    = auto_select_file(valid_vae_dir, "sd_vae", ('.vae.pt', '.vae.safetensors', '.pt', '.ckpt'))
    cprint(f"Selected VAE: {selected_vae}", color="green")

print_line(80, color="green")

configure_main_settings(config_file, valid_lora_dir, use_presets, ui_config_file)

if use_gradio_auth:
  cprint("Gradio Auth (use this account to login):", color="green")
  cprint("[-] Username: cagliostro", color="green")
  cprint("[-] Password:", password, color="green")
  print_line(80, color="green")

config = {
    "enable-insecure-extension-access": True,
    "disable-safe-unpickle"           : True,
    f"{accelerator}"                  : True,
    f"{select_tunnel}"                : True if not select_tunnel == "gradio" and not ngrok_token else False,
    "share"                           : True if not ngrok_token else False,
    "gradio-auth"                     : f"{user}:{password}" if use_gradio_auth else None,
    "no-hashing"                      : True,
    "disable-console-progressbars"    : True,
    "ngrok"                           : ngrok_token if ngrok_token else None,
    "ngrok-region"                    : ngrok_region if ngrok_token else None,
    "opt-sub-quad-attention"          : True,
    "opt-channelslast"                : True,
    "no-download-sd-model"            : True,
    "gradio-queue"                    : True,
    "listen"                          : True,
    "ckpt-dir"                        : valid_ckpt_dir,
    "vae-dir"                         : valid_vae_dir,
    "hypernetwork-dir"                : valid_hypernetwork_dir,
    "embeddings-dir"                  : valid_embedding_dir,
    "lora-dir"                        : valid_lora_dir,
    "lyco-dir"                        : valid_lora_dir,
}

args = parse_args(config)
final_args = f"python launch.py {args} {additional_arguments}"

cprint()
os.chdir(repo_dir)
os.environ["TCMALLOC_AGGRESSIVE_DECOMMIT"] = "t"
!{final_args}

main()

IndexError Traceback (most recent call last) in <cell line: 236>() 234 get_ipython().system('{final_args}') 235 --> 236 main()

1 frames in change_theme(filename) 40 41 style_config = config_utils.read_config(style_path) ---> 42 style_contents = style_config.split("/BREAKPOINT_CSS_CONTENT/")[1] 43 44 theme_config = config_utils.read_config(themes_file)

IndexError: list index out of range

does anybody know how to solve this problem plz help

aripsam commented 9 months ago

Yes! It works if you run the colab without checking the update_webui checkbox.