Spaces:
Running on Zero
Running on Zero
new update
Browse filesFiles changed (9)
- .gitignoreAdded+207
- README.md+1-1
- app.py+219-90
- constants.py+49-23
- image_processor.py+2-2
- packages.txt+1-1
- pre-requirements.txtAdded+1
- requirements.txt+8-2
- utils.py+181-104
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207# Byte-compiled / optimized / DLL files__pycache__/*.py[codz]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py.cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# UV# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.#uv.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock#poetry.toml
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.# https://pdm-project.org/en/latest/usage/project/#working-with-version-control#pdm.lock#pdm.toml.pdm-python.pdm-build/
# pixi# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.#pixi.lock# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one# in the .venv directory. It is recommended not to include this directory in version control..pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.envrc.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/
# Abstra# Abstra is an AI-powered process automation framework.# Ignore directories containing user credentials, local state, and settings.# Learn more at https://abstra.io/docs.abstra/
# Visual Studio Code# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore# and can be added to the global gitignore or merged into this file. However, if you prefer, # you could uncomment the following to ignore the entire vscode folder# .vscode/
# Ruff stuff:.ruff_cache/
# PyPI configuration file.pypirc
# Cursor# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data# refer to https://docs.cursor.com/context/ignore-files.cursorignore.cursorindexingignore
# Marimomarimo/_static/marimo/_lsp/__marimo__/3 unmodified lines456789103 unmodified linescolorFrom: redcolorTo: pinksdk: gradiosdk_version: 4.31.3app_file: app.pypinned: truelicense: mit3 unmodified lines456789103 unmodified linescolorFrom: redcolorTo: pinksdk: gradiosdk_version: 5.44.1app_file: app.pypinned: truelicense: mit
1234534 unmodified lines40414243444514 unmodified lines6061626364656 unmodified lines72737475767778798081821 unmodified line8485868788899091929394959697989910010110211 unmodified lines1141151161171181191201211221231241251261271283 unmodified lines1321331341351361371383 unmodified lines1421431441451461479 unmodified lines1571581591601611624 unmodified lines16716816917017117217317417517617717817918018138 unmodified lines2202212222232242252262272282293 unmodified lines233234235236237238239147 unmodified lines38738838939039139239391 unmodified lines48548648748848949049149249349449549649749849950050150250351 unmodified lines55555655755855956056156256356456523 unmodified lines589590591592593594595102 unmodified lines69869970070170270370410 unmodified lines7157167177187197207212 unmodified lines72472572672772872973073173273373442 unmodified lines77777877978078178278329 unmodified lines8138148158168178188197 unmodified lines8278288298308318321 unmodified line8348358368378388398408418421 unmodified line8448458468478488498508518528538548558568578581 unmodified line8608618628638648658668671 unmodified line8698708718728738748758768778788798808818828838848858868878888898908918926 unmodified lines8999009019029039049051 unmodified line90790890991091191291310 unmodified lines9249259269279289299305 unmodified lines9369379389399409419429439449452 unmodified lines94894995095195295395458 unmodified lines1013101410151016101710181019102028 unmodified lines104910501051105210531054105543 unmodified lines1099110011011102110311041105110611071108110911101111111211131114111511161117111849 unmodified lines1168116911701171117211731174117511761177185 unmodified lines1363136413651366136713681369137013711372import spacesimport osfrom stablepy import (Model_Diffusers,SCHEDULE_TYPE_OPTIONS,34 unmodified linesDIFFUSERS_CONTROLNET_MODEL,IP_MODELS,MODE_IP_OPTIONS,)from stablepy.diffusers_vanilla.style_prompt_config import STYLE_NAMESimport torch14 unmodified linesprogress_step_bar,html_template_message,escape_html,)from image_processor import preprocessor_tabfrom datetime import datetime6 unmodified lines# import urllib.parseimport subprocesssubprocess.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:1 unmodified line# 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)11 unmodified linesprint('\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######################## GUI3 unmodified lineswarnings.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; }3 unmodified lines"""class GuiSD:def __init__(self, stream=True):self.model = None9 unmodified linesremoval_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 = [4 unmodified linesdef load_new_model(self, model_name, vae_model, task, controlnet_model, progress=gr.Progress(track_tqdm=True)):# download link model > model_nameself.update_storage_models()vae_model = vae_model if vae_model != "None" else Nonemodel_type = get_model_type(model_name)dtype_model = torch.bfloat16 if model_type == "FLUX" else torch.float16if not os.path.exists(model_name):print("debug", model_name, vae_model, task, controlnet_model)_ = download_diffuser_repo(repo_name=model_name,model_type=model_type,38 unmodified linestype_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()3 unmodified linesprint("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],147 unmodified linesvae_msg = f"VAE: {vae_model}" if vae_model else ""msg_lora = ""print("Config model:", model_name, vae_model, loras_list)task = TASK_STABLEPY[task]91 unmodified lines"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"51 unmodified lines# kwargs for diffusers pipelineif guidance_rescale:pipe_params["guidance_rescale"] = guidance_rescaleself.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 = 0info_images = gr.update()23 unmodified linesdownload_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)])102 unmodified lines@spaces.GPU(duration=15)def process_upscale(image, upscaler_name, upscaler_size):if image is None: return Nonefrom stablepy.diffusers_vanilla.utils import save_pil_image_with_metadatafrom stablepy import load_upscaler_model10 unmodified linesname_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)2 unmodified lines# 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"):42 unmodified linesactual_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")29 unmodified lines"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)7 unmodified linesparameters["Sampler"] = value_samplerparameters["Schedule type"] = s_typefor key, val in parameters.items():# print(val)if key in valid_keys:1 unmodified lineif key == "Sampler":if val not in scheduler_names:continueif key == "Schedule type":if val not in SCHEDULE_TYPE_OPTIONS:val = "Automatic"elif key == "Clip skip":if "," in str(val):val = val.replace(",", "")1 unmodified lineval = Trueif 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 = Trueif key in ["CFG scale", "PAG"]:val = float(val)if key == "Model":filtered_models = [m for m in model_list if val in m]1 unmodified lineval = filtered_models[0]else:val = name_modelif key == "Seed":continuevalid_receptors[key] = gr.update(value=val)# print(val, type(val))# print(valid_receptors)1 unmodified lineprint(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(6 unmodified linesrun_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])1 unmodified lineupscaler_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")10 unmodified linesreturn 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")5 unmodified lineslora_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(2 unmodified lineslines=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(58 unmodified linespreprocess_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")28 unmodified linesgr.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")43 unmodified lineshires_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)49 unmodified lines# "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)185 unmodified linesshow_progress="minimal",)app.queue()app.launch(show_error=True,debug=True,allowed_paths=["./images/"],)12345634 unmodified lines4142434445464714 unmodified lines626364656667686 unmodified lines75767778798081828384858687888990911 unmodified line9394959697989910010110210310410510610711 unmodified lines1191201211221231241251261271281291301311321331343 unmodified lines1381391401411421431441451461471481491501511521531543 unmodified lines1581591601611621631641651661671681699 unmodified lines1791801811821831841851861871881891901911921934 unmodified lines19819920020120220320420520620720820921021121221321421521621721838 unmodified lines2572582592602612622632642652663 unmodified lines270271272273274275276277147 unmodified lines42542642742842943043191 unmodified lines52352452552652752852953053153253353453553653753853954054151 unmodified lines59359459559659759859960060160260323 unmodified lines627628629630631632633102 unmodified lines73673773873974074174274310 unmodified lines7547557567577587597602 unmodified lines76376476576676776876977077177277342 unmodified lines81681781881982082182229 unmodified lines8528538548558568578588598608618628638648658668678688698708718728737 unmodified lines8818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159161 unmodified line9189199209219229239249259269279289291 unmodified line9319329339349359369379389399409419429439449451 unmodified line9479489499509519529539549559569579581 unmodified line9609619629639649656 unmodified lines9729739749759769779781 unmodified line98098198298398498598610 unmodified lines997998999100010011002100310045 unmodified lines10101011101210131014101510161017101810192 unmodified lines102210231024102510261027102858 unmodified lines1087108810891090109110921093109428 unmodified lines112311241125112611271128112943 unmodified lines1173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123449 unmodified lines128412851286128712881289129012911292129312941295129612971298129913001301130213031304185 unmodified lines149014911492149314941495149614971498149915001501import spacesimport osfrom argparse import ArgumentParserfrom stablepy import (Model_Diffusers,SCHEDULE_TYPE_OPTIONS,34 unmodified linesDIFFUSERS_CONTROLNET_MODEL,IP_MODELS,MODE_IP_OPTIONS,CACHE_HF_ROOT,)from stablepy.diffusers_vanilla.style_prompt_config import STYLE_NAMESimport torch14 unmodified linesprogress_step_bar,html_template_message,escape_html,clear_hf_cache,)from image_processor import preprocessor_tabfrom datetime import datetime6 unmodified lines# import urllib.parseimport subprocessIS_ZERO_GPU = bool(os.getenv("SPACES_ZERO_GPU"))if IS_ZERO_GPU:subprocess.run("rm -rf /data-nvme/zerogpu-offload/*", env={}, shell=True)IS_GPU_MODE = True if IS_ZERO_GPU else (True if torch.cuda.is_available() else False)img_path = "./images/"allowed_path = os.path.abspath(img_path)delete_cache_time = (9600, 9600) if IS_ZERO_GPU else (86400, 86400)ImageFile.LOAD_TRUNCATED_IMAGES = Truetorch.backends.cuda.matmul.allow_tf32 = True# os.environ["PYTORCH_NO_CUDA_MEMORY_CACHING"] = "1"directories = [DIRECTORY_MODELS, DIRECTORY_LORAS, DIRECTORY_VAES, DIRECTORY_EMBEDS, DIRECTORY_UPSCALERS]for directory in directories:1 unmodified line# Download stuffsfor url in [url.strip() for url in DOWNLOAD_MODEL.split(',')]:download_things(DIRECTORY_MODELS, url, HF_TOKEN, CIVITAI_API_KEY)for url in [url.strip() for url in DOWNLOAD_VAE.split(',')]:download_things(DIRECTORY_VAES, url, HF_TOKEN, CIVITAI_API_KEY)for url in [url.strip() for url in DOWNLOAD_LORA.split(',')]:download_things(DIRECTORY_LORAS, url, HF_TOKEN, CIVITAI_API_KEY)# Download Embeddingsfor url_embed in DOWNLOAD_EMBEDS:download_things(DIRECTORY_EMBEDS, url_embed, HF_TOKEN, CIVITAI_API_KEY)# Build list modelsembed_list = get_model_list(DIRECTORY_EMBEDS)11 unmodified linesprint('\033[33m🏁 Download and listing of valid models completed.\033[0m')components = Noneif IS_ZERO_GPU: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)######################## GUI3 unmodified lineswarnings.filterwarnings(action="ignore", category=FutureWarning, module="diffusers")warnings.filterwarnings(action="ignore", category=UserWarning, module="diffusers")warnings.filterwarnings(action="ignore", category=FutureWarning, module="transformers")parser = ArgumentParser(description='DiffuseCraft: Create images from text prompts.', add_help=True)parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing")parser.add_argument('--theme', type=str, default="NoCrypt/miku", help='Set the theme (default: NoCrypt/miku)')parser.add_argument("--ssr", action="store_true", help="Enable SSR (Server-Side Rendering)")parser.add_argument("--log-level", type=str, default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], help="Set logging level (default: INFO)")args = parser.parse_args()logger.setLevel("INFO" if IS_ZERO_GPU else getattr(logging, args.log_level.upper()))CSS = """.contain { display: flex; flex-direction: column; }3 unmodified lines"""def lora_chk(lora_):if isinstance(lora_, str) and lora_.strip() not in ["", "None"]:return lora_return Noneclass GuiSD:def __init__(self, stream=True):self.model = None9 unmodified linesremoval_candidate = self.inventory.pop(0)delete_model(removal_candidate)# Cleanup after 60 seconds of inactivitylowPrioCleanup = max((datetime.now() - self.last_load).total_seconds(), 0) > 60if lowPrioCleanup and not self.status_loading and get_used_storage_gb(CACHE_HF_ROOT) > (storage_floor_gb * 2):print("Cleaning up Hugging Face cache...")clear_hf_cache()self.inventory = [m for m in self.inventory if os.path.exists(m)]def update_inventory(self, model_name):if model_name not in single_file_model_list:self.inventory = [4 unmodified linesdef load_new_model(self, model_name, vae_model, task, controlnet_model, progress=gr.Progress(track_tqdm=True)):# download link model > model_nameif model_name.startswith("http"):yield f"Downloading model: {model_name}"model_name = download_things(DIRECTORY_MODELS, model_name, HF_TOKEN, CIVITAI_API_KEY)if not model_name:raise ValueError("Error retrieving model information from URL")if IS_ZERO_GPU:self.update_storage_models()vae_model = vae_model if vae_model != "None" else Nonemodel_type = get_model_type(model_name)dtype_model = torch.bfloat16 if model_type == "FLUX" else torch.float16if not os.path.exists(model_name):logger.debug(f"model_name={model_name}, vae_model={vae_model}, task={task}, controlnet_model={controlnet_model}")_ = download_diffuser_repo(repo_name=model_name,model_type=model_type,38 unmodified linestype_model_precision=dtype_model,retain_task_model_in_cache=False,controlnet_model=controlnet_model,device="cpu" if IS_ZERO_GPU else None,env_components=components,)self.model.advanced_params(image_preprocessor_cuda_active=IS_GPU_MODE)else:if self.model.base_model_id != model_name:load_now_time = datetime.now()3 unmodified linesprint("Waiting for the previous model's time ops...")time.sleep(9 - elapsed_time)if IS_ZERO_GPU:self.model.device = torch.device("cpu")self.model.load_pipe(model_name,task_name=TASK_STABLEPY[task],147 unmodified linesvae_msg = f"VAE: {vae_model}" if vae_model else ""msg_lora = ""logger.debug(f"Config model: {model_name}, {vae_model}, {loras_list}")task = TASK_STABLEPY[task]91 unmodified lines"distance_threshold": distance_threshold,"recolor_gamma_correction": float(recolor_gamma_correction),"tile_blur_sigma": int(tile_blur_sigma),"lora_A": lora_chk(lora1),"lora_scale_A": lora_scale1,"lora_B": lora_chk(lora2),"lora_scale_B": lora_scale2,"lora_C": lora_chk(lora3),"lora_scale_C": lora_scale3,"lora_D": lora_chk(lora4),"lora_scale_D": lora_scale4,"lora_E": lora_chk(lora5),"lora_scale_E": lora_scale5,"lora_F": lora_chk(lora6),"lora_scale_F": lora_scale6,"lora_G": lora_chk(lora7),"lora_scale_G": lora_scale7,"textual_inversion": embed_list if textual_inversion else [],"syntax_weights": syntax_weights, # "Classic"51 unmodified lines# kwargs for diffusers pipelineif guidance_rescale:pipe_params["guidance_rescale"] = guidance_rescaleif IS_ZERO_GPU: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)logger.debug("transformer to cuda")actual_progress = 0info_images = gr.update()23 unmodified linesdownload_links = "<br>".join([f'<a href="{path.replace("/images/", f"/gradio_api/file={allowed_path}/")}" download="{os.path.basename(path)}">Download Image {i + 1}</a>'for i, path in enumerate(image_path)])102 unmodified lines@spaces.GPU(duration=15)def process_upscale(image, upscaler_name, upscaler_size):if image is None:return Nonefrom stablepy.diffusers_vanilla.utils import save_pil_image_with_metadatafrom stablepy import load_upscaler_model10 unmodified linesname_upscaler = f"./{DIRECTORY_UPSCALERS}/{name_upscaler.split('/')[-1]}"scaler_beta = load_upscaler_model(model=name_upscaler, tile=(0 if IS_ZERO_GPU else 192), tile_overlap=8, device=("cuda" if IS_GPU_MODE else "cpu"), half=IS_GPU_MODE)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)2 unmodified lines# https://huggingface.co/spaces/BestWishYsh/ConsisID-preview-Space/discussions/1#674969a022b99c122af5d407# dynamic_gpu_duration.zerogpu = True# sd_gen_generate_pipeline.zerogpu = Truesd_gen = GuiSD()with gr.Blocks(theme=args.theme, css=CSS, fill_width=True, fill_height=False, delete_cache=delete_cache_time) as app:gr.Markdown("# 🧩 DiffuseCraft")gr.Markdown(SUBTITLE_GUI)with gr.Tab("Generation"):42 unmodified linesactual_task_info = gr.HTML()with gr.Row(equal_height=False, variant="default", visible=IS_ZERO_GPU):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")29 unmodified lines"Schedule type": gr.update(value="Automatic"),"PAG": gr.update(value=.0),"FreeU": gr.update(value=False),"Hires upscaler": gr.update(),"Hires upscale": gr.update(),"Hires steps": gr.update(),"Hires denoising strength": gr.update(),"Hires CFG": gr.update(),"Hires sampler": gr.update(),"Hires schedule type": gr.update(),"Image resolution": gr.update(value=1024),"Strength": gr.update(),}# Generate up to 7 LoRAsfor i in range(1, 8):valid_receptors[f"Lora_{i}"] = gr.update()valid_receptors[f"Lora_scale_{i}"] = gr.update()valid_keys = list(valid_receptors.keys())parameters = extract_parameters(base_prompt)7 unmodified linesparameters["Sampler"] = value_samplerparameters["Schedule type"] = s_typeparams_lora = []if ">" in parameters["prompt"] and "<" in parameters["prompt"]:params_lora = re.findall(r'<lora:[^>]+>', parameters["prompt"])if "Loras" in parameters:params_lora += re.findall(r'<lora:[^>]+>', parameters["Loras"])if params_lora:parsed_params = []for tag_l in params_lora:try:inner = tag_l.strip("<>") # remove < >_, data_l = inner.split(":", 1) # remove the "lora:" partparts_l = data_l.split(":")name_l = parts_l[0]weight_l = float(parts_l[1]) if len(parts_l) > 1 else 1.0 # default weight = 1.0parsed_params.append((name_l, weight_l))except Exception as e:print(f"Error parsing LoRA tag {tag_l}: {e}")num_lora = 1for parsed_l, parsed_s in parsed_params:filtered_loras = [m for m in lora_model_list if parsed_l in m]if filtered_loras:parameters[f"Lora_{num_lora}"] = filtered_loras[0]parameters[f"Lora_scale_{num_lora}"] = parsed_snum_lora += 1# continue = discard new valuefor key, val in parameters.items():# print(val)if key in valid_keys:1 unmodified lineif key == "Sampler":if val not in scheduler_names:continueif key in ["Schedule type", "Hires schedule type"]:if val not in SCHEDULE_TYPE_OPTIONS:continueif key == "Hires sampler":if val not in POST_PROCESSING_SAMPLER:continueelif key == "Clip skip":if "," in str(val):val = val.replace(",", "")1 unmodified lineval = Trueif key == "prompt":if ">" in val and "<" in val:val = re.sub(r'<[^>]+>', '', val) # Delete html and lorasprint("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", "Hires steps", "Image resolution"]:val = int(val)if key == "FreeU":val = Trueif key in ["CFG scale", "PAG", "Hires upscale", "Hires denoising strength", "Hires CFG", "Strength"]:val = float(val)if key == "Model":filtered_models = [m for m in model_list if val in m]1 unmodified lineval = filtered_models[0]else:val = name_modelif key == "Hires upscaler":if val not in UPSCALER_KEYS:continueif key == "Seed":continuevalid_receptors[key] = gr.update(value=val)# print(val, type(val))# print(valid_receptors)1 unmodified lineprint(str(e))return [value for value in valid_receptors.values()]def run_clear_prompt_gui():return gr.update(value=""), gr.update(value="")clear_prompt_gui.click(6 unmodified linesrun_set_random_seed, [], seed_gui)num_images_gui = gr.Slider(minimum=1, maximum=(5 if IS_ZERO_GPU else 20), 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])1 unmodified lineupscaler_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 if IS_ZERO_GPU else 192), 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")10 unmodified linesreturn gr.Dropdown(label=label, choices=lora_model_list, value="None", allow_custom_value=True, visible=visible)def lora_scale_slider(label, visible=True):val_lora = 2 if IS_ZERO_GPU else 8return gr.Slider(minimum=-val_lora, maximum=val_lora, 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")5 unmodified lineslora_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=(not IS_ZERO_GPU))lora_scale_6_gui = lora_scale_slider("Lora Scale 6", visible=(not IS_ZERO_GPU))lora7_gui = lora_dropdown("Lora7", visible=(not IS_ZERO_GPU))lora_scale_7_gui = lora_scale_slider("Lora Scale 7", visible=(not IS_ZERO_GPU))with gr.Accordion("From URL", open=False, visible=True):text_lora = gr.Textbox(2 unmodified lineslines=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=(not IS_ZERO_GPU))button_lora = gr.Button("Get and Refresh the LoRA Lists")new_lora_status = gr.HTML()button_lora.click(58 unmodified linespreprocess_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=0.0, maximum=2.0, step=0.01, value=0.1, label="'MLSD' Hough value threshold")distance_threshold_gui = gr.Slider(minimum=0.0, 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")28 unmodified linesgr.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")43 unmodified lineshires_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.Column(visible=(not IS_ZERO_GPU)):image_storage_location_gui = gr.Textbox(value=img_path, label="Image Storage Location")disable_progress_bar_gui = gr.Checkbox(value=False, label="Disable Progress Bar")leave_progress_bar_gui = gr.Checkbox(value=True, label="Leave Progress Bar")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")display_images_gui = gr.Checkbox(value=False, label="Display Images")image_previews_gui = gr.Checkbox(value=True, label="Image Previews")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")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,upscaler_model_path_gui,upscaler_increases_size_gui,hires_steps_gui,hires_denoising_strength_gui,hires_guidance_scale_gui,hires_sampler_gui,hires_schedule_type_gui,image_resolution_gui,strength_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,],)with gr.Accordion("Examples and help", open=False, visible=True):gr.Markdown(HELP_GUI)gr.Markdown(EXAMPLES_GUI_HELP)49 unmodified lines# "hsl(360, 120, 120)" # in fact any valid colorstring]),eraser=gr.Eraser(default_size="16"),render=True,visible=False,interactive=False,)show_canvas = gr.Button("SHOW INPAINT CANVAS")def change_visibility_canvas():return gr.update(visible=True, interactive=True), gr.update(visible=False)show_canvas.click(change_visibility_canvas, [], [image_base, show_canvas])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)185 unmodified linesshow_progress="minimal",)if __name__ == "__main__":app.queue()app.launch(show_error=True,share=args.share_enabled,debug=True,ssr_mode=args.ssr,allowed_paths=[allowed_path],)
8 unmodified lines910111213148 unmodified lines2324252627282930313233342 unmodified lines37383940414243444546474849505152535455565758594 unmodified lines6465666768694 unmodified lines747576777879808182838485868788899091929 unmodified lines1021031041051061071081091 unmodified line1111121131141151161171181191201211221233 unmodified lines12712812913013113213313413513613713813919 unmodified lines15916016116216316416516616715 unmodified lines18318418518618718818919035 unmodified lines226227228229230231127 unmodified lines359360361362363364365366367117 unmodified lines48548648748848949049188 unmodified lines5805815825835845858 unmodified linesIP_ADAPTERS_SDXL,)# - **Download Models**DOWNLOAD_MODEL = "https://huggingface.co/TechnoByte/MilkyWonderland/resolve/main/milkyWonderland_v40.safetensors"8 unmodified lines'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',2 unmodified lines# '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',4 unmodified lines'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',4 unmodified lines'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',9 unmodified lines'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',1 unmodified line'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',3 unmodified lines'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',19 unmodified lines'GraydientPlatformAPI/realcartoon3d-17','GraydientPlatformAPI/realcartoon-pixar11','GraydientPlatformAPI/realcartoon-real17','nitrosocke/Ghibli-Diffusion',]DIFFUSERS_FORMAT_LORAS = ["nerijs/animation2k-flux","XLabs-AI/flux-RealismLora",15 unmodified linesDIRECTORY_EMBEDS = 'embedings'DIRECTORY_UPSCALERS = 'upscalers'CACHE_HF = "/home/user/.cache/huggingface/hub/"STORAGE_ROOT = "/home/user/"TASK_STABLEPY = {'txt2img': 'txt2img',35 unmodified lines# "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",127 unmodified lines" 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."""117 unmodified lines20,4.0,-1,"loras/Coloring_book_-_LineArt.safetensors",1.0,"DPM++ 2M SDE",1024,88 unmodified linesRESOURCES = ("""### 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).""")8 unmodified lines9101112131415168 unmodified lines2526272829303132333435362 unmodified lines394041424344454647484950515253545556574 unmodified lines626364656667684 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051069 unmodified lines1161171181191201211221231241251 unmodified line1271281291301311321331341351361371381391403 unmodified lines14414514614714814915015115215315415515615715819 unmodified lines17817918018118218318418518615 unmodified lines20220320420520620720820921021121235 unmodified lines248249250251252253254127 unmodified lines382383384385386387388389390391392117 unmodified lines51051151251351451551688 unmodified lines6056066076086096106118 unmodified linesIP_ADAPTERS_SDXL,)IS_ZERO_GPU = bool(os.getenv("SPACES_ZERO_GPU"))# - **Download Models**DOWNLOAD_MODEL = "https://huggingface.co/TechnoByte/MilkyWonderland/resolve/main/milkyWonderland_v40.safetensors"8 unmodified lines'Laxhar/noobai-XL-1.1','Laxhar/noobai-XL-Vpred-1.0','black-forest-labs/FLUX.1-dev','black-forest-labs/FLUX.1-Krea-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','Freepik/flux.1-lite-8B-alpha','shauray/FluxDev-HyperSD-merged','mikeyandfriends/PixelWave_FLUX.1-dev_03',2 unmodified lines# 'ostris/OpenFLUX.1','shuttleai/shuttle-3-diffusion','Laxhar/noobai-XL-1.0','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/ripplemix-noob-vpred10-illustrious01-v14-sdxl','John6666/sigmaih-15-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-v22-sdxl','John6666/haruki-mix-illustrious-v10-sdxl','John6666/noobreal-v10-sdxl','John6666/complicated-noobai-merge-vprediction-sdxl',4 unmodified lines'Laxhar/noobai-XL-Vpred-0.65','Laxhar/noobai-XL-Vpred-0.6','John6666/cat-tower-noobai-xl-checkpoint-v14vpred-sdxl','John6666/cat-tower-noobai-xl-checkpoint-v15vpred-sdxl','John6666/noobai-xl-nai-xl-vpred05version-sdxl','John6666/noobai-fusion2-vpred-itercomp-v1-sdxl','John6666/noobai-xl-nai-xl-vpredtestversion-sdxl',4 unmodified lines'John6666/obsession-illustriousxl-v21-sdxl','John6666/obsession-illustriousxl-v30-sdxl','John6666/obsession-illustriousxl-v31-sdxl','John6666/one-obsession-13-sdxl','John6666/one-obsession-14-24d-sdxl','John6666/one-obsession-15-noobai-sdxl','John6666/one-obsession-v16-noobai-sdxl','John6666/prefect-illustrious-xl-v3-sdxl','John6666/wai-nsfw-illustrious-v70-sdxl','John6666/wai-nsfw-illustrious-sdxl-v140-sdxl','John6666/illustrious-pony-mix-v3-sdxl','John6666/nova-anime-xl-il-v90-sdxl','John6666/nova-anime-xl-il-v110-sdxl','John6666/nova-orange-xl-re-v10-sdxl','John6666/nova-orange-xl-v110-sdxl','John6666/nova-orange-xl-re-v20-sdxl','John6666/nova-unreal-xl-v60-sdxl','John6666/nova-unreal-xl-v70-sdxl','John6666/nova-unreal-xl-v80-sdxl','John6666/nova-cartoon-xl-v40-sdxl','John6666/silvermoon-mix03-illustrious-v10-sdxl','eienmojiki/Anything-XL','eienmojiki/Starry-XL-v5.2','votepurchase/plantMilkModelSuite_walnut','John6666/meinaxl-v2-sdxl','Eugeoter/artiwaifu-diffusion-2.0','comin/IterComp','John6666/epicrealism-xl-v8kiss-sdxl','John6666/epicrealism-xl-v10kiss2-sdxl','John6666/epicrealism-xl-vxiabeast-sdxl','John6666/epicrealism-xl-vxvii-crystal-clear-realism-sdxl','misri/zavychromaxl_v80','SG161222/RealVisXL_V4.0','SG161222/RealVisXL_V5.0',9 unmodified lines'John6666/ebara-mfcg-pony-mix-v12-sdxl','John6666/t-ponynai3-v51-sdxl','John6666/t-ponynai3-v65-sdxl','John6666/t-ponynai3-v7-sdxl','John6666/prefect-pony-xl-v3-sdxl','John6666/prefect-pony-xl-v4-sdxl','John6666/prefect-pony-xl-v50-sdxl','John6666/mala-anime-mix-nsfw-pony-xl-v5-sdxl','John6666/wai-ani-nsfw-ponyxl-v10-sdxl','John6666/wai-real-mix-v11-sdxl',1 unmodified line'John6666/wai-c-v6-sdxl','John6666/iniverse-mix-xl-sfwnsfw-pony-guofeng-v43-sdxl','John6666/sifw-annihilation-xl-v2-sdxl','John6666/sifw-annihilation-xl-v305illustrious-beta-sdxl','John6666/photo-realistic-pony-v5-sdxl','John6666/pony-realism-v21main-sdxl','John6666/pony-realism-v22main-sdxl','John6666/pony-realism-v23-ultra-sdxl','John6666/cyberrealistic-pony-v65-sdxl','John6666/cyberrealistic-pony-v7-sdxl','John6666/cyberrealistic-pony-v127-alternative-sdxl','GraydientPlatformAPI/realcartoon-pony-diffusion','John6666/nova-anime-xl-pony-v5-sdxl','John6666/autismmix-sdxl-autismmix-pony-sdxl',3 unmodified lines'John6666/duchaiten-pony-real-v11fix-sdxl','John6666/duchaiten-pony-real-v20-sdxl','John6666/duchaiten-pony-xl-no-score-v70-sdxl','KBlueLeaf/Kohaku-XL-Zeta','cagliostrolab/animagine-xl-3.1','cagliostrolab/animagine-xl-4.0','yodayo-ai/kivotos-xl-2.0','yodayo-ai/holodayo-xl-2.1','yodayo-ai/clandestine-xl-1.0','https://huggingface.co/chemwolf/Karmix-XL-v0/resolve/main/Karmix-XL-v0.safetensors?download=true','https://civitai.com/api/download/models/128713?type=Model&format=SafeTensor&size=pruned&fp=fp16','https://civitai.com/models/30240?modelVersionId=125771','digiplay/majicMIX_sombre_v2','digiplay/majicMIX_realistic_v6','digiplay/majicMIX_realistic_v7',19 unmodified lines'GraydientPlatformAPI/realcartoon3d-17','GraydientPlatformAPI/realcartoon-pixar11','GraydientPlatformAPI/realcartoon-real17',]DIFFUSERS_FORMAT_LORAS = ["nerijs/animation2k-flux","XLabs-AI/flux-RealismLora",15 unmodified linesDIRECTORY_EMBEDS = 'embedings'DIRECTORY_UPSCALERS = 'upscalers'STORAGE_ROOT = "/home/user/"CACHE_HF_ROOT = os.path.expanduser("~/.cache/huggingface")CACHE_HF = os.path.join(CACHE_HF_ROOT, "hub")if IS_ZERO_GPU:os.environ["HF_HOME"] = CACHE_HFTASK_STABLEPY = {'txt2img': 'txt2img',35 unmodified lines# "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","Real-ESRGAN-Anime-finetuning": "https://huggingface.co/danhtran2mind/Real-ESRGAN-Anime-finetuning/resolve/main/Real-ESRGAN-Anime-finetuning.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",127 unmodified lines" to perform different tasks in image generation.")msg_zero = "" if not IS_ZERO_GPU else "- 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'."HELP_GUI = (f"""### Help:{msg_zero}- 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."""117 unmodified lines20,4.0,-1,("loras/Coloring_book_-_LineArt.safetensors" if os.path.exists("loras/Coloring_book_-_LineArt.safetensors") else "None"),1.0,"DPM++ 2M SDE",1024,88 unmodified linesRESOURCES = ("""### Resources- John6666's space has some great features you might find helpful [link](https://huggingface.co/spaces/John6666/DiffuseCraftMod).- Try the image generator in Colab’s free tier, which provides free GPU [link](https://github.com/R3gm/SD_diffusers_interactive).- `DiffuseCraft` in Colab:[link](https://github.com/R3gm/DiffuseCraft?tab=readme-ov-file#diffusecraft).""")
91 unmodified lines929394959697989991 unmodified linespre_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")91 unmodified lines929394959697989991 unmodified linespre_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=0., maximum=2.0, step=0.01, value=0.1, label="'MLSD' Hough value threshold")pre_distance_threshold = gr.Slider(minimum=0., 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")
123git-lfsaria2 -yffmpeg123git-lfsaria2ffmpeg
1pip>=23.0.01234567stablepy==0.6.2torch==2.2.0gdownopencv-pythonunidecodepydantic==2.10.6huggingface_hub==0.29.312345678910111213stablepy==0.6.2torch==2.5.1diffusersgdownopencv-pythonunidecodepydantic==2.10.6huggingface_hubhf_transferhf_xetspacesgradio==5.44.1matplotlib-inline
8 unmodified lines9101112131413 unmodified lines28293031323332 unmodified lines666768697071723 unmodified lines76777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219322 unmodified lines21621721821922022122222322422522622722822976 unmodified lines306307308309310311312120 unmodified lines43343443543643743843944044113 unmodified lines4554564574584594608 unmodified linesDIRECTORY_LORAS,DIRECTORY_MODELS,DIFFUSECRAFT_CHECKPOINT_NAME,CACHE_HF,STORAGE_ROOT,)13 unmodified linesimport shutilimport subprocessUSER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'32 unmodified lines)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)3 unmodified linesself.original_json = copy.deepcopy(json_data)def retrieve_model_info(url):json_data = request_json_data(url)if not json_data:return Nonemodel_descriptor = ModelInformation(json_data)return model_descriptordef download_things(directory, url, hf_token="", civitai_api_key="", romanize=False):url = url.strip()downloaded_file_path = Noneif "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 encodingif "/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 Noneand model_profile.download_urland model_profile.filename_url):url = model_profile.download_urlfilename = unidecode(model_profile.filename_url) if romanize else model_profile.filename_urlelse: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}")22 unmodified linesif "Steps:" in input_string:input_string = input_string.replace("Steps:", "Negative prompt: Steps:")else:print("Invalid metadata")parameters["prompt"] = input_stringreturn parametersparm = 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 parametersparm = parm[1].split("Steps:")76 unmodified linesmodel = api.model_info(repo_id=repo_id, timeout=5.0)tags = model.tagsfor tag in tags:if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)except Exception:return default120 unmodified linesreturn total_size_gbdef 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 = 99913 unmodified linesshutil.rmtree(diffusers_model)def progress_step_bar(step, total):# Calculate the percentage for the progress bar widthpercentage = min(100, ((step / total) * 100))8 unmodified lines910111213141513 unmodified lines2930313233343532 unmodified lines68697071727374753 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225322 unmodified lines27627727827928028128228328428528628728828929076 unmodified lines367368369370371372373374120 unmodified lines49549649749849950050150250313 unmodified lines5175185195205215225235245255265275285295305315325335345355365378 unmodified linesDIRECTORY_LORAS,DIRECTORY_MODELS,DIFFUSECRAFT_CHECKPOINT_NAME,CACHE_HF_ROOT,CACHE_HF,STORAGE_ROOT,)13 unmodified linesimport shutilimport subprocessIS_ZERO_GPU = bool(os.getenv("SPACES_ZERO_GPU"))USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'32 unmodified lines)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)3 unmodified linesself.original_json = copy.deepcopy(json_data)def get_civit_params(url):try:json_data = request_json_data(url)mdc = ModelInformation(json_data)if mdc.download_url and mdc.filename_url:return mdc.download_url, mdc.filename_url, mdc.model_urlelse:ValueError("Invalid Civitai model URL")except Exception as e:print(f"Error retrieving Civitai metadata: {e} — fallback to direct download")return url, None, Nonedef civ_redirect_down(url, dir_, civitai_api_key, romanize, alternative_name):filename_base = filename = Noneif alternative_name:output_path = os.path.join(dir_, alternative_name)if os.path.exists(output_path):return output_path, alternative_name# Follow the redirect to get the actual download URLcurl_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" URLlocation_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 filenamedecoded_filename = urllib.parse.unquote(encoded_filename)filename = unidecode(decoded_filename) if romanize else decoded_filename# print(f"Filename redirect: {filename}")filename_base = alternative_name if alternative_name else filenameif not filename_base:return None, Noneelif os.path.exists(os.path.join(dir_, filename_base)):return os.path.join(dir_, filename_base), filename_basearia2_command = (f'aria2c --console-log-level=error --summary-interval=10 -c -x 16 'f'-k 1M -s 16 -d "{dir_}" -o "{filename_base}" "{redirect_url}"')r_code = os.system(aria2_command) # noqa# if r_code != 0:# raise RuntimeError(f"Failed to download file: {filename_base}. Error code: {r_code}")output_path = os.path.join(dir_, filename_base)if not os.path.exists(output_path):return None, filename_basereturn output_path, filename_basedef civ_api_down(url, dir_, civitai_api_key, civ_filename):"""This method is susceptible to being blocked because it generates a lot of temp redirect links with aria2c.If an API key limit is reached, generating a new API key and using it can fix the issue."""output_path = Noneurl_dl = url + f"?token={civitai_api_key}"if not civ_filename:aria2_command = f'aria2c -c -x 1 -s 1 -d "{dir_}" "{url_dl}"'os.system(aria2_command)else:output_path = os.path.join(dir_, civ_filename)if not os.path.exists(output_path):aria2_command = (f'aria2c --console-log-level=error --summary-interval=10 -c -x 16 'f'-k 1M -s 16 -d "{dir_}" -o "{civ_filename}" "{url_dl}"')os.system(aria2_command)return output_pathdef drive_down(url, dir_):import gdownoutput_path = Nonedrive_id, _ = gdown.parse_url.parse_url(url, warning=False)dir_files = os.listdir(dir_)for dfile in dir_files:if drive_id in dfile:output_path = os.path.join(dir_, dfile)breakif not output_path:original_path = gdown.download(url, f"{dir_}/", fuzzy=True)dir_name, base_name = os.path.split(original_path)name, ext = base_name.rsplit(".", 1)new_name = f"{name}_{drive_id}.{ext}"output_path = os.path.join(dir_name, new_name)os.rename(original_path, output_path)return output_pathdef hf_down(url, dir_, hf_token, romanize):url = url.replace("?download=true", "")# url = urllib.parse.quote(url, safe=':/') # fix encodingfilename = unidecode(url.split('/')[-1]) if romanize else url.split('/')[-1]output_path = os.path.join(dir_, filename)if os.path.exists(output_path):return output_pathif "/blob/" in url:url = url.replace("/blob/", "/resolve/")if hf_token:user_header = f'"Authorization: Bearer {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 {dir_} -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 {dir_} -o {filename}")return output_pathdef download_things(directory, url, hf_token="", civitai_api_key="", romanize=False):url = url.strip()downloaded_file_path = Noneif "drive.google.com" in url:downloaded_file_path = drive_down(url, directory)elif "huggingface.co" in url:downloaded_file_path = hf_down(url, directory, hf_token, romanize)elif "civitai.com" in url:if not civitai_api_key:msg = "You need an API key to download Civitai models."print(f"\033[91m{msg}\033[0m")gr.Warning(msg)return Noneurl, civ_filename, civ_page = get_civit_params(url)if civ_page and not IS_ZERO_GPU:print(f"\033[92mCivitai model: {civ_filename} [page: {civ_page}]\033[0m")downloaded_file_path, civ_filename = civ_redirect_down(url, directory, civitai_api_key, romanize, civ_filename)if not downloaded_file_path:msg = ("Download failed.\n""If this is due to an API limit, generating a new API key may resolve the issue.\n""Attempting to download using the old method...")print(msg)gr.Warning(msg)downloaded_file_path = civ_api_down(url, directory, civitai_api_key, civ_filename)else:os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")22 unmodified linesif "Steps:" in input_string:input_string = input_string.replace("Steps:", "Negative prompt: Steps:")else:msg = "Generation data is invalid."gr.Warning(msg)print(msg)parameters["prompt"] = input_stringreturn parametersparm = input_string.split("Negative prompt:")parameters["prompt"] = parm[0].strip()if "Steps:" not in parm[1]:parameters["neg_prompt"] = parm[1].strip()return parametersparm = parm[1].split("Steps:")76 unmodified linesmodel = api.model_info(repo_id=repo_id, timeout=5.0)tags = model.tagsfor tag in tags:if tag in MODEL_TYPE_CLASS.keys():return MODEL_TYPE_CLASS.get(tag, default)except Exception:return default120 unmodified linesreturn total_size_gbdef get_used_storage_gb(path_storage=STORAGE_ROOT):try:used_gb = get_folder_size_gb(path_storage)print(f"Used Storage: {used_gb:.2f} GB")except Exception as e:used_gb = 99913 unmodified linesshutil.rmtree(diffusers_model)def clear_hf_cache():"""Clears the entire Hugging Face cache at ~/.cache/huggingface.Hugging Face will re-download models as needed later."""try:if os.path.exists(CACHE_HF_ROOT):shutil.rmtree(CACHE_HF_ROOT, ignore_errors=True)print(f"Hugging Face cache cleared: {CACHE_HF_ROOT}")else:print(f"No Hugging Face cache found at: {CACHE_HF_ROOT}")except Exception as e:print(f"Error clearing Hugging Face cache: {e}")def progress_step_bar(step, total):# Calculate the percentage for the progress bar widthpercentage = min(100, ((step / total) * 100))
.gitignoreAdded+207
README.md+1-1
app.py+219-90
constants.py+49-23
image_processor.py+2-2
packages.txt+1-1
pre-requirements.txtAdded+1
requirements.txt+8-2
utils.py+181-104