Spaces:
Paused
Paused
Super-squash branch 'main' using huggingface_hub
Browse filesCo-authored-by: John6666 <John6666@users.noreply.huggingface.co>
Files changed (11)
- .gitattributesAdded+35
- README.mdAdded+16
- app.pyAdded+1371
- color_image.pngAdded
- constants.pyAdded+585
- image.webpAdded
- image_processor.pyAdded+130
- packages.txtAdded+3
- requirements.txtAdded+5
- spiral_no_transparent.pngAdded
- utils.pyAdded+485
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12345678910111213141516---title: 🧩 DiffuseCraftemoji: 🧩🖼️colorFrom: redcolorTo: pinksdk: gradiosdk_version: 4.31.3app_file: app.pypinned: truelicense: mitshort_description: Stunning images using stable diffusion.preload_from_hub: - madebyollin/sdxl-vae-fp16-fix config.json,diffusion_pytorch_model.safetensors---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371import spacesimport osfrom stablepy import ( Model_Diffusers, SCHEDULE_TYPE_OPTIONS, SCHEDULE_PREDICTION_TYPE_OPTIONS, check_scheduler_compatibility, TASK_AND_PREPROCESSORS, FACE_RESTORATION_MODELS, scheduler_names,)from constants import ( DIRECTORY_MODELS, DIRECTORY_LORAS, DIRECTORY_VAES, DIRECTORY_EMBEDS, DIRECTORY_UPSCALERS, DOWNLOAD_MODEL, DOWNLOAD_VAE, DOWNLOAD_LORA, LOAD_DIFFUSERS_FORMAT_MODEL, DIFFUSERS_FORMAT_LORAS, DOWNLOAD_EMBEDS, CIVITAI_API_KEY, HF_TOKEN, TASK_STABLEPY, TASK_MODEL_LIST, UPSCALER_DICT_GUI, UPSCALER_KEYS, PROMPT_W_OPTIONS, WARNING_MSG_VAE, SDXL_TASK, MODEL_TYPE_TASK, POST_PROCESSING_SAMPLER, SUBTITLE_GUI, HELP_GUI, EXAMPLES_GUI_HELP, EXAMPLES_GUI, RESOURCES, DIFFUSERS_CONTROLNET_MODEL, IP_MODELS, MODE_IP_OPTIONS,)from stablepy.diffusers_vanilla.style_prompt_config import STYLE_NAMESimport torchimport reimport timefrom PIL import ImageFilefrom utils import ( download_things, get_model_list, extract_parameters, get_my_lora, get_model_type, extract_exif_data, create_mask_now, download_diffuser_repo, get_used_storage_gb, delete_model, progress_step_bar, html_template_message, escape_html,)from image_processor import preprocessor_tabfrom datetime import datetimeimport gradio as grimport loggingimport diffusersimport warningsfrom stablepy import loggerfrom diffusers import FluxPipeline# import urllib.parseimport subprocess
subprocess.run("rm -rf /data-nvme/zerogpu-offload/*", env={}, shell=True)ImageFile.LOAD_TRUNCATED_IMAGES = Truetorch.backends.cuda.matmul.allow_tf32 = True# os.environ["PYTORCH_NO_CUDA_MEMORY_CACHING"] = "1"print(os.getenv("SPACES_ZERO_GPU"))
directories = [DIRECTORY_MODELS, DIRECTORY_LORAS, DIRECTORY_VAES, DIRECTORY_EMBEDS, DIRECTORY_UPSCALERS]for directory in directories: os.makedirs(directory, exist_ok=True)
# Download stuffsfor url in [url.strip() for url in DOWNLOAD_MODEL.split(',')]: if not os.path.exists(f"./models/{url.split('/')[-1]}"): download_things(DIRECTORY_MODELS, url, HF_TOKEN, CIVITAI_API_KEY)for url in [url.strip() for url in DOWNLOAD_VAE.split(',')]: if not os.path.exists(f"./vaes/{url.split('/')[-1]}"): download_things(DIRECTORY_VAES, url, HF_TOKEN, CIVITAI_API_KEY)for url in [url.strip() for url in DOWNLOAD_LORA.split(',')]: if not os.path.exists(f"./loras/{url.split('/')[-1]}"): download_things(DIRECTORY_LORAS, url, HF_TOKEN, CIVITAI_API_KEY)
# Download Embeddingsfor url_embed in DOWNLOAD_EMBEDS: if not os.path.exists(f"./embedings/{url_embed.split('/')[-1]}"): download_things(DIRECTORY_EMBEDS, url_embed, HF_TOKEN, CIVITAI_API_KEY)
# Build list modelsembed_list = get_model_list(DIRECTORY_EMBEDS)embed_list = [ (os.path.splitext(os.path.basename(emb))[0], emb) for emb in embed_list]single_file_model_list = get_model_list(DIRECTORY_MODELS)model_list = LOAD_DIFFUSERS_FORMAT_MODEL + single_file_model_listlora_model_list = get_model_list(DIRECTORY_LORAS)lora_model_list.insert(0, "None")lora_model_list = lora_model_list + DIFFUSERS_FORMAT_LORASvae_model_list = get_model_list(DIRECTORY_VAES)vae_model_list.insert(0, "BakedVAE")vae_model_list.insert(0, "None")
print('\033[33m🏁 Download and listing of valid models completed.\033[0m')
flux_repo = "camenduru/FLUX.1-dev-diffusers"flux_pipe = FluxPipeline.from_pretrained( flux_repo, transformer=None, torch_dtype=torch.bfloat16,).to("cuda")components = flux_pipe.componentsdelete_model(flux_repo)# components = None
######################## GUI#######################logging.getLogger("diffusers").setLevel(logging.ERROR)diffusers.utils.logging.set_verbosity(40)warnings.filterwarnings(action="ignore", category=FutureWarning, module="diffusers")warnings.filterwarnings(action="ignore", category=UserWarning, module="diffusers")warnings.filterwarnings(action="ignore", category=FutureWarning, module="transformers")logger.setLevel(logging.DEBUG)
CSS = """.contain { display: flex; flex-direction: column; }#component-0 { height: 100%; }#gallery { flex-grow: 1; }#load_model { height: 50px; }"""
class GuiSD: def __init__(self, stream=True): self.model = None self.status_loading = False self.sleep_loading = 4 self.last_load = datetime.now() self.inventory = []
def update_storage_models(self, storage_floor_gb=24, required_inventory_for_purge=3): while get_used_storage_gb() > storage_floor_gb: if len(self.inventory) < required_inventory_for_purge: break removal_candidate = self.inventory.pop(0) delete_model(removal_candidate)
def update_inventory(self, model_name): if model_name not in single_file_model_list: self.inventory = [ m for m in self.inventory if m != model_name ] + [model_name] print(self.inventory)
def load_new_model(self, model_name, vae_model, task, controlnet_model, progress=gr.Progress(track_tqdm=True)):
# download link model > model_name
self.update_storage_models()
vae_model = vae_model if vae_model != "None" else None model_type = get_model_type(model_name) dtype_model = torch.bfloat16 if model_type == "FLUX" else torch.float16
if not os.path.exists(model_name): _ = download_diffuser_repo( repo_name=model_name, model_type=model_type, revision="main", token=True, )
self.update_inventory(model_name)
for i in range(68): if not self.status_loading: self.status_loading = True if i > 0: time.sleep(self.sleep_loading) print("Previous model ops...") break time.sleep(0.5) print(f"Waiting queue {i}") yield "Waiting queue"
self.status_loading = True
yield f"Loading model: {model_name}"
if vae_model == "BakedVAE": vae_model = model_name elif vae_model: vae_type = "SDXL" if "sdxl" in vae_model.lower() else "SD 1.5" if model_type != vae_type: gr.Warning(WARNING_MSG_VAE)
print("Loading model...")
try: start_time = time.time()
if self.model is None: self.model = Model_Diffusers( base_model_id=model_name, task_name=TASK_STABLEPY[task], vae_model=vae_model, type_model_precision=dtype_model, retain_task_model_in_cache=False, controlnet_model=controlnet_model, device="cpu", env_components=components, ) self.model.advanced_params(image_preprocessor_cuda_active=True) else: if self.model.base_model_id != model_name: load_now_time = datetime.now() elapsed_time = max((load_now_time - self.last_load).total_seconds(), 0)
if elapsed_time <= 9: print("Waiting for the previous model's time ops...") time.sleep(9 - elapsed_time)
self.model.device = torch.device("cpu") self.model.load_pipe( model_name, task_name=TASK_STABLEPY[task], vae_model=vae_model, type_model_precision=dtype_model, retain_task_model_in_cache=False, controlnet_model=controlnet_model, )
end_time = time.time() self.sleep_loading = max(min(int(end_time - start_time), 10), 4) except Exception as e: self.last_load = datetime.now() self.status_loading = False self.sleep_loading = 4 raise e
self.last_load = datetime.now() self.status_loading = False
yield f"Model loaded: {model_name}"
# @spaces.GPU(duration=59) @torch.inference_mode() def generate_pipeline( self, prompt, neg_prompt, num_images, steps, cfg, clip_skip, seed, lora1, lora_scale1, lora2, lora_scale2, lora3, lora_scale3, lora4, lora_scale4, lora5, lora_scale5, lora6, lora_scale6, lora7, lora_scale7, sampler, schedule_type, schedule_prediction_type, img_height, img_width, model_name, vae_model, task, image_control, preprocessor_name, preprocess_resolution, image_resolution, style_prompt, # list [] style_json_file, image_mask, strength, low_threshold, high_threshold, value_threshold, distance_threshold, recolor_gamma_correction, tile_blur_sigma, controlnet_output_scaling_in_unet, controlnet_start_threshold, controlnet_stop_threshold, textual_inversion, syntax_weights, upscaler_model_path, upscaler_increases_size, upscaler_tile_size, upscaler_tile_overlap, hires_steps, hires_denoising_strength, hires_sampler, hires_prompt, hires_negative_prompt, hires_before_adetailer, hires_after_adetailer, hires_schedule_type, hires_guidance_scale, controlnet_model, loop_generation, leave_progress_bar, disable_progress_bar, image_previews, display_images, save_generated_images, filename_pattern, image_storage_location, retain_compel_previous_load, retain_detailfix_model_previous_load, retain_hires_model_previous_load, t2i_adapter_preprocessor, t2i_adapter_conditioning_scale, t2i_adapter_conditioning_factor, xformers_memory_efficient_attention, freeu, generator_in_cpu, adetailer_inpaint_only, adetailer_verbose, adetailer_sampler, adetailer_active_a, prompt_ad_a, negative_prompt_ad_a, strength_ad_a, face_detector_ad_a, person_detector_ad_a, hand_detector_ad_a, mask_dilation_a, mask_blur_a, mask_padding_a, adetailer_active_b, prompt_ad_b, negative_prompt_ad_b, strength_ad_b, face_detector_ad_b, person_detector_ad_b, hand_detector_ad_b, mask_dilation_b, mask_blur_b, mask_padding_b, retain_task_cache_gui, guidance_rescale, image_ip1, mask_ip1, model_ip1, mode_ip1, scale_ip1, image_ip2, mask_ip2, model_ip2, mode_ip2, scale_ip2, pag_scale, face_restoration_model, face_restoration_visibility, face_restoration_weight, ): info_state = html_template_message("Navigating latent space...") yield info_state, gr.update(), gr.update()
vae_model = vae_model if vae_model != "None" else None loras_list = [lora1, lora2, lora3, lora4, lora5, lora6, lora7] vae_msg = f"VAE: {vae_model}" if vae_model else "" msg_lora = ""
print("Config model:", model_name, vae_model, loras_list)
task = TASK_STABLEPY[task]
params_ip_img = [] params_ip_msk = [] params_ip_model = [] params_ip_mode = [] params_ip_scale = []
all_adapters = [ (image_ip1, mask_ip1, model_ip1, mode_ip1, scale_ip1), (image_ip2, mask_ip2, model_ip2, mode_ip2, scale_ip2), ]
if not hasattr(self.model.pipe, "transformer"): for imgip, mskip, modelip, modeip, scaleip in all_adapters: if imgip: params_ip_img.append(imgip) if mskip: params_ip_msk.append(mskip) params_ip_model.append(modelip) params_ip_mode.append(modeip) params_ip_scale.append(scaleip)
concurrency = 5 self.model.stream_config(concurrency=concurrency, latent_resize_by=1, vae_decoding=False)
if task != "txt2img" and not image_control: raise ValueError("Reference image is required. Please upload one in 'Image ControlNet/Inpaint/Img2img'.")
if task in ["inpaint", "repaint"] and not image_mask: raise ValueError("Mask image not found. Upload one in 'Image Mask' to proceed.")
if "https://" not in str(UPSCALER_DICT_GUI[upscaler_model_path]): upscaler_model = upscaler_model_path else: url_upscaler = UPSCALER_DICT_GUI[upscaler_model_path]
if not os.path.exists(f"./{DIRECTORY_UPSCALERS}/{url_upscaler.split('/')[-1]}"): download_things(DIRECTORY_UPSCALERS, url_upscaler, HF_TOKEN)
upscaler_model = f"./{DIRECTORY_UPSCALERS}/{url_upscaler.split('/')[-1]}"
logging.getLogger("ultralytics").setLevel(logging.INFO if adetailer_verbose else logging.ERROR)
adetailer_params_A = { "face_detector_ad": face_detector_ad_a, "person_detector_ad": person_detector_ad_a, "hand_detector_ad": hand_detector_ad_a, "prompt": prompt_ad_a, "negative_prompt": negative_prompt_ad_a, "strength": strength_ad_a, # "image_list_task" : None, "mask_dilation": mask_dilation_a, "mask_blur": mask_blur_a, "mask_padding": mask_padding_a, "inpaint_only": adetailer_inpaint_only, "sampler": adetailer_sampler, }
adetailer_params_B = { "face_detector_ad": face_detector_ad_b, "person_detector_ad": person_detector_ad_b, "hand_detector_ad": hand_detector_ad_b, "prompt": prompt_ad_b, "negative_prompt": negative_prompt_ad_b, "strength": strength_ad_b, # "image_list_task" : None, "mask_dilation": mask_dilation_b, "mask_blur": mask_blur_b, "mask_padding": mask_padding_b, } pipe_params = { "prompt": prompt, "negative_prompt": neg_prompt, "img_height": img_height, "img_width": img_width, "num_images": num_images, "num_steps": steps, "guidance_scale": cfg, "clip_skip": clip_skip, "pag_scale": float(pag_scale), "seed": seed, "image": image_control, "preprocessor_name": preprocessor_name, "preprocess_resolution": preprocess_resolution, "image_resolution": image_resolution, "style_prompt": style_prompt if style_prompt else "", "style_json_file": "", "image_mask": image_mask, # only for Inpaint "strength": strength, # only for Inpaint or ... "low_threshold": low_threshold, "high_threshold": high_threshold, "value_threshold": value_threshold, "distance_threshold": distance_threshold, "recolor_gamma_correction": float(recolor_gamma_correction), "tile_blur_sigma": int(tile_blur_sigma), "lora_A": lora1 if lora1 != "None" else None, "lora_scale_A": lora_scale1, "lora_B": lora2 if lora2 != "None" else None, "lora_scale_B": lora_scale2, "lora_C": lora3 if lora3 != "None" else None, "lora_scale_C": lora_scale3, "lora_D": lora4 if lora4 != "None" else None, "lora_scale_D": lora_scale4, "lora_E": lora5 if lora5 != "None" else None, "lora_scale_E": lora_scale5, "lora_F": lora6 if lora6 != "None" else None, "lora_scale_F": lora_scale6, "lora_G": lora7 if lora7 != "None" else None, "lora_scale_G": lora_scale7, "textual_inversion": embed_list if textual_inversion else [], "syntax_weights": syntax_weights, # "Classic" "sampler": sampler, "schedule_type": schedule_type, "schedule_prediction_type": schedule_prediction_type, "xformers_memory_efficient_attention": xformers_memory_efficient_attention, "gui_active": True, "loop_generation": loop_generation, "controlnet_conditioning_scale": float(controlnet_output_scaling_in_unet), "control_guidance_start": float(controlnet_start_threshold), "control_guidance_end": float(controlnet_stop_threshold), "generator_in_cpu": generator_in_cpu, "FreeU": freeu, "adetailer_A": adetailer_active_a, "adetailer_A_params": adetailer_params_A, "adetailer_B": adetailer_active_b, "adetailer_B_params": adetailer_params_B, "leave_progress_bar": leave_progress_bar, "disable_progress_bar": disable_progress_bar, "image_previews": image_previews, "display_images": display_images, "save_generated_images": save_generated_images, "filename_pattern": filename_pattern, "image_storage_location": image_storage_location, "retain_compel_previous_load": retain_compel_previous_load, "retain_detailfix_model_previous_load": retain_detailfix_model_previous_load, "retain_hires_model_previous_load": retain_hires_model_previous_load, "t2i_adapter_preprocessor": t2i_adapter_preprocessor, "t2i_adapter_conditioning_scale": float(t2i_adapter_conditioning_scale), "t2i_adapter_conditioning_factor": float(t2i_adapter_conditioning_factor), "upscaler_model_path": upscaler_model, "upscaler_increases_size": upscaler_increases_size, "upscaler_tile_size": upscaler_tile_size, "upscaler_tile_overlap": upscaler_tile_overlap, "hires_steps": hires_steps, "hires_denoising_strength": hires_denoising_strength, "hires_prompt": hires_prompt, "hires_negative_prompt": hires_negative_prompt, "hires_sampler": hires_sampler, "hires_before_adetailer": hires_before_adetailer, "hires_after_adetailer": hires_after_adetailer, "hires_schedule_type": hires_schedule_type, "hires_guidance_scale": hires_guidance_scale, "ip_adapter_image": params_ip_img, "ip_adapter_mask": params_ip_msk, "ip_adapter_model": params_ip_model, "ip_adapter_mode": params_ip_mode, "ip_adapter_scale": params_ip_scale, "face_restoration_model": face_restoration_model, "face_restoration_visibility": face_restoration_visibility, "face_restoration_weight": face_restoration_weight, }
# kwargs for diffusers pipeline if guidance_rescale: pipe_params["guidance_rescale"] = guidance_rescale
self.model.device = torch.device("cuda:0") if hasattr(self.model.pipe, "transformer") and loras_list != ["None"] * self.model.num_loras: self.model.pipe.transformer.to(self.model.device) print("transformer to cuda")
actual_progress = 0 info_images = gr.update() for img, [seed, image_path, metadata] in self.model(**pipe_params): info_state = progress_step_bar(actual_progress, steps) actual_progress += concurrency if image_path: info_images = f"Seeds: {str(seed)}" if vae_msg: info_images = info_images + "<br>" + vae_msg
if "Cannot copy out of meta tensor; no data!" in self.model.last_lora_error: msg_ram = "Unable to process the LoRAs due to high RAM usage; please try again later." print(msg_ram) msg_lora += f"<br>{msg_ram}"
for status, lora in zip(self.model.lora_status, self.model.lora_memory): if status: msg_lora += f"<br>Loaded: {lora}" elif status is not None: msg_lora += f"<br>Error with: {lora}"
if msg_lora: info_images += msg_lora
info_images = info_images + "<br>" + "GENERATION DATA:<br>" + escape_html(metadata[-1]) + "<br>-------<br>"
download_links = "<br>".join( [ f'<a href="{path.replace("/images/", "/file=/home/user/app/images/")}" download="{os.path.basename(path)}">Download Image {i + 1}</a>' for i, path in enumerate(image_path) ] ) if save_generated_images: info_images += f"<br>{download_links}"
info_state = "COMPLETE"
yield info_state, img, info_images
def dynamic_gpu_duration(func, duration, *args):
# @torch.inference_mode() @spaces.GPU(duration=duration) def wrapped_func(): yield from func(*args)
return wrapped_func()
@spaces.GPUdef dummy_gpu(): return None
def sd_gen_generate_pipeline(*args): gpu_duration_arg = int(args[-1]) if args[-1] else 59 verbose_arg = int(args[-2]) load_lora_cpu = args[-3] generation_args = args[:-3] lora_list = [ None if item == "None" else item for item in [args[7], args[9], args[11], args[13], args[15], args[17], args[19]] ] lora_status = [None] * sd_gen.model.num_loras
msg_load_lora = "Updating LoRAs in GPU..." if load_lora_cpu: msg_load_lora = "Updating LoRAs in CPU..."
if lora_list != sd_gen.model.lora_memory and lora_list != [None] * sd_gen.model.num_loras: yield msg_load_lora, gr.update(), gr.update()
# Load lora in CPU if load_lora_cpu: lora_status = sd_gen.model.load_lora_on_the_fly( lora_A=lora_list[0], lora_scale_A=args[8], lora_B=lora_list[1], lora_scale_B=args[10], lora_C=lora_list[2], lora_scale_C=args[12], lora_D=lora_list[3], lora_scale_D=args[14], lora_E=lora_list[4], lora_scale_E=args[16], lora_F=lora_list[5], lora_scale_F=args[18], lora_G=lora_list[6], lora_scale_G=args[20], ) print(lora_status)
sampler_name = args[21] schedule_type_name = args[22] _, _, msg_sampler = check_scheduler_compatibility( sd_gen.model.class_name, sampler_name, schedule_type_name ) if msg_sampler: gr.Warning(msg_sampler)
if verbose_arg: for status, lora in zip(lora_status, lora_list): if status: gr.Info(f"LoRA loaded in CPU: {lora}") elif status is not None: gr.Warning(f"Failed to load LoRA: {lora}")
if lora_status == [None] * sd_gen.model.num_loras and sd_gen.model.lora_memory != [None] * sd_gen.model.num_loras and load_lora_cpu: lora_cache_msg = ", ".join( str(x) for x in sd_gen.model.lora_memory if x is not None ) gr.Info(f"LoRAs in cache: {lora_cache_msg}")
msg_request = f"Requesting {gpu_duration_arg}s. of GPU time.\nModel: {sd_gen.model.base_model_id}" if verbose_arg: gr.Info(msg_request) print(msg_request) yield msg_request.replace("\n", "<br>"), gr.update(), gr.update()
start_time = time.time()
# yield from sd_gen.generate_pipeline(*generation_args) yield from dynamic_gpu_duration( sd_gen.generate_pipeline, gpu_duration_arg, *generation_args, )
end_time = time.time() execution_time = end_time - start_time msg_task_complete = ( f"GPU task complete in: {int(round(execution_time, 0) + 1)} seconds" )
if verbose_arg: gr.Info(msg_task_complete) print(msg_task_complete)
yield msg_task_complete, gr.update(), gr.update()
@spaces.GPU(duration=15)def process_upscale(image, upscaler_name, upscaler_size): if image is None: return None
from stablepy.diffusers_vanilla.utils import save_pil_image_with_metadata from stablepy import load_upscaler_model
image = image.convert("RGB") exif_image = extract_exif_data(image)
name_upscaler = UPSCALER_DICT_GUI[upscaler_name]
if "https://" in str(name_upscaler):
if not os.path.exists(f"./{DIRECTORY_UPSCALERS}/{name_upscaler.split('/')[-1]}"): download_things(DIRECTORY_UPSCALERS, name_upscaler, HF_TOKEN)
name_upscaler = f"./{DIRECTORY_UPSCALERS}/{name_upscaler.split('/')[-1]}"
scaler_beta = load_upscaler_model(model=name_upscaler, tile=0, tile_overlap=8, device="cuda", half=True) image_up = scaler_beta.upscale(image, upscaler_size, True)
image_path = save_pil_image_with_metadata(image_up, f'{os.getcwd()}/up_images', exif_image)
return image_path
# https://huggingface.co/spaces/BestWishYsh/ConsisID-preview-Space/discussions/1#674969a022b99c122af5d407dynamic_gpu_duration.zerogpu = Truesd_gen_generate_pipeline.zerogpu = Truesd_gen = GuiSD()
with gr.Blocks(theme="NoCrypt/miku", css=CSS) as app: gr.Markdown("# 🧩 DiffuseCraft") gr.Markdown(SUBTITLE_GUI) with gr.Tab("Generation"): with gr.Row():
with gr.Column(scale=2):
def update_task_options(model_name, task_name): new_choices = MODEL_TYPE_TASK[get_model_type(model_name)]
if task_name not in new_choices: task_name = "txt2img"
return gr.update(value=task_name, choices=new_choices)
task_gui = gr.Dropdown(label="Task", choices=SDXL_TASK, value=TASK_MODEL_LIST[0]) model_name_gui = gr.Dropdown(label="Model", choices=model_list, value=model_list[0], allow_custom_value=True) prompt_gui = gr.Textbox(lines=5, placeholder="Enter prompt", label="Prompt") neg_prompt_gui = gr.Textbox(lines=3, placeholder="Enter Neg prompt", label="Negative prompt", value="lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, worst quality, low quality, very displeasing, (bad)") with gr.Row(equal_height=False): set_params_gui = gr.Button(value="↙️", variant="secondary", size="sm") clear_prompt_gui = gr.Button(value="🗑️", variant="secondary", size="sm") set_random_seed = gr.Button(value="🎲", variant="secondary", size="sm") generate_button = gr.Button(value="GENERATE IMAGE", variant="primary")
model_name_gui.change( update_task_options, [model_name_gui, task_gui], [task_gui], )
load_model_gui = gr.HTML(elem_id="load_model", elem_classes="contain")
result_images = gr.Gallery( label="Generated images", show_label=False, elem_id="gallery", columns=[2], rows=[2], object_fit="contain", # height="auto", interactive=False, preview=False, selected_index=50, )
actual_task_info = gr.HTML()
with gr.Row(equal_height=False, variant="default"): gpu_duration_gui = gr.Number(minimum=5, maximum=240, value=59, show_label=False, container=False, info="GPU time duration (seconds)") with gr.Column(): verbose_info_gui = gr.Checkbox(value=False, container=False, label="Status info") load_lora_cpu_gui = gr.Checkbox(value=False, container=False, label="Load LoRAs on CPU")
with gr.Column(scale=1): steps_gui = gr.Slider(minimum=1, maximum=100, step=1, value=28, label="Steps") cfg_gui = gr.Slider(minimum=0, maximum=30, step=0.5, value=7., label="CFG") sampler_gui = gr.Dropdown(label="Sampler", choices=scheduler_names, value="Euler") schedule_type_gui = gr.Dropdown(label="Schedule type", choices=SCHEDULE_TYPE_OPTIONS, value=SCHEDULE_TYPE_OPTIONS[0]) img_width_gui = gr.Slider(minimum=64, maximum=4096, step=8, value=1024, label="Img Width") img_height_gui = gr.Slider(minimum=64, maximum=4096, step=8, value=1024, label="Img Height") seed_gui = gr.Number(minimum=-1, maximum=9999999999, value=-1, label="Seed") pag_scale_gui = gr.Slider(minimum=0.0, maximum=10.0, step=0.1, value=0.0, label="PAG Scale") with gr.Row(): clip_skip_gui = gr.Checkbox(value=True, label="Layer 2 Clip Skip") free_u_gui = gr.Checkbox(value=False, label="FreeU")
with gr.Row(equal_height=False):
def run_set_params_gui(base_prompt, name_model): valid_receptors = { # default values "prompt": gr.update(value=base_prompt), "neg_prompt": gr.update(value=""), "Steps": gr.update(value=30), "width": gr.update(value=1024), "height": gr.update(value=1024), "Seed": gr.update(value=-1), "Sampler": gr.update(value="Euler"), "CFG scale": gr.update(value=7.), # cfg "Clip skip": gr.update(value=True), "Model": gr.update(value=name_model), "Schedule type": gr.update(value="Automatic"), "PAG": gr.update(value=.0), "FreeU": gr.update(value=False), } valid_keys = list(valid_receptors.keys())
parameters = extract_parameters(base_prompt) # print(parameters)
if "Sampler" in parameters: value_sampler = parameters["Sampler"] for s_type in SCHEDULE_TYPE_OPTIONS: if s_type in value_sampler: value_sampler = value_sampler.replace(s_type, "").strip() parameters["Sampler"] = value_sampler parameters["Schedule type"] = s_type
for key, val in parameters.items(): # print(val) if key in valid_keys: try: if key == "Sampler": if val not in scheduler_names: continue if key == "Schedule type": if val not in SCHEDULE_TYPE_OPTIONS: val = "Automatic" elif key == "Clip skip": if "," in str(val): val = val.replace(",", "") if int(val) >= 2: val = True if key == "prompt": if ">" in val and "<" in val: val = re.sub(r'<[^>]+>', '', val) print("Removed LoRA written in the prompt") if key in ["prompt", "neg_prompt"]: val = re.sub(r'\s+', ' ', re.sub(r',+', ',', val)).strip() if key in ["Steps", "width", "height", "Seed"]: val = int(val) if key == "FreeU": val = True if key in ["CFG scale", "PAG"]: val = float(val) if key == "Model": filtered_models = [m for m in model_list if val in m] if filtered_models: val = filtered_models[0] else: val = name_model if key == "Seed": continue valid_receptors[key] = gr.update(value=val) # print(val, type(val)) # print(valid_receptors) except Exception as e: print(str(e)) return [value for value in valid_receptors.values()]
set_params_gui.click( run_set_params_gui, [prompt_gui, model_name_gui], [ prompt_gui, neg_prompt_gui, steps_gui, img_width_gui, img_height_gui, seed_gui, sampler_gui, cfg_gui, clip_skip_gui, model_name_gui, schedule_type_gui, pag_scale_gui, free_u_gui, ], )
def run_clear_prompt_gui(): return gr.update(value=""), gr.update(value="") clear_prompt_gui.click( run_clear_prompt_gui, [], [prompt_gui, neg_prompt_gui] )
def run_set_random_seed(): return -1 set_random_seed.click( run_set_random_seed, [], seed_gui )
num_images_gui = gr.Slider(minimum=1, maximum=5, step=1, value=1, label="Images") prompt_syntax_gui = gr.Dropdown(label="Prompt Syntax", choices=PROMPT_W_OPTIONS, value=PROMPT_W_OPTIONS[1][1]) vae_model_gui = gr.Dropdown(label="VAE Model", choices=vae_model_list, value=vae_model_list[0])
with gr.Accordion("Hires fix", open=False, visible=True):
upscaler_model_path_gui = gr.Dropdown(label="Upscaler", choices=UPSCALER_KEYS, value=UPSCALER_KEYS[0]) upscaler_increases_size_gui = gr.Slider(minimum=1.1, maximum=4., step=0.1, value=1.2, label="Upscale by") upscaler_tile_size_gui = gr.Slider(minimum=0, maximum=512, step=16, value=0, label="Upscaler Tile Size", info="0 = no tiling") upscaler_tile_overlap_gui = gr.Slider(minimum=0, maximum=48, step=1, value=8, label="Upscaler Tile Overlap") hires_steps_gui = gr.Slider(minimum=0, value=30, maximum=100, step=1, label="Hires Steps") hires_denoising_strength_gui = gr.Slider(minimum=0.1, maximum=1.0, step=0.01, value=0.55, label="Hires Denoising Strength") hires_sampler_gui = gr.Dropdown(label="Hires Sampler", choices=POST_PROCESSING_SAMPLER, value=POST_PROCESSING_SAMPLER[0]) hires_schedule_list = ["Use same schedule type"] + SCHEDULE_TYPE_OPTIONS hires_schedule_type_gui = gr.Dropdown(label="Hires Schedule type", choices=hires_schedule_list, value=hires_schedule_list[0]) hires_guidance_scale_gui = gr.Slider(minimum=-1., maximum=30., step=0.5, value=-1., label="Hires CFG", info="If the value is -1, the main CFG will be used") hires_prompt_gui = gr.Textbox(label="Hires Prompt", placeholder="Main prompt will be use", lines=3) hires_negative_prompt_gui = gr.Textbox(label="Hires Negative Prompt", placeholder="Main negative prompt will be use", lines=3)
with gr.Accordion("LoRA", open=False, visible=True):
def lora_dropdown(label, visible=True): return gr.Dropdown(label=label, choices=lora_model_list, value="None", allow_custom_value=True, visible=visible)
def lora_scale_slider(label, visible=True): return gr.Slider(minimum=-2, maximum=2, step=0.01, value=0.33, label=label, visible=visible)
lora1_gui = lora_dropdown("Lora1") lora_scale_1_gui = lora_scale_slider("Lora Scale 1") lora2_gui = lora_dropdown("Lora2") lora_scale_2_gui = lora_scale_slider("Lora Scale 2") lora3_gui = lora_dropdown("Lora3") lora_scale_3_gui = lora_scale_slider("Lora Scale 3") lora4_gui = lora_dropdown("Lora4") lora_scale_4_gui = lora_scale_slider("Lora Scale 4") lora5_gui = lora_dropdown("Lora5") lora_scale_5_gui = lora_scale_slider("Lora Scale 5") lora6_gui = lora_dropdown("Lora6", visible=False) lora_scale_6_gui = lora_scale_slider("Lora Scale 6", visible=False) lora7_gui = lora_dropdown("Lora7", visible=False) lora_scale_7_gui = lora_scale_slider("Lora Scale 7", visible=False)
with gr.Accordion("From URL", open=False, visible=True): text_lora = gr.Textbox( label="LoRA's download URL", placeholder="https://civitai.com/api/download/models/28907", lines=1, info="It has to be .safetensors files, and you can also download them from Hugging Face.", ) romanize_text = gr.Checkbox(value=False, label="Transliterate name", visible=False) button_lora = gr.Button("Get and Refresh the LoRA Lists") new_lora_status = gr.HTML() button_lora.click( get_my_lora, [text_lora, romanize_text], [lora1_gui, lora2_gui, lora3_gui, lora4_gui, lora5_gui, lora6_gui, lora7_gui, new_lora_status] )
with gr.Accordion("Face restoration", open=False, visible=True):
face_rest_options = [None] + FACE_RESTORATION_MODELS
face_restoration_model_gui = gr.Dropdown(label="Face restoration model", choices=face_rest_options, value=face_rest_options[0]) face_restoration_visibility_gui = gr.Slider(minimum=0., maximum=1., step=0.001, value=1., label="Visibility") face_restoration_weight_gui = gr.Slider(minimum=0., maximum=1., step=0.001, value=.5, label="Weight", info="(0 = maximum effect, 1 = minimum effect)")
with gr.Accordion("IP-Adapter", open=False, visible=True):
with gr.Accordion("IP-Adapter 1", open=False, visible=True): image_ip1 = gr.Image(label="IP Image", type="filepath") mask_ip1 = gr.Image(label="IP Mask", type="filepath") model_ip1 = gr.Dropdown(value="plus_face", label="Model", choices=IP_MODELS) mode_ip1 = gr.Dropdown(value="original", label="Mode", choices=MODE_IP_OPTIONS) scale_ip1 = gr.Slider(minimum=0., maximum=2., step=0.01, value=0.7, label="Scale") with gr.Accordion("IP-Adapter 2", open=False, visible=True): image_ip2 = gr.Image(label="IP Image", type="filepath") mask_ip2 = gr.Image(label="IP Mask (optional)", type="filepath") model_ip2 = gr.Dropdown(value="base", label="Model", choices=IP_MODELS) mode_ip2 = gr.Dropdown(value="style", label="Mode", choices=MODE_IP_OPTIONS) scale_ip2 = gr.Slider(minimum=0., maximum=2., step=0.01, value=0.7, label="Scale")
with gr.Accordion("ControlNet / Img2img / Inpaint", open=False, visible=True): image_control = gr.Image(label="Image ControlNet/Inpaint/Img2img", type="filepath") image_mask_gui = gr.Image(label="Image Mask", type="filepath") strength_gui = gr.Slider( minimum=0.01, maximum=1.0, step=0.01, value=0.55, label="Strength", info="This option adjusts the level of changes for img2img, repaint and inpaint." ) image_resolution_gui = gr.Slider( minimum=64, maximum=2048, step=64, value=1024, label="Image Resolution", info="The maximum proportional size of the generated image based on the uploaded image." ) controlnet_model_gui = gr.Dropdown(label="ControlNet model", choices=DIFFUSERS_CONTROLNET_MODEL, value=DIFFUSERS_CONTROLNET_MODEL[0], allow_custom_value=True) control_net_output_scaling_gui = gr.Slider(minimum=0, maximum=5.0, step=0.1, value=1, label="ControlNet Output Scaling in UNet") control_net_start_threshold_gui = gr.Slider(minimum=0, maximum=1, step=0.01, value=0, label="ControlNet Start Threshold (%)") control_net_stop_threshold_gui = gr.Slider(minimum=0, maximum=1, step=0.01, value=1, label="ControlNet Stop Threshold (%)") preprocessor_name_gui = gr.Dropdown(label="Preprocessor Name", choices=TASK_AND_PREPROCESSORS["canny"])
def change_preprocessor_choices(task): task = TASK_STABLEPY[task] if task in TASK_AND_PREPROCESSORS.keys(): choices_task = TASK_AND_PREPROCESSORS[task] else: choices_task = TASK_AND_PREPROCESSORS["canny"] return gr.update(choices=choices_task, value=choices_task[0]) task_gui.change( change_preprocessor_choices, [task_gui], [preprocessor_name_gui], )
preprocess_resolution_gui = gr.Slider(minimum=64, maximum=2048, step=64, value=512, label="Preprocessor Resolution") low_threshold_gui = gr.Slider(minimum=1, maximum=255, step=1, value=100, label="'CANNY' low threshold") high_threshold_gui = gr.Slider(minimum=1, maximum=255, step=1, value=200, label="'CANNY' high threshold") value_threshold_gui = gr.Slider(minimum=1, maximum=2.0, step=0.01, value=0.1, label="'MLSD' Hough value threshold") distance_threshold_gui = gr.Slider(minimum=1, maximum=20.0, step=0.01, value=0.1, label="'MLSD' Hough distance threshold") recolor_gamma_correction_gui = gr.Number(minimum=0., maximum=25., value=1., step=0.001, label="'RECOLOR' gamma correction") tile_blur_sigma_gui = gr.Number(minimum=0, maximum=100, value=9, step=1, label="'TILE' blur sigma")
with gr.Accordion("T2I adapter", open=False, visible=False): t2i_adapter_preprocessor_gui = gr.Checkbox(value=True, label="T2i Adapter Preprocessor") adapter_conditioning_scale_gui = gr.Slider(minimum=0, maximum=5., step=0.1, value=1, label="Adapter Conditioning Scale") adapter_conditioning_factor_gui = gr.Slider(minimum=0, maximum=1., step=0.01, value=0.55, label="Adapter Conditioning Factor (%)")
with gr.Accordion("Styles", open=False, visible=True):
try: style_names_found = sd_gen.model.STYLE_NAMES except Exception: style_names_found = STYLE_NAMES
style_prompt_gui = gr.Dropdown( style_names_found, multiselect=True, value=None, label="Style Prompt", interactive=True, ) style_json_gui = gr.File(label="Style JSON File") style_button = gr.Button("Load styles")
def load_json_style_file(json): if not sd_gen.model: gr.Info("First load the model") return gr.update(value=None, choices=STYLE_NAMES)
sd_gen.model.load_style_file(json) gr.Info(f"{len(sd_gen.model.STYLE_NAMES)} styles loaded") return gr.update(value=None, choices=sd_gen.model.STYLE_NAMES)
style_button.click(load_json_style_file, [style_json_gui], [style_prompt_gui])
with gr.Accordion("Textual inversion", open=False, visible=False): active_textual_inversion_gui = gr.Checkbox(value=False, label="Active Textual Inversion in prompt")
with gr.Accordion("Detailfix", open=False, visible=True):
# Adetailer Inpaint Only adetailer_inpaint_only_gui = gr.Checkbox(label="Inpaint only", value=True)
# Adetailer Verbose adetailer_verbose_gui = gr.Checkbox(label="Verbose", value=False)
# Adetailer Sampler adetailer_sampler_gui = gr.Dropdown(label="Adetailer sampler:", choices=POST_PROCESSING_SAMPLER, value=POST_PROCESSING_SAMPLER[0])
with gr.Accordion("Detailfix A", open=False, visible=True): # Adetailer A adetailer_active_a_gui = gr.Checkbox(label="Enable Adetailer A", value=False) prompt_ad_a_gui = gr.Textbox(label="Main prompt", placeholder="Main prompt will be use", lines=3) negative_prompt_ad_a_gui = gr.Textbox(label="Negative prompt", placeholder="Main negative prompt will be use", lines=3) strength_ad_a_gui = gr.Number(label="Strength:", value=0.35, step=0.01, minimum=0.01, maximum=1.0) face_detector_ad_a_gui = gr.Checkbox(label="Face detector", value=True) person_detector_ad_a_gui = gr.Checkbox(label="Person detector", value=False) hand_detector_ad_a_gui = gr.Checkbox(label="Hand detector", value=False) mask_dilation_a_gui = gr.Number(label="Mask dilation:", value=4, minimum=1) mask_blur_a_gui = gr.Number(label="Mask blur:", value=4, minimum=1) mask_padding_a_gui = gr.Number(label="Mask padding:", value=32, minimum=1)
with gr.Accordion("Detailfix B", open=False, visible=True): # Adetailer B adetailer_active_b_gui = gr.Checkbox(label="Enable Adetailer B", value=False) prompt_ad_b_gui = gr.Textbox(label="Main prompt", placeholder="Main prompt will be use", lines=3) negative_prompt_ad_b_gui = gr.Textbox(label="Negative prompt", placeholder="Main negative prompt will be use", lines=3) strength_ad_b_gui = gr.Number(label="Strength:", value=0.35, step=0.01, minimum=0.01, maximum=1.0) face_detector_ad_b_gui = gr.Checkbox(label="Face detector", value=False) person_detector_ad_b_gui = gr.Checkbox(label="Person detector", value=True) hand_detector_ad_b_gui = gr.Checkbox(label="Hand detector", value=False) mask_dilation_b_gui = gr.Number(label="Mask dilation:", value=4, minimum=1) mask_blur_b_gui = gr.Number(label="Mask blur:", value=4, minimum=1) mask_padding_b_gui = gr.Number(label="Mask padding:", value=32, minimum=1)
with gr.Accordion("Other settings", open=False, visible=True): schedule_prediction_type_gui = gr.Dropdown(label="Discrete Sampling Type", choices=SCHEDULE_PREDICTION_TYPE_OPTIONS, value=SCHEDULE_PREDICTION_TYPE_OPTIONS[0]) guidance_rescale_gui = gr.Number(label="CFG rescale:", value=0., step=0.01, minimum=0., maximum=1.5) save_generated_images_gui = gr.Checkbox(value=True, label="Create a download link for the images") filename_pattern_gui = gr.Textbox(label="Filename pattern", value="model,seed", placeholder="model,seed,sampler,schedule_type,img_width,img_height,guidance_scale,num_steps,vae,prompt_section,neg_prompt_section", lines=1) hires_before_adetailer_gui = gr.Checkbox(value=False, label="Hires Before Adetailer") hires_after_adetailer_gui = gr.Checkbox(value=True, label="Hires After Adetailer") generator_in_cpu_gui = gr.Checkbox(value=False, label="Generator in CPU")
with gr.Accordion("More settings", open=False, visible=False): loop_generation_gui = gr.Slider(minimum=1, value=1, label="Loop Generation") retain_task_cache_gui = gr.Checkbox(value=False, label="Retain task model in cache") leave_progress_bar_gui = gr.Checkbox(value=True, label="Leave Progress Bar") disable_progress_bar_gui = gr.Checkbox(value=False, label="Disable Progress Bar") display_images_gui = gr.Checkbox(value=False, label="Display Images") image_previews_gui = gr.Checkbox(value=True, label="Image Previews") image_storage_location_gui = gr.Textbox(value="./images", label="Image Storage Location") retain_compel_previous_load_gui = gr.Checkbox(value=False, label="Retain Compel Previous Load") retain_detailfix_model_previous_load_gui = gr.Checkbox(value=False, label="Retain Detailfix Model Previous Load") retain_hires_model_previous_load_gui = gr.Checkbox(value=False, label="Retain Hires Model Previous Load") xformers_memory_efficient_attention_gui = gr.Checkbox(value=False, label="Xformers Memory Efficient Attention")
with gr.Accordion("Examples and help", open=False, visible=True): gr.Markdown(HELP_GUI) gr.Markdown(EXAMPLES_GUI_HELP) gr.Examples( examples=EXAMPLES_GUI, fn=sd_gen.generate_pipeline, inputs=[ prompt_gui, neg_prompt_gui, steps_gui, cfg_gui, seed_gui, lora1_gui, lora_scale_1_gui, sampler_gui, img_height_gui, img_width_gui, model_name_gui, task_gui, image_control, image_resolution_gui, strength_gui, control_net_output_scaling_gui, control_net_start_threshold_gui, control_net_stop_threshold_gui, prompt_syntax_gui, upscaler_model_path_gui, gpu_duration_gui, load_lora_cpu_gui, ], outputs=[load_model_gui, result_images, actual_task_info], cache_examples=False, ) gr.Markdown(RESOURCES)
with gr.Tab("Inpaint mask maker", render=True):
with gr.Row(): with gr.Column(scale=2): image_base = gr.ImageEditor( sources=["upload", "clipboard"], # crop_size="1:1", # enable crop (or disable it) # transforms=["crop"], brush=gr.Brush( default_size="16", # or leave it as 'auto' color_mode="fixed", # 'fixed' hides the user swatches and colorpicker, 'defaults' shows it # default_color="black", # html names are supported colors=[ "rgba(0, 0, 0, 1)", # rgb(a) "rgba(0, 0, 0, 0.1)", "rgba(255, 255, 255, 0.1)", # "hsl(360, 120, 120)" # in fact any valid colorstring ] ), eraser=gr.Eraser(default_size="16") ) invert_mask = gr.Checkbox(value=False, label="Invert mask") btn = gr.Button("Create mask") with gr.Column(scale=1): img_source = gr.Image(interactive=False) img_result = gr.Image(label="Mask image", show_label=True, interactive=False) btn_send = gr.Button("Send to the first tab")
btn.click(create_mask_now, [image_base, invert_mask], [img_source, img_result])
def send_img(img_source, img_result): return img_source, img_result btn_send.click(send_img, [img_source, img_result], [image_control, image_mask_gui])
with gr.Tab("PNG Info"):
with gr.Row(): with gr.Column(): image_metadata = gr.Image(label="Image with metadata", type="pil", sources=["upload"])
with gr.Column(): result_metadata = gr.Textbox(label="Metadata", show_label=True, show_copy_button=True, interactive=False, container=True, max_lines=99)
image_metadata.change( fn=extract_exif_data, inputs=[image_metadata], outputs=[result_metadata], )
with gr.Tab("Upscaler"):
with gr.Row(): with gr.Column():
USCALER_TAB_KEYS = [name for name in UPSCALER_KEYS[9:]]
image_up_tab = gr.Image(label="Image", type="pil", sources=["upload"]) upscaler_tab = gr.Dropdown(label="Upscaler", choices=USCALER_TAB_KEYS, value=USCALER_TAB_KEYS[5]) upscaler_size_tab = gr.Slider(minimum=1., maximum=4., step=0.1, value=1.1, label="Upscale by") generate_button_up_tab = gr.Button(value="START UPSCALE", variant="primary")
with gr.Column(): result_up_tab = gr.Image(label="Result", type="pil", interactive=False, format="png")
generate_button_up_tab.click( fn=process_upscale, inputs=[image_up_tab, upscaler_tab, upscaler_size_tab], outputs=[result_up_tab], )
with gr.Tab("Preprocessor", render=True): preprocessor_tab()
generate_button.click( fn=sd_gen.load_new_model, inputs=[ model_name_gui, vae_model_gui, task_gui, controlnet_model_gui, ], outputs=[load_model_gui], queue=True, show_progress="minimal", ).success( fn=sd_gen_generate_pipeline, # fn=sd_gen.generate_pipeline, inputs=[ prompt_gui, neg_prompt_gui, num_images_gui, steps_gui, cfg_gui, clip_skip_gui, seed_gui, lora1_gui, lora_scale_1_gui, lora2_gui, lora_scale_2_gui, lora3_gui, lora_scale_3_gui, lora4_gui, lora_scale_4_gui, lora5_gui, lora_scale_5_gui, lora6_gui, lora_scale_6_gui, lora7_gui, lora_scale_7_gui, sampler_gui, schedule_type_gui, schedule_prediction_type_gui, img_height_gui, img_width_gui, model_name_gui, vae_model_gui, task_gui, image_control, preprocessor_name_gui, preprocess_resolution_gui, image_resolution_gui, style_prompt_gui, style_json_gui, image_mask_gui, strength_gui, low_threshold_gui, high_threshold_gui, value_threshold_gui, distance_threshold_gui, recolor_gamma_correction_gui, tile_blur_sigma_gui, control_net_output_scaling_gui, control_net_start_threshold_gui, control_net_stop_threshold_gui, active_textual_inversion_gui, prompt_syntax_gui, upscaler_model_path_gui, upscaler_increases_size_gui, upscaler_tile_size_gui, upscaler_tile_overlap_gui, hires_steps_gui, hires_denoising_strength_gui, hires_sampler_gui, hires_prompt_gui, hires_negative_prompt_gui, hires_before_adetailer_gui, hires_after_adetailer_gui, hires_schedule_type_gui, hires_guidance_scale_gui, controlnet_model_gui, loop_generation_gui, leave_progress_bar_gui, disable_progress_bar_gui, image_previews_gui, display_images_gui, save_generated_images_gui, filename_pattern_gui, image_storage_location_gui, retain_compel_previous_load_gui, retain_detailfix_model_previous_load_gui, retain_hires_model_previous_load_gui, t2i_adapter_preprocessor_gui, adapter_conditioning_scale_gui, adapter_conditioning_factor_gui, xformers_memory_efficient_attention_gui, free_u_gui, generator_in_cpu_gui, adetailer_inpaint_only_gui, adetailer_verbose_gui, adetailer_sampler_gui, adetailer_active_a_gui, prompt_ad_a_gui, negative_prompt_ad_a_gui, strength_ad_a_gui, face_detector_ad_a_gui, person_detector_ad_a_gui, hand_detector_ad_a_gui, mask_dilation_a_gui, mask_blur_a_gui, mask_padding_a_gui, adetailer_active_b_gui, prompt_ad_b_gui, negative_prompt_ad_b_gui, strength_ad_b_gui, face_detector_ad_b_gui, person_detector_ad_b_gui, hand_detector_ad_b_gui, mask_dilation_b_gui, mask_blur_b_gui, mask_padding_b_gui, retain_task_cache_gui, guidance_rescale_gui, image_ip1, mask_ip1, model_ip1, mode_ip1, scale_ip1, image_ip2, mask_ip2, model_ip2, mode_ip2, scale_ip2, pag_scale_gui, face_restoration_model_gui, face_restoration_visibility_gui, face_restoration_weight_gui, load_lora_cpu_gui, verbose_info_gui, gpu_duration_gui, ], outputs=[load_model_gui, result_images, actual_task_info], queue=True, show_progress="minimal", )
app.queue()
app.launch( show_error=True, debug=True, allowed_paths=["./images/"],)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585import osfrom stablepy.diffusers_vanilla.constants import FLUX_CN_UNION_MODESfrom stablepy import ( scheduler_names, SD15_TASKS, SDXL_TASKS, ALL_BUILTIN_UPSCALERS, IP_ADAPTERS_SD, IP_ADAPTERS_SDXL,)
# - **Download Models**DOWNLOAD_MODEL = "https://huggingface.co/TechnoByte/MilkyWonderland/resolve/main/milkyWonderland_v40.safetensors"
# - **Download VAEs**DOWNLOAD_VAE = "https://huggingface.co/fp16-guy/anything_kl-f8-anime2_vae-ft-mse-840000-ema-pruned_blessed_clearvae_fp16_cleaned/resolve/main/vae-ft-mse-840000-ema-pruned_fp16.safetensors?download=true"
# - **Download LoRAs**DOWNLOAD_LORA = "https://huggingface.co/Leopain/color/resolve/main/Coloring_book_-_LineArt.safetensors, https://civitai.com/api/download/models/135867, https://huggingface.co/Linaqruf/anime-detailer-xl-lora/resolve/main/anime-detailer-xl.safetensors?download=true, https://huggingface.co/Linaqruf/style-enhancer-xl-lora/resolve/main/style-enhancer-xl.safetensors?download=true, https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SD15-8steps-CFG-lora.safetensors?download=true, https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-8steps-CFG-lora.safetensors?download=true"
LOAD_DIFFUSERS_FORMAT_MODEL = [ 'stabilityai/stable-diffusion-xl-base-1.0', 'Laxhar/noobai-XL-1.1', 'Laxhar/noobai-XL-Vpred-1.0', 'black-forest-labs/FLUX.1-dev', 'John6666/blue-pencil-flux1-v021-fp8-flux', 'John6666/wai-ani-flux-v10forfp8-fp8-flux', 'John6666/xe-anime-flux-v04-fp8-flux', 'John6666/lyh-anime-flux-v2a1-fp8-flux', 'John6666/carnival-unchained-v10-fp8-flux', 'John6666/iniverse-mix-xl-sfwnsfw-fluxdfp16nsfwv11-fp8-flux', 'Freepik/flux.1-lite-8B-alpha', 'shauray/FluxDev-HyperSD-merged', 'mikeyandfriends/PixelWave_FLUX.1-dev_03', 'terminusresearch/FluxBooru-v0.3', 'black-forest-labs/FLUX.1-schnell', # 'ostris/OpenFLUX.1', 'shuttleai/shuttle-3-diffusion', 'Laxhar/noobai-XL-1.0', 'John6666/noobai-xl-nai-xl-epsilonpred10version-sdxl', 'Laxhar/noobai-XL-0.77', 'John6666/noobai-xl-nai-xl-epsilonpred075version-sdxl', 'Laxhar/noobai-XL-0.6', 'John6666/noobai-xl-nai-xl-epsilonpred05version-sdxl', 'John6666/noobai-cyberfix-v10-sdxl', 'John6666/noobaiiter-xl-vpred-v075-sdxl', 'John6666/ntr-mix-illustrious-xl-noob-xl-v40-sdxl', 'John6666/ntr-mix-illustrious-xl-noob-xl-ntrmix35-sdxl', 'John6666/ntr-mix-illustrious-xl-noob-xl-v777-sdxl', 'John6666/ntr-mix-illustrious-xl-noob-xl-v777forlora-sdxl', 'John6666/ntr-mix-illustrious-xl-noob-xl-xi-sdxl', 'John6666/ntr-mix-illustrious-xl-noob-xl-xii-sdxl', 'John6666/ntr-mix-illustrious-xl-noob-xl-xiii-sdxl', 'John6666/mistoon-anime-v10illustrious-sdxl', 'John6666/hassaku-xl-illustrious-v10-sdxl', 'John6666/hassaku-xl-illustrious-v10style-sdxl', 'John6666/haruki-mix-illustrious-v10-sdxl', 'John6666/noobreal-v10-sdxl', 'John6666/complicated-noobai-merge-vprediction-sdxl', 'Laxhar/noobai-XL-Vpred-0.9r', 'Laxhar/noobai-XL-Vpred-0.75s', 'Laxhar/noobai-XL-Vpred-0.75', 'Laxhar/noobai-XL-Vpred-0.65s', 'Laxhar/noobai-XL-Vpred-0.65', 'Laxhar/noobai-XL-Vpred-0.6', 'John6666/cat-tower-noobai-xl-checkpoint-v14vpred-sdxl', 'John6666/noobai-xl-nai-xl-vpred05version-sdxl', 'John6666/noobai-fusion2-vpred-itercomp-v1-sdxl', 'John6666/noobai-xl-nai-xl-vpredtestversion-sdxl', 'John6666/chadmix-noobai075-illustrious01-v10-sdxl', 'OnomaAIResearch/Illustrious-xl-early-release-v0', 'John6666/illustriousxl-mmmix-v50-sdxl', 'John6666/illustrious-pencil-xl-v200-sdxl', 'John6666/obsession-illustriousxl-v21-sdxl', 'John6666/obsession-illustriousxl-v30-sdxl', 'John6666/obsession-illustriousxl-v31-sdxl', 'John6666/wai-nsfw-illustrious-v70-sdxl', 'John6666/illustrious-pony-mix-v3-sdxl', 'John6666/nova-anime-xl-illustriousv10-sdxl', 'John6666/nova-orange-xl-v30-sdxl', 'John6666/silvermoon-mix03-illustrious-v10-sdxl', 'eienmojiki/Anything-XL', 'eienmojiki/Starry-XL-v5.2', 'John6666/meinaxl-v2-sdxl', 'Eugeoter/artiwaifu-diffusion-2.0', 'comin/IterComp', 'John6666/epicrealism-xl-vxiabeast-sdxl', 'John6666/epicrealism-xl-v10kiss2-sdxl', 'John6666/epicrealism-xl-v8kiss-sdxl', 'misri/zavychromaxl_v80', 'SG161222/RealVisXL_V4.0', 'SG161222/RealVisXL_V5.0', 'misri/newrealityxlAllInOne_Newreality40', 'gsdf/CounterfeitXL', 'WhiteAiZ/autismmixSDXL_autismmixConfetti_diffusers', 'kitty7779/ponyDiffusionV6XL', 'GraydientPlatformAPI/aniverse-pony', 'John6666/ras-real-anime-screencap-v1-sdxl', 'John6666/duchaiten-pony-xl-no-score-v60-sdxl', 'John6666/mistoon-anime-ponyalpha-sdxl', 'John6666/mistoon-xl-copper-v20fast-sdxl', 'John6666/ebara-mfcg-pony-mix-v12-sdxl', 'John6666/t-ponynai3-v51-sdxl', 'John6666/t-ponynai3-v65-sdxl', 'John6666/prefect-pony-xl-v3-sdxl', 'John6666/prefect-pony-xl-v4-sdxl', 'John6666/mala-anime-mix-nsfw-pony-xl-v5-sdxl', 'John6666/wai-ani-nsfw-ponyxl-v10-sdxl', 'John6666/wai-real-mix-v11-sdxl', 'John6666/wai-shuffle-pdxl-v2-sdxl', 'John6666/wai-c-v6-sdxl', 'John6666/iniverse-mix-xl-sfwnsfw-pony-guofeng-v43-sdxl', 'John6666/sifw-annihilation-xl-v2-sdxl', 'John6666/photo-realistic-pony-v5-sdxl', 'John6666/pony-realism-v21main-sdxl', 'John6666/pony-realism-v22main-sdxl', 'John6666/cyberrealistic-pony-v63-sdxl', 'John6666/cyberrealistic-pony-v64-sdxl', 'John6666/cyberrealistic-pony-v65-sdxl', 'John6666/cyberrealistic-pony-v7-sdxl', 'GraydientPlatformAPI/realcartoon-pony-diffusion', 'John6666/nova-anime-xl-pony-v5-sdxl', 'John6666/autismmix-sdxl-autismmix-pony-sdxl', 'John6666/aimz-dream-real-pony-mix-v3-sdxl', 'John6666/prefectious-xl-nsfw-v10-sdxl', 'GraydientPlatformAPI/iniverseponyRealGuofeng49', 'John6666/duchaiten-pony-real-v11fix-sdxl', 'John6666/duchaiten-pony-real-v20-sdxl', 'John6666/duchaiten-pony-xl-no-score-v70-sdxl', 'Spestly/OdysseyXL-3.0', 'Spestly/OdysseyXL-4.0', 'KBlueLeaf/Kohaku-XL-Zeta', 'cagliostrolab/animagine-xl-3.1', 'yodayo-ai/kivotos-xl-2.0', 'yodayo-ai/holodayo-xl-2.1', 'yodayo-ai/clandestine-xl-1.0', 'digiplay/majicMIX_sombre_v2', 'digiplay/majicMIX_realistic_v6', 'digiplay/majicMIX_realistic_v7', 'digiplay/DreamShaper_8', 'digiplay/BeautifulArt_v1', 'digiplay/DarkSushi2.5D_v1', 'digiplay/darkphoenix3D_v1.1', 'digiplay/BeenYouLiteL11_diffusers', 'GraydientPlatformAPI/rev-animated2', 'myxlmynx/cyberrealistic_classic40', 'GraydientPlatformAPI/cyberreal6', 'GraydientPlatformAPI/cyberreal5', 'youknownothing/deliberate-v6', 'GraydientPlatformAPI/deliberate-cyber3', 'GraydientPlatformAPI/picx-real', 'GraydientPlatformAPI/perfectworld6', 'emilianJR/epiCRealism', 'votepurchase/counterfeitV30_v30', 'votepurchase/ChilloutMix', 'Meina/MeinaMix_V11', 'Meina/MeinaUnreal_V5', 'Meina/MeinaPastel_V7', 'GraydientPlatformAPI/realcartoon3d-17', 'GraydientPlatformAPI/realcartoon-pixar11', 'GraydientPlatformAPI/realcartoon-real17', 'nitrosocke/Ghibli-Diffusion',]
DIFFUSERS_FORMAT_LORAS = [ "nerijs/animation2k-flux", "XLabs-AI/flux-RealismLora", "Shakker-Labs/FLUX.1-dev-LoRA-Logo-Design",]
DOWNLOAD_EMBEDS = [ 'https://huggingface.co/datasets/Nerfgun3/bad_prompt/blob/main/bad_prompt_version2.pt', # 'https://huggingface.co/embed/negative/resolve/main/EasyNegativeV2.safetensors', # 'https://huggingface.co/embed/negative/resolve/main/bad-hands-5.pt',]
CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")HF_TOKEN = os.environ.get("HF_READ_TOKEN")
DIRECTORY_MODELS = 'models'DIRECTORY_LORAS = 'loras'DIRECTORY_VAES = 'vaes'DIRECTORY_EMBEDS = 'embedings'DIRECTORY_UPSCALERS = 'upscalers'
CACHE_HF = "/home/user/.cache/huggingface/hub/"STORAGE_ROOT = "/home/user/"
TASK_STABLEPY = { 'txt2img': 'txt2img', 'img2img': 'img2img', 'inpaint': 'inpaint', # 'canny T2I Adapter': 'sdxl_canny_t2i', # NO HAVE STEP CALLBACK PARAMETERS SO NOT WORKS WITH DIFFUSERS 0.29.0 # 'sketch T2I Adapter': 'sdxl_sketch_t2i', # 'lineart T2I Adapter': 'sdxl_lineart_t2i', # 'depth-midas T2I Adapter': 'sdxl_depth-midas_t2i', # 'openpose T2I Adapter': 'sdxl_openpose_t2i', 'openpose ControlNet': 'openpose', 'canny ControlNet': 'canny', 'mlsd ControlNet': 'mlsd', 'scribble ControlNet': 'scribble', 'softedge ControlNet': 'softedge', 'segmentation ControlNet': 'segmentation', 'depth ControlNet': 'depth', 'normalbae ControlNet': 'normalbae', 'lineart ControlNet': 'lineart', 'lineart_anime ControlNet': 'lineart_anime', 'shuffle ControlNet': 'shuffle', 'ip2p ControlNet': 'ip2p', 'optical pattern ControlNet': 'pattern', 'recolor ControlNet': 'recolor', 'tile ControlNet': 'tile', 'repaint ControlNet': 'repaint',}
TASK_MODEL_LIST = list(TASK_STABLEPY.keys())
UPSCALER_DICT_GUI = { None: None, **{bu: bu for bu in ALL_BUILTIN_UPSCALERS if bu not in ["HAT x4", "DAT x4", "DAT x3", "DAT x2", "SwinIR 4x"]}, # "RealESRGAN_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth", "RealESRNet_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth", # "RealESRGAN_x4plus_anime_6B": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth", # "RealESRGAN_x2plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth", # "realesr-animevideov3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth", # "realesr-general-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth", # "realesr-general-wdn-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth", "4x-UltraSharp": "https://huggingface.co/Shandypur/ESRGAN-4x-UltraSharp/resolve/main/4x-UltraSharp.pth", "4x_foolhardy_Remacri": "https://huggingface.co/FacehugmanIII/4x_foolhardy_Remacri/resolve/main/4x_foolhardy_Remacri.pth", "Remacri4xExtraSmoother": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/Remacri%204x%20ExtraSmoother.pth", "AnimeSharp4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/AnimeSharp%204x.pth", "lollypop": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/lollypop.pth", "RealisticRescaler4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/RealisticRescaler%204x.pth", "NickelbackFS4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/NickelbackFS%204x.pth"}
UPSCALER_KEYS = list(UPSCALER_DICT_GUI.keys())
DIFFUSERS_CONTROLNET_MODEL = [ "Automatic",
"brad-twinkl/controlnet-union-sdxl-1.0-promax", "xinsir/controlnet-union-sdxl-1.0", "xinsir/anime-painter", "Eugeoter/noob-sdxl-controlnet-canny", "Eugeoter/noob-sdxl-controlnet-lineart_anime", "Eugeoter/noob-sdxl-controlnet-depth", "Eugeoter/noob-sdxl-controlnet-normal", "Eugeoter/noob-sdxl-controlnet-softedge_hed", "Eugeoter/noob-sdxl-controlnet-scribble_pidinet", "Eugeoter/noob-sdxl-controlnet-scribble_hed", "Eugeoter/noob-sdxl-controlnet-manga_line", "Eugeoter/noob-sdxl-controlnet-lineart_realistic", "Eugeoter/noob-sdxl-controlnet-depth_midas-v1-1", "dimitribarbot/controlnet-openpose-sdxl-1.0-safetensors", "r3gm/controlnet-openpose-sdxl-1.0-fp16", "r3gm/controlnet-canny-scribble-integrated-sdxl-v2-fp16", "r3gm/controlnet-union-sdxl-1.0-fp16", "r3gm/controlnet-lineart-anime-sdxl-fp16", "r3gm/control_v1p_sdxl_qrcode_monster_fp16", "r3gm/controlnet-tile-sdxl-1.0-fp16", "r3gm/controlnet-recolor-sdxl-fp16", "r3gm/controlnet-openpose-twins-sdxl-1.0-fp16", "r3gm/controlnet-qr-pattern-sdxl-fp16", "Yakonrus/SDXL_Controlnet_Tile_Realistic_v2", "TheMistoAI/MistoLine", "briaai/BRIA-2.3-ControlNet-Recoloring", "briaai/BRIA-2.3-ControlNet-Canny",
"lllyasviel/control_v11p_sd15_openpose", "lllyasviel/control_v11p_sd15_canny", "lllyasviel/control_v11p_sd15_mlsd", "lllyasviel/control_v11p_sd15_scribble", "lllyasviel/control_v11p_sd15_softedge", "lllyasviel/control_v11p_sd15_seg", "lllyasviel/control_v11f1p_sd15_depth", "lllyasviel/control_v11p_sd15_normalbae", "lllyasviel/control_v11p_sd15_lineart", "lllyasviel/control_v11p_sd15s2_lineart_anime", "lllyasviel/control_v11e_sd15_shuffle", "lllyasviel/control_v11e_sd15_ip2p", "lllyasviel/control_v11p_sd15_inpaint", "monster-labs/control_v1p_sd15_qrcode_monster", "lllyasviel/control_v11f1e_sd15_tile", "latentcat/control_v1p_sd15_brightness", "yuanqiuye/qrcode_controlnet_v3",
"Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro", # "Shakker-Labs/FLUX.1-dev-ControlNet-Pose", # "Shakker-Labs/FLUX.1-dev-ControlNet-Depth", # "jasperai/Flux.1-dev-Controlnet-Upscaler", # "jasperai/Flux.1-dev-Controlnet-Depth", # "jasperai/Flux.1-dev-Controlnet-Surface-Normals", # "XLabs-AI/flux-controlnet-canny-diffusers", # "XLabs-AI/flux-controlnet-hed-diffusers", # "XLabs-AI/flux-controlnet-depth-diffusers", # "InstantX/FLUX.1-dev-Controlnet-Union", # "InstantX/FLUX.1-dev-Controlnet-Canny",]
PROMPT_W_OPTIONS = [ ("Compel format: (word)weight", "Compel"), ("Classic format: (word:weight)", "Classic"), ("Classic-original format: (word:weight)", "Classic-original"), ("Classic-no_norm format: (word:weight)", "Classic-no_norm"), ("Classic-sd_embed format: (word:weight)", "Classic-sd_embed"), ("Classic-ignore", "Classic-ignore"), ("None", "None"),]
WARNING_MSG_VAE = ( "Use the right VAE for your model to maintain image quality. The wrong" " VAE can lead to poor results, like blurriness in the generated images.")
SDXL_TASK = [k for k, v in TASK_STABLEPY.items() if v in SDXL_TASKS]SD_TASK = [k for k, v in TASK_STABLEPY.items() if v in SD15_TASKS]FLUX_TASK = list(TASK_STABLEPY.keys())[:3] + [k for k, v in TASK_STABLEPY.items() if v in FLUX_CN_UNION_MODES.keys()]
MODEL_TYPE_TASK = { "SD 1.5": SD_TASK, "SDXL": SDXL_TASK, "FLUX": FLUX_TASK,}
MODEL_TYPE_CLASS = { "diffusers:StableDiffusionPipeline": "SD 1.5", "diffusers:StableDiffusionXLPipeline": "SDXL", "diffusers:FluxPipeline": "FLUX",}
DIFFUSECRAFT_CHECKPOINT_NAME = { "sd1.5": "SD 1.5", "sdxl": "SDXL", "flux-dev": "FLUX", "flux-schnell": "FLUX",}
POST_PROCESSING_SAMPLER = ["Use same sampler"] + [ name_s for name_s in scheduler_names if "Auto-Loader" not in name_s]
IP_MODELS = []ALL_IPA = sorted(set(IP_ADAPTERS_SD + IP_ADAPTERS_SDXL))
for origin_name in ALL_IPA: suffixes = [] if origin_name in IP_ADAPTERS_SD: suffixes.append("sd1.5") if origin_name in IP_ADAPTERS_SDXL: suffixes.append("sdxl") ref_name = f"{origin_name} ({'/'.join(suffixes)})" IP_MODELS.append((ref_name, origin_name))
MODE_IP_OPTIONS = ["original", "style", "layout", "style+layout"]
SUBTITLE_GUI = ( "### This demo uses [diffusers](https://github.com/huggingface/diffusers)" " to perform different tasks in image generation.")
HELP_GUI = ( """### Help: - The current space runs on a ZERO GPU which is assigned for approximately 60 seconds; Therefore, if you submit expensive tasks, the operation may be canceled upon reaching the maximum allowed time with 'GPU TASK ABORTED'. - Distorted or strange images often result from high prompt weights, so it's best to use low weights and scales, and consider using Classic variants like 'Classic-original'. - For better results with Pony Diffusion, try using sampler DPM++ 1s or DPM2 with Compel or Classic prompt weights. """)
EXAMPLES_GUI_HELP = ( """### The following examples perform specific tasks: 1. Generation with SDXL and upscale 2. Generation with FLUX dev 3. ControlNet Canny SDXL 4. Optical pattern (Optical illusion) SDXL 5. Convert an image to a coloring drawing 6. V prediction model inference 7. V prediction model sd_embed variant inference 8. ControlNet OpenPose SD 1.5 and Latent upscale
- Different tasks can be performed, such as img2img or using the IP adapter, to preserve a person's appearance or a specific style based on an image. """)
EXAMPLES_GUI = [ [ "splatter paint theme, 1girl, frame center, pretty face, face with artistic paint artwork, feminism, long hair, upper body view, futuristic expression illustrative painted background, origami, stripes, explosive paint splashes behind her, hand on cheek pose, strobe lighting, masterpiece photography creative artwork, golden morning light, highly detailed, masterpiece, best quality, very aesthetic, absurdres", "logo, artist name, (worst quality, normal quality), bad-artist, ((bad anatomy)), ((bad hands)), ((bad proportions)), ((duplicate limbs)), ((fused limbs)), ((interlocking fingers)), ((poorly drawn face)), high contrast., score_6, score_5, score_4, lowres, (bad), text, error, fewer, extra, missing, worst quality, jpeg artifacts, low quality, watermark, unfinished, displeasing, oldest, early, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]", 28, 5.0, -1, "None", 0.33, "DPM++ 2M SDE", 1152, 896, "John6666/noobai-xl-nai-xl-epsilonpred10version-sdxl", "txt2img", "image.webp", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Classic-no_norm", "Nearest", 45, False, ], [ "a digital illustration of a movie poster titled 'Finding Emo', finding nemo parody poster, featuring a depressed cartoon clownfish with black emo hair, eyeliner, and piercings, bored expression, swimming in a dark underwater scene, in the background, movie title in a dripping, grungy font, moody blue and purple color palette", "", 24, 3.5, -1, "None", 0.33, "FlowMatch Euler", 1152, 896, "black-forest-labs/FLUX.1-dev", "txt2img", None, # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Classic", None, 70, True, ], [ "((masterpiece)), best quality, blonde disco girl, detailed face, realistic face, realistic hair, dynamic pose, pink pvc, intergalactic disco background, pastel lights, dynamic contrast, airbrush, fine detail, 70s vibe, midriff", "(worst quality:1.2), (bad quality:1.2), (poor quality:1.2), (missing fingers:1.2), bad-artist-anime, bad-artist, bad-picture-chill-75v", 48, 3.5, -1, "None", 0.33, "DPM++ 2M SDE Ef", 1024, 1024, "John6666/epicrealism-xl-v10kiss2-sdxl", "canny ControlNet", "image.webp", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Classic", None, 44, False, ], [ "cinematic scenery old city ruins", "(worst quality, low quality, illustration, 3d, 2d, painting, cartoons, sketch), (illustration, 3d, 2d, painting, cartoons, sketch, blurry, film grain, noise), (low quality, worst quality:1.2)", 50, 4.0, -1, "None", 0.33, "Euler a", 1024, 1024, "SG161222/RealVisXL_V5.0", "optical pattern ControlNet", "spiral_no_transparent.png", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.05, # cn start 0.8, # cn end "Classic", None, 35, False, ], [ "black and white, line art, coloring drawing, clean line art, black strokes, no background, white, black, free lines, black scribbles, on paper, A blend of comic book art and lineart full of black and white color, masterpiece, high-resolution, trending on Pixiv fan box, palette knife, brush strokes, two-dimensional, planar vector, T-shirt design, stickers, and T-shirt design, vector art, fantasy art, Adobe Illustrator, hand-painted, digital painting, low polygon, soft lighting, aerial view, isometric style, retro aesthetics, 8K resolution, black sketch lines, monochrome, invert color", "color, red, green, yellow, colored, duplicate, blurry, abstract, disfigured, deformed, animated, toy, figure, framed, 3d, bad art, poorly drawn, extra limbs, close up, b&w, weird colors, blurry, watermark, blur haze, 2 heads, long neck, watermark, elongated body, cropped image, out of frame, draft, deformed hands, twisted fingers, double image, malformed hands, multiple heads, extra limb, ugly, poorly drawn hands, missing limb, cut-off, over satured, grain, lowères, bad anatomy, poorly drawn face, mutation, mutated, floating limbs, disconnected limbs, out of focus, long body, disgusting, extra fingers, groos proportions, missing arms, mutated hands, cloned face, missing legs, ugly, tiling, poorly drawn hands, poorly drawn feet, poorly drawn face, out of frame, extra limbs, disfigured, deformed, body out of frame, blurry, bad anatomy, blurred, watermark, grainy, signature, cut off, draft, deformed, blurry, bad anatomy, disfigured, poorly drawn face, mutation, bluelish, blue", 20, 4.0, -1, "loras/Coloring_book_-_LineArt.safetensors", 1.0, "DPM++ 2M SDE", 1024, 1024, "eienmojiki/Anything-XL", "lineart ControlNet", "color_image.png", # img conttol 896, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Compel", None, 35, False, ], [ "[mochizuki_shiina], [syuri22], newest, reimu, solo, outdoors, water, flower, lantern", "worst quality, normal quality, old, sketch,", 28, 7.0, -1, "None", 0.33, "DPM 3M Ef", 1600, 1024, "Laxhar/noobai-XL-Vpred-1.0", "txt2img", "color_image.png", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Classic", None, 30, False, ], [ "[mochizuki_shiina], [syuri22], newest, multiple girls, 2girls, earrings, jewelry, gloves, purple eyes, black hair, looking at viewer, nail polish, hat, smile, open mouth, fingerless gloves, sleeveless, :d, upper body, blue eyes, closed mouth, black gloves, hands up, long hair, shirt, bare shoulders, white headwear, blush, black headwear, blue nails, upper teeth only, short hair, white gloves, white shirt, teeth, rabbit hat, star earrings, purple nails, pink hair, detached sleeves, fingernails, fake animal ears, animal hat, sleeves past wrists, black shirt, medium hair, fur trim, sleeveless shirt, turtleneck, long sleeves, rabbit ears, star \\(symbol\\)", "worst quality, normal quality, old, sketch,", 28, 7.0, -1, "None", 0.33, "DPM 3M Ef", 1600, 1024, "Laxhar/noobai-XL-Vpred-1.0", "txt2img", "color_image.png", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Classic-sd_embed", None, 30, False, ], [ "1girl,face,curly hair,red hair,white background,", "(worst quality:2),(low quality:2),(normal quality:2),lowres,watermark,", 38, 5.0, -1, "None", 0.33, "DPM++ 2M SDE", 512, 512, "digiplay/majicMIX_realistic_v7", "openpose ControlNet", "image.webp", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 0.9, # cn end "Classic-original", "Latent (antialiased)", 46, False, ],]
RESOURCES = ( """### Resources - John6666's space has some great features you might find helpful [link](https://huggingface.co/spaces/John6666/DiffuseCraftMod). - You can also try the image generator in Colab’s free tier, which provides free GPU [link](https://github.com/R3gm/SD_diffusers_interactive). """)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130import spacesimport gradio as grfrom stablepy import Preprocessor
PREPROCESSOR_TASKS_LIST = [ "Canny", "Openpose", "DPT", "Midas", "ZoeDepth", "DepthAnything", "HED", "PidiNet", "TEED", "Lineart", "LineartAnime", "Anyline", "Lineart standard", "SegFormer", "UPerNet", "ContentShuffle", "Recolor", "Blur", "MLSD", "NormalBae",]
preprocessor = Preprocessor()
def process_inputs( image, name, resolution, precessor_resolution, low_threshold, high_threshold, value_threshod, distance_threshold, recolor_mode, recolor_gamma_correction, blur_k_size, pre_openpose_extra, hed_scribble, pre_pidinet_safe, pre_lineart_coarse, use_cuda,): if not image: raise ValueError("To use this, simply upload an image.")
preprocessor.load(name, False)
params = dict( image_resolution=resolution, detect_resolution=precessor_resolution, low_threshold=low_threshold, high_threshold=high_threshold, thr_v=value_threshod, thr_d=distance_threshold, mode=recolor_mode, gamma_correction=recolor_gamma_correction, blur_sigma=blur_k_size, hand_and_face=pre_openpose_extra, scribble=hed_scribble, safe=pre_pidinet_safe, coarse=pre_lineart_coarse, )
if use_cuda: @spaces.GPU(duration=15) def wrapped_func(): preprocessor.to("cuda") return preprocessor(image, **params) return wrapped_func()
return preprocessor(image, **params)
def preprocessor_tab(): with gr.Row(): with gr.Column(): pre_image = gr.Image(label="Image", type="pil", sources=["upload"]) pre_options = gr.Dropdown(label="Preprocessor", choices=PREPROCESSOR_TASKS_LIST, value=PREPROCESSOR_TASKS_LIST[0]) pre_img_resolution = gr.Slider( minimum=64, maximum=4096, step=64, value=1024, label="Image Resolution", info="The maximum proportional size of the generated image based on the uploaded image." ) pre_start = gr.Button(value="PROCESS IMAGE", variant="primary") with gr.Accordion("Advanced Settings", open=False): with gr.Column(): pre_processor_resolution = gr.Slider(minimum=64, maximum=2048, step=64, value=512, label="Preprocessor Resolution") pre_low_threshold = gr.Slider(minimum=1, maximum=255, step=1, value=100, label="'CANNY' low threshold") pre_high_threshold = gr.Slider(minimum=1, maximum=255, step=1, value=200, label="'CANNY' high threshold") pre_value_threshold = gr.Slider(minimum=1, maximum=2.0, step=0.01, value=0.1, label="'MLSD' Hough value threshold") pre_distance_threshold = gr.Slider(minimum=1, maximum=20.0, step=0.01, value=0.1, label="'MLSD' Hough distance threshold") pre_recolor_mode = gr.Dropdown(label="'RECOLOR' mode", choices=["luminance", "intensity"], value="luminance") pre_recolor_gamma_correction = gr.Number(minimum=0., maximum=25., value=1., step=0.001, label="'RECOLOR' gamma correction") pre_blur_k_size = gr.Number(minimum=0, maximum=100, value=9, step=1, label="'BLUR' sigma") pre_openpose_extra = gr.Checkbox(value=True, label="'OPENPOSE' face and hand") pre_hed_scribble = gr.Checkbox(value=False, label="'HED' scribble") pre_pidinet_safe = gr.Checkbox(value=False, label="'PIDINET' safe") pre_lineart_coarse = gr.Checkbox(value=False, label="'LINEART' coarse") pre_use_cuda = gr.Checkbox(value=False, label="Use CUDA")
with gr.Column(): pre_result = gr.Image(label="Result", type="pil", interactive=False, format="png")
pre_start.click( fn=process_inputs, inputs=[ pre_image, pre_options, pre_img_resolution, pre_processor_resolution, pre_low_threshold, pre_high_threshold, pre_value_threshold, pre_distance_threshold, pre_recolor_mode, pre_recolor_gamma_correction, pre_blur_k_size, pre_openpose_extra, pre_hed_scribble, pre_pidinet_safe, pre_lineart_coarse, pre_use_cuda, ], outputs=[pre_result], )123git-lfsaria2 -yffmpeg12345stablepy==0.6.0torch==2.2.0gdownopencv-pythonunidecode123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485import osimport reimport gradio as grfrom constants import ( DIFFUSERS_FORMAT_LORAS, CIVITAI_API_KEY, HF_TOKEN, MODEL_TYPE_CLASS, DIRECTORY_LORAS, DIRECTORY_MODELS, DIFFUSECRAFT_CHECKPOINT_NAME, CACHE_HF, STORAGE_ROOT,)from huggingface_hub import HfApifrom huggingface_hub import snapshot_downloadfrom diffusers import DiffusionPipelinefrom huggingface_hub import model_info as model_info_datafrom diffusers.pipelines.pipeline_loading_utils import variant_compatible_siblingsfrom stablepy.diffusers_vanilla.utils import checkpoint_model_typefrom pathlib import PosixPathfrom unidecode import unidecodeimport urllib.parseimport copyimport requestsfrom requests.adapters import HTTPAdapterfrom urllib3.util import Retryimport shutilimport subprocess
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'
def request_json_data(url): model_version_id = url.split('/')[-1] if "?modelVersionId=" in model_version_id: match = re.search(r'modelVersionId=(\d+)', url) model_version_id = match.group(1)
endpoint_url = f"https://civitai.com/api/v1/model-versions/{model_version_id}"
params = {} headers = {'User-Agent': USER_AGENT, 'content-type': 'application/json'} session = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504]) session.mount("https://", HTTPAdapter(max_retries=retries))
try: result = session.get(endpoint_url, params=params, headers=headers, stream=True, timeout=(3.0, 15)) result.raise_for_status() json_data = result.json() return json_data if json_data else None except Exception as e: print(f"Error: {e}") return None
class ModelInformation: def __init__(self, json_data): self.model_version_id = json_data.get("id", "") self.model_id = json_data.get("modelId", "") self.download_url = json_data.get("downloadUrl", "") self.model_url = f"https://civitai.com/models/{self.model_id}?modelVersionId={self.model_version_id}" self.filename_url = next( (v.get("name", "") for v in json_data.get("files", []) if str(self.model_version_id) in v.get("downloadUrl", "") and v.get("type", "Model") == "Model"), "" ) self.filename_url = self.filename_url if self.filename_url else "" self.description = json_data.get("description", "") if self.description is None: self.description = "" self.model_name = json_data.get("model", {}).get("name", "") self.model_type = json_data.get("model", {}).get("type", "") self.nsfw = json_data.get("model", {}).get("nsfw", False) self.poi = json_data.get("model", {}).get("poi", False) self.images = [img.get("url", "") for img in json_data.get("images", [])] self.example_prompt = json_data.get("trainedWords", [""])[0] if json_data.get("trainedWords") else "" self.original_json = copy.deepcopy(json_data)
def retrieve_model_info(url): json_data = request_json_data(url) if not json_data: return None model_descriptor = ModelInformation(json_data) return model_descriptor
def download_things(directory, url, hf_token="", civitai_api_key="", romanize=False): url = url.strip() downloaded_file_path = None
if "drive.google.com" in url: original_dir = os.getcwd() os.chdir(directory) os.system(f"gdown --fuzzy {url}") os.chdir(original_dir) elif "huggingface.co" in url: url = url.replace("?download=true", "") # url = urllib.parse.quote(url, safe=':/') # fix encoding if "/blob/" in url: url = url.replace("/blob/", "/resolve/") user_header = f'"Authorization: Bearer {hf_token}"'
filename = unidecode(url.split('/')[-1]) if romanize else url.split('/')[-1]
if hf_token: os.system(f"aria2c --console-log-level=error --summary-interval=10 --header={user_header} -c -x 16 -k 1M -s 16 {url} -d {directory} -o {filename}") else: os.system(f"aria2c --optimize-concurrent-downloads --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 {url} -d {directory} -o {filename}")
downloaded_file_path = os.path.join(directory, filename)
elif "civitai.com" in url:
if not civitai_api_key: print("\033[91mYou need an API key to download Civitai models.\033[0m")
model_profile = retrieve_model_info(url) if ( model_profile is not None and model_profile.download_url and model_profile.filename_url ): url = model_profile.download_url filename = unidecode(model_profile.filename_url) if romanize else model_profile.filename_url else: if "?" in url: url = url.split("?")[0] filename = ""
url_dl = url + f"?token={civitai_api_key}" print(f"Filename: {filename}")
param_filename = "" if filename: param_filename = f"-o '{filename}'"
aria2_command = ( f'aria2c --console-log-level=error --summary-interval=10 -c -x 16 ' f'-k 1M -s 16 -d "{directory}" {param_filename} "{url_dl}"' ) os.system(aria2_command)
if param_filename and os.path.exists(os.path.join(directory, filename)): downloaded_file_path = os.path.join(directory, filename)
# # PLAN B # # Follow the redirect to get the actual download URL # curl_command = ( # f'curl -L -sI --connect-timeout 5 --max-time 5 ' # f'-H "Content-Type: application/json" ' # f'-H "Authorization: Bearer {civitai_api_key}" "{url}"' # )
# headers = os.popen(curl_command).read()
# # Look for the redirected "Location" URL # location_match = re.search(r'location: (.+)', headers, re.IGNORECASE)
# if location_match: # redirect_url = location_match.group(1).strip()
# # Extract the filename from the redirect URL's "Content-Disposition" # filename_match = re.search(r'filename%3D%22(.+?)%22', redirect_url) # if filename_match: # encoded_filename = filename_match.group(1) # # Decode the URL-encoded filename # decoded_filename = urllib.parse.unquote(encoded_filename)
# filename = unidecode(decoded_filename) if romanize else decoded_filename # print(f"Filename: {filename}")
# aria2_command = ( # f'aria2c --console-log-level=error --summary-interval=10 -c -x 16 ' # f'-k 1M -s 16 -d "{directory}" -o "{filename}" "{redirect_url}"' # ) # return_code = os.system(aria2_command)
# # if return_code != 0: # # raise RuntimeError(f"Failed to download file: {filename}. Error code: {return_code}") # downloaded_file_path = os.path.join(directory, filename) # if not os.path.exists(downloaded_file_path): # downloaded_file_path = None
# if not downloaded_file_path: # # Old method # if "?" in url: # url = url.split("?")[0] # url = url + f"?token={civitai_api_key}" # os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
else: os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
return downloaded_file_path
def get_model_list(directory_path): model_list = [] valid_extensions = {'.ckpt', '.pt', '.pth', '.safetensors', '.bin'}
for filename in os.listdir(directory_path): if os.path.splitext(filename)[1] in valid_extensions: # name_without_extension = os.path.splitext(filename)[0] file_path = os.path.join(directory_path, filename) # model_list.append((name_without_extension, file_path)) model_list.append(file_path) print('\033[34mFILE: ' + file_path + '\033[0m') return model_list
def extract_parameters(input_string): parameters = {} input_string = input_string.replace("\n", "")
if "Negative prompt:" not in input_string: if "Steps:" in input_string: input_string = input_string.replace("Steps:", "Negative prompt: Steps:") else: print("Invalid metadata") parameters["prompt"] = input_string return parameters
parm = input_string.split("Negative prompt:") parameters["prompt"] = parm[0].strip() if "Steps:" not in parm[1]: print("Steps not detected") parameters["neg_prompt"] = parm[1].strip() return parameters parm = parm[1].split("Steps:") parameters["neg_prompt"] = parm[0].strip() input_string = "Steps:" + parm[1]
# Extracting Steps steps_match = re.search(r'Steps: (\d+)', input_string) if steps_match: parameters['Steps'] = int(steps_match.group(1))
# Extracting Size size_match = re.search(r'Size: (\d+x\d+)', input_string) if size_match: parameters['Size'] = size_match.group(1) width, height = map(int, parameters['Size'].split('x')) parameters['width'] = width parameters['height'] = height
# Extracting other parameters other_parameters = re.findall(r'([^,:]+): (.*?)(?=, [^,:]+:|$)', input_string) for param in other_parameters: parameters[param[0].strip()] = param[1].strip('"')
return parameters
def get_my_lora(link_url, romanize): l_name = "" for url in [url.strip() for url in link_url.split(',')]: if not os.path.exists(f"./loras/{url.split('/')[-1]}"): l_name = download_things(DIRECTORY_LORAS, url, HF_TOKEN, CIVITAI_API_KEY, romanize) new_lora_model_list = get_model_list(DIRECTORY_LORAS) new_lora_model_list.insert(0, "None") new_lora_model_list = new_lora_model_list + DIFFUSERS_FORMAT_LORAS msg_lora = "Downloaded" if l_name: msg_lora += f": <b>{l_name}</b>" print(msg_lora)
return gr.update( choices=new_lora_model_list ), gr.update( choices=new_lora_model_list ), gr.update( choices=new_lora_model_list ), gr.update( choices=new_lora_model_list ), gr.update( choices=new_lora_model_list ), gr.update( choices=new_lora_model_list ), gr.update( choices=new_lora_model_list ), gr.update( value=msg_lora )
def info_html(json_data, title, subtitle): return f""" <div style='padding: 0; border-radius: 10px;'> <p style='margin: 0; font-weight: bold;'>{title}</p> <details> <summary>Details</summary> <p style='margin: 0; font-weight: bold;'>{subtitle}</p> </details> </div> """
def get_model_type(repo_id: str): api = HfApi(token=os.environ.get("HF_TOKEN")) # if use private or gated model default = "SD 1.5" try: if os.path.exists(repo_id): tag, _, _, _ = checkpoint_model_type(repo_id) return DIFFUSECRAFT_CHECKPOINT_NAME[tag] else: model = api.model_info(repo_id=repo_id, timeout=5.0) tags = model.tags for tag in tags: if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)
except Exception: return default return default
def restart_space(repo_id: str, factory_reboot: bool): api = HfApi(token=os.environ.get("HF_TOKEN")) try: runtime = api.get_space_runtime(repo_id=repo_id) if runtime.stage == "RUNNING": api.restart_space(repo_id=repo_id, factory_reboot=factory_reboot) print(f"Restarting space: {repo_id}") else: print(f"Space {repo_id} is in stage: {runtime.stage}") except Exception as e: print(e)
def extract_exif_data(image): if image is None: return ""
try: metadata_keys = ['parameters', 'metadata', 'prompt', 'Comment']
for key in metadata_keys: if key in image.info: return image.info[key]
return str(image.info)
except Exception as e: return f"Error extracting metadata: {str(e)}"
def create_mask_now(img, invert): import numpy as np import time
time.sleep(0.5)
transparent_image = img["layers"][0]
# Extract the alpha channel alpha_channel = np.array(transparent_image)[:, :, 3]
# Create a binary mask by thresholding the alpha channel binary_mask = alpha_channel > 1
if invert: print("Invert") # Invert the binary mask so that the drawn shape is white and the rest is black binary_mask = np.invert(binary_mask)
# Convert the binary mask to a 3-channel RGB mask rgb_mask = np.stack((binary_mask,) * 3, axis=-1)
# Convert the mask to uint8 rgb_mask = rgb_mask.astype(np.uint8) * 255
return img["background"], rgb_mask
def download_diffuser_repo(repo_name: str, model_type: str, revision: str = "main", token=True):
variant = None if token is True and not os.environ.get("HF_TOKEN"): token = None
if model_type == "SDXL": info = model_info_data( repo_name, token=token, revision=revision, timeout=5.0, )
filenames = {sibling.rfilename for sibling in info.siblings} model_filenames, variant_filenames = variant_compatible_siblings( filenames, variant="fp16" )
if len(variant_filenames): variant = "fp16"
if model_type == "FLUX": cached_folder = snapshot_download( repo_id=repo_name, allow_patterns="transformer/*" ) else: cached_folder = DiffusionPipeline.download( pretrained_model_name=repo_name, force_download=False, token=token, revision=revision, # mirror="https://hf-mirror.com", variant=variant, use_safetensors=True, trust_remote_code=False, timeout=5.0, )
if isinstance(cached_folder, PosixPath): cached_folder = cached_folder.as_posix()
# Task model # from huggingface_hub import hf_hub_download # hf_hub_download( # task_model, # filename="diffusion_pytorch_model.safetensors", # fix fp16 variant # )
return cached_folder
def get_folder_size_gb(folder_path): result = subprocess.run(["du", "-s", folder_path], capture_output=True, text=True)
total_size_kb = int(result.stdout.split()[0]) total_size_gb = total_size_kb / (1024 ** 2)
return total_size_gb
def get_used_storage_gb(): try: used_gb = get_folder_size_gb(STORAGE_ROOT) print(f"Used Storage: {used_gb:.2f} GB") except Exception as e: used_gb = 999 print(f"Error while retrieving the used storage: {e}.")
return used_gb
def delete_model(removal_candidate): print(f"Removing: {removal_candidate}")
if os.path.exists(removal_candidate): os.remove(removal_candidate) else: diffusers_model = f"{CACHE_HF}{DIRECTORY_MODELS}--{removal_candidate.replace('/', '--')}" if os.path.isdir(diffusers_model): shutil.rmtree(diffusers_model)
def progress_step_bar(step, total): # Calculate the percentage for the progress bar width percentage = min(100, ((step / total) * 100))
return f""" <div style="position: relative; width: 100%; background-color: gray; border-radius: 5px; overflow: hidden;"> <div style="width: {percentage}%; height: 17px; background-color: #800080; transition: width 0.5s;"></div> <div style="position: absolute; width: 100%; text-align: center; color: white; top: 0; line-height: 19px; font-size: 13px;"> {int(percentage)}% </div> </div> """
def html_template_message(msg): return f""" <div style="position: relative; width: 100%; background-color: gray; border-radius: 5px; overflow: hidden;"> <div style="width: 0%; height: 17px; background-color: #800080; transition: width 0.5s;"></div> <div style="position: absolute; width: 100%; text-align: center; color: white; top: 0; line-height: 19px; font-size: 14px; font-weight: bold; text-shadow: 1px 1px 2px black;"> {msg} </div> </div> """
def escape_html(text): """Escapes HTML special characters in the input text.""" return text.replace("<", "<").replace(">", ">").replace("\n", "<br>").gitattributesAdded+35
README.mdAdded+16
app.pyAdded+1371
color_image.pngAdded

constants.pyAdded+585
image.webpAdded

image_processor.pyAdded+130
packages.txtAdded+3
requirements.txtAdded+5
spiral_no_transparent.pngAdded

utils.pyAdded+485