Spaces:
Running on Zero
Running on Zero
Update constants.py
#13
by aayanmishra-ml - opened
Files changed (9)
- .gitignoreDeleted-207
- README.md+1-2
- app.py+217-443
- constants.py+34-89
- image_processor.py+2-2
- packages.txt+1
- pre-requirements.txtDeleted-1
- requirements.txt+3-12
- utils.py+485-779
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 lines45678910113 unmodified linescolorFrom: redcolorTo: pinksdk: gradiosdk_version: 6.10.0python_version: '3.12'app_file: app.pypinned: truelicense: mit3 unmodified lines456789103 unmodified linescolorFrom: redcolorTo: pinksdk: gradiosdk_version: 4.31.3app_file: app.pypinned: truelicense: mit
1234561 unmodified line89101112131427 unmodified lines42434445464748495051525354559 unmodified lines656667686970713 unmodified lines757677787980818283848586878889909192939495961 unmodified line989910010110210310410510610710810911011111211 unmodified lines1241251261271281291301311321331341351361371381393 unmodified lines1431441451461471481491501511521531541551561571581593 unmodified lines1631641651661671681691701711721731742 unmodified lines1771781791801811821831841851861871881891901911921931941951961971981992002012022032042052063 unmodified lines2102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842858 unmodified lines29429529629729829930015 unmodified lines3163173183193203213223233243253 unmodified lines32933033133233333433533614 unmodified lines35135235335435535635775 unmodified lines43343443543643743843941 unmodified lines48148248348448548648748848949091 unmodified lines5825835845855865875885895905915925935945955965975985996006016026036046056066078 unmodified lines61661761861962062162229 unmodified lines65265365465565665765865966066166212 unmodified lines6756766776786796806816826832 unmodified lines68668768868969069169269369469569669769869970070170270370470570670770870971071171257 unmodified lines77077177277377477577623 unmodified lines80080180280380480580680710 unmodified lines8188198208218228238242 unmodified lines8278288298308318328338348358368379 unmodified lines84784884985085185285385485585685785885986011 unmodified lines87287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410 unmodified lines108510861087108810891090109110925 unmodified lines10981099110011011102110311041105110611072 unmodified lines111011111112111311141115111658 unmodified lines1175117611771178117911801181118216 unmodified lines11991200120112021203120412055 unmodified lines121112121213121412151216121739 unmodified lines1257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132450 unmodified lines13751376137713781379138013811382138313841385138613871388138913901391139213931394139512 unmodified lines140814091410141114121413141436 unmodified lines145114521453145414551456145773 unmodified lines153115321533153415351536153742 unmodified lines158015811582158315841585158615871588158915901591159215931594159515961597import spacesimport osfrom argparse import ArgumentParserfrom stablepy import (Model_Diffusers,SCHEDULE_TYPE_OPTIONS,1 unmodified linecheck_scheduler_compatibility,TASK_AND_PREPROCESSORS,FACE_RESTORATION_MODELS,PROMPT_WEIGHT_OPTIONS_PRIORITY,scheduler_names,)from constants import (27 unmodified linesDIFFUSERS_CONTROLNET_MODEL,IP_MODELS,MODE_IP_OPTIONS,CACHE_HF_ROOT,CACHE_HF,)from stablepy.diffusers_vanilla.style_prompt_config import STYLE_NAMESimport torchimport reimport timeimport threadingfrom PIL import ImageFilefrom utils import (download_things,9 unmodified linesprogress_step_bar,html_template_message,escape_html,clear_hf_cache,)from image_processor import preprocessor_tabfrom datetime import datetime3 unmodified linesimport warningsfrom stablepy import loggerfrom diffusers import FluxPipelineimport urllib.parseimport subprocessos.system("pip list")IS_ZERO_GPU = bool(os.getenv("SPACES_ZERO_GPU"))HIDE_API = bool(os.getenv("HIDE_API"))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 = None2 unmodified linesself.last_load = datetime.now()self.inventory = []# Avoid duplicate downloadsself.active_downloads = set()self.download_lock = threading.Lock()# Anti-abuse: Track new model requestsself.used_models = []self.new_model_history = []def update_storage_models(self, storage_floor_gb=30, required_inventory_for_purge=3):while get_used_storage_gb() > storage_floor_gb:if len(self.inventory) < required_inventory_for_purge:breakremoval_candidate = self.inventory.pop(0)delete_model(removal_candidate)# Cleanup after 60 seconds of inactivitylowPrioCleanup = max((datetime.now() - self.last_load).total_seconds(), 0) > 120if lowPrioCleanup and (len(self.inventory) >= required_inventory_for_purge - 1) 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 = [3 unmodified linesdef load_new_model(self, model_name, vae_model, task, controlnet_model, progress=gr.Progress(track_tqdm=True)):if model_name != model_list[0]:# --- Anti-Abuse Check Start ---if model_name in self.used_models:# Move to the end to mark as the most recently used (prevents it from being forgotten)self.used_models.remove(model_name)self.used_models.append(model_name)else:current_time = datetime.now()# Retain history of new model requests from the last 20 minutes (1200 seconds)self.new_model_history = [t for t in self.new_model_historyif (current_time - t).total_seconds() < 1200]# Allow a maximum of 5 NEW model requests per 20 minutesif len(self.new_model_history) >= 5:yield "Rate limit exceeded: Too many new models requested."raise gr.Error("Too many new models requested. Please reuse your previously loaded models or wait a few minutes before trying new ones.")# Log the new model attemptself.new_model_history.append(current_time)self.used_models.append(model_name)# Prevent the bypass list from growing infinitely (cap at 5 most recent models)if len(self.used_models) > 5:self.used_models.pop(0)# --- Anti-Abuse Check End ---lock_key = model_namewhile True:with self.download_lock:if lock_key not in self.active_downloads:self.active_downloads.add(lock_key)breakyield f"Waiting for existing download to finish: {escape_html(model_name)}..."time.sleep(1)try:# download link model > model_nameif model_name.startswith("http"):yield f"Downloading model: {escape_html(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,revision="main",token=True,)self.update_inventory(model_name)except Exception as e:raise efinally:with self.download_lock:self.active_downloads.discard(lock_key)for i in range(68):if not self.status_loading:8 unmodified linesself.status_loading = Trueyield f"Loading model: {escape_html(model_name)}"if vae_model == "BakedVAE":vae_model = model_name15 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],14 unmodified linesself.last_load = datetime.now()self.status_loading = Falseyield f"Model loaded: {escape_html(model_name)}"# @spaces.GPU(duration=59)@torch.inference_mode()75 unmodified linest2i_adapter_preprocessor,t2i_adapter_conditioning_scale,t2i_adapter_conditioning_factor,enable_live_preview,freeu,generator_in_cpu,adetailer_inpaint_only,41 unmodified linesvae_model = vae_model if vae_model != "None" else Noneloras_list = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]vae_msg = f"VAE: {escape_html(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""sampler": sampler,"schedule_type": schedule_type,"schedule_prediction_type": schedule_prediction_type,"xformers_memory_efficient_attention": False,"gui_active": True,"loop_generation": loop_generation,"controlnet_conditioning_scale": float(controlnet_output_scaling_in_unet),8 unmodified lines"leave_progress_bar": leave_progress_bar,"disable_progress_bar": disable_progress_bar,"image_previews": image_previews,"display_images": False,"save_generated_images": save_generated_images,"filename_pattern": filename_pattern,"image_storage_location": image_storage_location,29 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()12 unmodified linesfor status, lora in zip(self.model.lora_status, self.model.lora_memory):if status:msg_lora += f"<br>Loaded: {escape_html(lora)}"elif status is not None:msg_lora += f"<br>Error with: {escape_html(lora)}"if msg_lora:info_images += msg_lora2 unmodified linesdownload_links = "<br>".join([f'<a href="{path.replace("/images/", f"/gradio_api/file={allowed_path}/")}" download="{escape_html(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}"if not display_images:img = gr.update()info_state = "COMPLETE"elif not enable_live_preview:img = gr.update()yield info_state, img, info_imagesdef dynamic_gpu_duration(func, duration, *args):# @torch.inference_mode()@spaces.GPU(duration=(duration/1.5)) # https://pypi-browser.org/package/spaces/spaces-0.51.1-py3-none-any.whl/spaces/zero/configs.json#L18def wrapped_func():yield from func(*args)57 unmodified lines)gr.Info(f"LoRAs in cache: {lora_cache_msg}")msg_request = f"Requesting {gpu_duration_arg}s. of GPU time.\nModel: {escape_html(sd_gen.model.base_model_id)}"if verbose_arg:gr.Info(msg_request)print(msg_request)23 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(fill_width=True, fill_height=False) as app:gr.Markdown("# 🧩 DiffuseCraft")gr.Markdown(SUBTITLE_GUI)with gr.Tab("Generation"):9 unmodified linesreturn gr.update(value=task_name, choices=new_choices)with gr.Accordion("Model and Task", open=True, visible=True):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")with gr.Accordion("Negative prompt", open=False, visible=True):neg_prompt_gui = gr.Textbox(lines=3, placeholder="Enter Neg prompt", label="Negative prompt", value="bad anatomy, ((many hands, bad hands, missing fingers)), anatomical nonsense, ugly, deformed, bad proportions, bad shadow, extra limbs, missing limbs, floating limbs, disconnected limbs, malformed hands, poorly drawn, mutation, mutated hands and fingers, extra legs, interlocked fingers, extra arms, disfigured face, long neck, asymmetrical eyes, lowres, extra digit, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry, duplicate, bad composition, text, worst quality, normal quality, low quality, very displeasing, desaturated, low contrast, muted tones, washed out, unfinished, incomplete, draft, logo, backlighting")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")11 unmodified linesresult_images = gr.Gallery(label="Generated images",show_label=False,# elem_id="gallery",columns=[2],rows=[2],object_fit="contain",# height="auto",interactive=False,preview=True,selected_index=None,)actual_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")load_lora_cpu_gui = gr.Checkbox(value=False, container=False, label="Load LoRAs on CPU")with gr.Column(scale=1):with gr.Accordion("Generation settings", open=True, visible=True):steps_gui = gr.Slider(minimum=1, maximum=100, step=1, value=30, 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=832, label="Img Width")img_height_gui = gr.Slider(minimum=64, maximum=4096, step=8, value=1216, 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=True, label="FreeU")with gr.Row(equal_height=False):num_images_gui = gr.Slider(minimum=1, maximum=(16 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[2][1])vae_model_gui = gr.Dropdown(label="VAE Model", choices=vae_model_list, value=vae_model_list[0])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),"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(),"Prompt emphasis": gr.update(),"VAE": 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)# 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_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}")new_lora_model_list = get_model_list(DIRECTORY_LORAS)new_lora_model_list.insert(0, "None")num_lora = 1for parsed_l, parsed_s in parsed_params:filtered_loras = [m for m in new_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:try:if 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:continueif key == "Prompt emphasis":if val not in PROMPT_WEIGHT_OPTIONS_PRIORITY:continueelif key == "Clip skip":if "," in str(val):val = val.replace(",", "")if int(val) >= 2:val = 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\r\n]+", " ", re.sub(r"[ \t]*,[ \t,]*", ", ", 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]if filtered_models:val = filtered_models[0]else:val = name_modelif key == "VAE":val_unquote = urllib.parse.unquote(str(val))filtered_vaes = [v for v in vae_model_list if str(val) in v or val_unquote in v]if filtered_vaes:val = filtered_vaes[0]elif val in ["None", "BakedVAE"]:val = valelse:continueif 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)except Exception as e:print(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(run_clear_prompt_gui, [], [prompt_gui, neg_prompt_gui])def run_set_random_seed():return -1set_random_seed.click(run_set_random_seed, [], seed_gui)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 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 = 8 if IS_ZERO_GPU else 10return 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")lora_scale_6_gui = lora_scale_slider("Lora Scale 6")lora7_gui = lora_dropdown("Lora7")lora_scale_7_gui = lora_scale_slider("Lora Scale 7")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")16 unmodified lineslabel="Style Prompt",interactive=True,)style_json_gui = gr.File(label="Style JSON File", file_count="single", file_types=[".json"])style_button = gr.Button("Load styles")def load_json_style_file(json):5 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")39 unmodified linesschedule_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")enable_live_preview_gui = gr.Checkbox(value=True, label="Enable live previews")display_images_gui = gr.Checkbox(value=True, label="Show final results")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.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")image_previews_gui = gr.Checkbox(value=True, label="Image Previews (alt)")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")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,prompt_syntax_gui,vae_model_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)50 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)12 unmodified linesimage_metadata = gr.Image(label="Image with metadata", type="pil", sources=["upload"])with gr.Column():result_metadata = gr.Textbox(label="Metadata", show_label=True, buttons=["copy"], interactive=False, container=True, max_lines=99)image_metadata.change(fn=extract_exif_data,36 unmodified linesoutputs=[load_model_gui],queue=True,show_progress="minimal",api_visibility=("private" if HIDE_API else "public"),).success(fn=sd_gen_generate_pipeline, # fn=sd_gen.generate_pipeline,inputs=[73 unmodified linest2i_adapter_preprocessor_gui,adapter_conditioning_scale_gui,adapter_conditioning_factor_gui,enable_live_preview_gui,free_u_gui,generator_in_cpu_gui,adetailer_inpaint_only_gui,42 unmodified linesoutputs=[load_model_gui, result_images, actual_task_info],queue=True,show_progress="minimal",# api_visibility=("private" if HIDE_API else "public"),)if __name__ == "__main__":app.queue()app.launch(show_error=True,share=args.share_enabled,debug=True,ssr_mode=args.ssr,allowed_paths=[allowed_path],footer_links=(["api", "gradio", "settings"] if not HIDE_API else ["gradio", "settings"]),theme=args.theme,css=CSS,)123451 unmodified line78910111227 unmodified lines40414243444546474849509 unmodified lines6061626364653 unmodified lines69707172737475767778798081821 unmodified line8485868788899091929394959697989910010110211 unmodified lines1141151161171181191201211221231241251261271283 unmodified lines1321331341351361371383 unmodified lines1421431441451461472 unmodified lines1501511521531541551561571581591601611623 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871888 unmodified lines19719819920020120220315 unmodified lines2192202212222232242252262272283 unmodified lines23223323423523623723814 unmodified lines25325425525625725825975 unmodified lines33533633733833934034141 unmodified lines38338438538638738838939039139291 unmodified lines4844854864874884894904914924934944954964974984995005015025035045055065075085098 unmodified lines51851952052152252352429 unmodified lines55455555655755855956056156256356412 unmodified lines5775785795805815825835845852 unmodified lines58858959059159259359459559659759859960060160260360460560660760860957 unmodified lines66766866967067167267323 unmodified lines69769869970070170270310 unmodified lines7147157167177187197202 unmodified lines7237247257267277287297307317327339 unmodified lines74374474574674774874975075175211 unmodified lines76476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191210 unmodified lines9239249259269279289295 unmodified lines9359369379389399409419429439442 unmodified lines94794894995095195295358 unmodified lines1012101310141015101610171018101916 unmodified lines10361037103810391040104110425 unmodified lines104810491050105110521053105439 unmodified lines1094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111650 unmodified lines116711681169117011711172117311741175117612 unmodified lines118911901191119211931194119536 unmodified lines12321233123412351236123773 unmodified lines131113121313131413151316131742 unmodified lines136013611362136313641365136613671368136913701371import spacesimport osfrom stablepy import (Model_Diffusers,SCHEDULE_TYPE_OPTIONS,1 unmodified linecheck_scheduler_compatibility,TASK_AND_PREPROCESSORS,FACE_RESTORATION_MODELS,scheduler_names,)from constants import (27 unmodified linesDIFFUSERS_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,9 unmodified linesprogress_step_bar,html_template_message,escape_html,)from image_processor import preprocessor_tabfrom datetime import datetime3 unmodified linesimport warningsfrom stablepy import loggerfrom diffusers import FluxPipeline# 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 = None2 unmodified linesself.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:breakremoval_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 = [3 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):_ = 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:8 unmodified linesself.status_loading = Trueyield f"Loading model: {model_name}"if vae_model == "BakedVAE":vae_model = model_name15 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],14 unmodified linesself.last_load = datetime.now()self.status_loading = Falseyield f"Model loaded: {model_name}"# @spaces.GPU(duration=59)@torch.inference_mode()75 unmodified linest2i_adapter_preprocessor,t2i_adapter_conditioning_scale,t2i_adapter_conditioning_factor,xformers_memory_efficient_attention,freeu,generator_in_cpu,adetailer_inpaint_only,41 unmodified linesvae_model = vae_model if vae_model != "None" else Noneloras_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]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""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),8 unmodified lines"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,29 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()12 unmodified linesfor 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_lora2 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)])if save_generated_images:info_images += f"<br>{download_links}"info_state = "COMPLETE"yield info_state, img, info_imagesdef dynamic_gpu_duration(func, duration, *args):# @torch.inference_mode()@spaces.GPU(duration=duration)def wrapped_func():yield from func(*args)57 unmodified lines)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)23 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"):9 unmodified linesreturn 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")11 unmodified linesresult_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_samplerparameters["Schedule type"] = s_typefor key, val in parameters.items():# print(val)if key in valid_keys:try:if 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(",", "")if int(val) >= 2:val = 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]if filtered_models:val = filtered_models[0]else:val = name_modelif key == "Seed":continuevalid_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 -1set_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")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")16 unmodified lineslabel="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):5 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")39 unmodified linesschedule_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)50 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)12 unmodified linesimage_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,36 unmodified linesoutputs=[load_model_gui],queue=True,show_progress="minimal",).success(fn=sd_gen_generate_pipeline, # fn=sd_gen.generate_pipeline,inputs=[73 unmodified linest2i_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,42 unmodified linesoutputs=[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/"],)
6 unmodified lines789101112131415161718192021222324252627282930313233343536373839402 unmodified lines4344454647484950515253545556575859606162634 unmodified lines68697071727374754 unmodified lines80818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241259 unmodified lines1351361371381391401411421431441 unmodified line1461471481491501511521531541551561571581593 unmodified lines16316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319 unmodified lines21321421521621721821922022115 unmodified lines23723823924024124224324424524624735 unmodified lines28328428528628728828966 unmodified lines35635735835936036136236336446 unmodified lines411412413414415416417418419420421117 unmodified lines53954054154254354454588 unmodified lines6346356366376386396406 unmodified linesALL_BUILTIN_UPSCALERS,IP_ADAPTERS_SD,IP_ADAPTERS_SDXL,PROMPT_WEIGHT_OPTIONS_PRIORITY,)IS_ZERO_GPU = bool(os.getenv("SPACES_ZERO_GPU"))# - **Download Models**DOWNLOAD_MODEL = "https://huggingface.co/zuv0/test/resolve/main/milkyWonderland_v40.safetensors"# - **Download VAEs**DOWNLOAD_VAE = "https://huggingface.co/Anzhc/Anzhcs-VAEs/resolve/main/SDXL%20Anime%20VAE%20Dec-only%20B3.safetensors, 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"LOAD_DIFFUSERS_FORMAT_MODEL = ['stabilityai/stable-diffusion-xl-base-1.0','TestOrganizationPleaseIgnore/potato_quality_anime_plzwork_sdxl','TestOrganizationPleaseIgnore/rinAnim8drawIllustriousXL_v20_sdxl','TestOrganizationPleaseIgnore/perfectrsbmixIllustrious_definitiveiota_sdxl','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','martineux/nova-unreal10','John6666/mistoon-anime-v10illustrious-sdxl','John6666/hassaku-xl-illustrious-v22-sdxl','John6666/hassaku-xl-illustrious-v31-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/cat-tower-noobai-xl-checkpoint-v20-vpred-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/one-obsession-17-red-sdxl','martineux/oneobs18','martineux/oneobsession19','John6666/cat-tower-noobai-xl-checkpoint-v14-epsilon-pred-sdxl','martineux/cattower-chenkin-xl','John6666/prefect-illustrious-xl-v3-sdxl','martineux/perfect4','martineux/prefectIllustriousXL_v5','John6666/wai-nsfw-illustrious-v70-sdxl','John6666/wai-nsfw-illustrious-sdxl-v140-sdxl','martineux/waiIllustriousSDXL_v160','John6666/illustrious-pony-mix-v3-sdxl','John6666/nova-anime-xl-il-v90-sdxl','John6666/nova-anime-xl-il-v110-sdxl','frankjoshua/novaAnimeXL_ilV140','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','martineux/nova-unreal10','John6666/nova-cartoon-xl-v40-sdxl','martineux/novacartoon6','martineux/novareal8','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','Raelina/Raehoshi-illust-XL-8','johnkillington/chenkinxmilfynoobai_v20-MLX','martineux/unholydesire5-xl','abacaxthebrave/Unholy_Desire_Mix_ILXL','martineux/diving5','martineux/diving7','martineux/mergestein-animuplus-xl','martineux/mergestein-uncannyr2-xl','martineux/steincustom_V12','martineux/miaomiao-realskin1p25-xl','martineux/miaov18','John6666/garage-mix-noob-vpred-eps-v10-vpred-sdxl','TestOrganizationPleaseIgnore/perfectrsbmixIllustrious_definitivelambda_sdxl','TestOrganizationPleaseIgnore/rinFlanimeIllustrious_v27_sdxl','TestOrganizationPleaseIgnore/rinAnimepopcute_v30_sdxl','TestOrganizationPleaseIgnore/potato_quality_anime_zzz_sdxl','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",66 unmodified lines# "InstantX/FLUX.1-dev-Controlnet-Canny",]PROMPT_W_OPTIONS = [(pwf, pwf) for pwf in PROMPT_WEIGHT_OPTIONS_PRIORITY]PROMPT_W_OPTIONS[0] = ("Classic format: (word:weight)", "Classic")PROMPT_W_OPTIONS[1] = ("Compel format: (word)weight", "Compel")WARNING_MSG_VAE = ("Use the right VAE for your model to maintain image quality. The wrong"46 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).""")6 unmodified lines789101112131415161718192021222324252627282930313233342 unmodified lines37383940414243444546474849505152535455565758594 unmodified lines6465666768694 unmodified lines747576777879808182838485868788899091929 unmodified lines1021031041051061071081091 unmodified line1111121131141151161171181191201211221233 unmodified lines12712812913013113213313413513613713813919 unmodified lines15916016116216316416516616715 unmodified lines18318418518618718818919035 unmodified lines22622722822923023166 unmodified lines29829930030130230330430530630730830931031131246 unmodified lines359360361362363364365366367117 unmodified lines48548648748848949049188 unmodified lines5805815825835845856 unmodified linesALL_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',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','odyssey-labs/OdysseyXL-3.0','odyssey-labs/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",66 unmodified lines# "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"46 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).""")
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")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")
12git-lfsffmpeg123git-lfsaria2 -yffmpeg
1pip>=23.0.01234567891011121314stablepy==0.6.5torch==2.8.0diffusersgdownopencv-pythonunidecode# pydantic==2.10.6huggingface_hubhf_transferhf_xetspacesgradio==6.10.0matplotlib-inlinemediapipe==0.10.1312345stablepy==0.6.0torch==2.2.0gdownopencv-pythonunidecode
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779import osimport reimport ipaddressimport urllib.parsefrom shlex import quote as shqtimport 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_ROOT,CACHE_HF,STORAGE_ROOT,)from huggingface_hub import HfApi, get_hf_file_metadata, 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 copyimport requestsfrom requests.adapters import HTTPAdapterfrom urllib3.util import Retryimport shutilimport subprocessimport jsonfrom html import escape as escIS_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'MODEL_ARCH = {'stable-diffusion-xl-v1-base/lora': "Stable Diffusion XL (Illustrious, Pony, NoobAI)",'stable-diffusion-v1/lora': "Stable Diffusion 1.5",'flux-1-dev/lora': "Flux",}def validate_url(url: str) -> str:"""Validate URL protocol and host."""url = url.strip()if not url:raise ValueError("URL cannot be empty.")parsed = urllib.parse.urlparse(url)if parsed.scheme != "https":raise ValueError(f"Invalid protocol '{parsed.scheme}'. Only HTTPS is allowed.")hostname = (parsed.hostname or "").lower()if not hostname:raise ValueError("Invalid URL: missing hostname.")# Restrict local and internal endpointsif hostname in ("localhost", "0.0.0.0", "127.0.0.1", "::1"):raise ValueError("Restricted address.")# Restrict private IP addressestry:ip = ipaddress.ip_address(hostname)if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:raise ValueError(f"Access to ({hostname}) is blocked.")except ValueError:pass # Standard domain name# Normalize domain aliasif hostname == "civitai.red" or hostname.endswith(".civitai.red"):url = url.replace("civitai.red", "civitai.com")return urldef read_safetensors_header_from_url(url: str):"""Read safetensors header from a remote Hugging Face file."""url = validate_url(url)meta = get_hf_file_metadata(url)# Step 1: first 8 bytes → header lengthresp = requests.get(meta.location, headers={"Range": "bytes=0-7"})resp.raise_for_status()header_len = int.from_bytes(resp.content, "little")# Step 2: fetch full header JSONend = 8 + header_len - 1resp = requests.get(meta.location, headers={"Range": f"bytes=8-{end}"})resp.raise_for_status()header_json = resp.content.decode("utf-8")return json.loads(header_json)def read_safetensors_header_from_file(path: str):"""Read safetensors header from a local file."""with open(path, "rb") as f:# Step 1: first 8 bytes → header lengthheader_len = int.from_bytes(f.read(8), "little")# Step 2: read header JSONheader_json = f.read(header_len).decode("utf-8")return json.loads(header_json)class LoraHeaderInformation:"""Encapsulates parsed info from a LoRA JSON header and providesa compact HTML summary via .to_html()."""def __init__(self, json_data):self.original_json = copy.deepcopy(json_data or {})# Check if text encoder was trained# guard for json_data being a mappingtry:self.text_encoder_trained = any("text_model" in ln for ln in json_data)except Exception:self.text_encoder_trained = False# Metadata (may be None)metadata = (json_data or {}).get("__metadata__", None)self.metadata = metadata# Default valuesself.architecture = "undefined"self.prediction_type = "undefined"self.base_model = "undefined"self.author = "undefined"self.title = "undefined"self.common_tags_list = []if metadata:self.architecture = MODEL_ARCH.get(metadata.get('modelspec.architecture', None),"undefined")self.prediction_type = metadata.get('modelspec.prediction_type', "undefined")self.base_model = metadata.get('ss_sd_model_name', "undefined")self.author = metadata.get('modelspec.author', "undefined")self.title = metadata.get('modelspec.title', "undefined")base_model_hash = metadata.get('ss_new_sd_model_hash', None) # SHA256# AUTOV1 ss_sd_model_hash# https://civitai.com/api/v1/model-versions/by-hash/{base_model_hash} # Infoif base_model_hash:self.base_model += f" hash={base_model_hash}"# Extract tagstry:tags = metadata.get('ss_tag_frequency') if "ss_tag_frequency" in metadata else metadata.get('ss_datasets', "")tags = json.loads(tags) if tags else ""if isinstance(tags, list):tags = tags[0].get("tag_frequency", {})if tags:self.common_tags_list = list(tags[list(tags.keys())[0]].keys())except Exception:self.common_tags_list = []def to_dict(self):"""Return a plain dict summary of parsed fields."""return {"architecture": self.architecture,"prediction_type": self.prediction_type,"base_model": self.base_model,"author": self.author,"title": self.title,"text_encoder_trained": bool(self.text_encoder_trained),"common_tags": self.common_tags_list,}def to_html(self, limit_tags=20):"""Return a compact HTML snippet (string) showing the parsed infoin a small font. Values are HTML-escaped."""rows = [("Title", esc(str(self.title))),("Author", esc(str(self.author))),("Architecture", esc(str(self.architecture))),("Base model", esc(str(self.base_model))),("Prediction type", esc(str(self.prediction_type))),("Text encoder trained", esc(str(self.text_encoder_trained))),("Reference tags", esc(str(", ".join(self.common_tags_list[:limit_tags])))),]# small, compact table with inline styling (small font)html_rows = "".join(f"<tr><th style='text-align:left;padding:2px 6px;white-space:nowrap'>{k}</th>"f"<td style='padding:2px 6px'>{v}</td></tr>"for k, v in rows)html_snippet = ("<div style='font-family:system-ui, -apple-system, \"Segoe UI\", Roboto, ""Helvetica, Arial, \"Noto Sans\", sans-serif; font-size:12px; line-height:1.2; ""'>"f"<table style='border-collapse:collapse; font-size:12px;'>"f"{html_rows}""</table>""</div>")return html_snippetdef 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 Noneexcept Exception as e:print(f"Error: {e}")return Noneclass 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 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 {shqt(f"Authorization: Bearer {civitai_api_key}")} {shqt(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_basewget_command = (f'wget -c -nv 'f'-O {shqt(os.path.join(dir_, filename_base))} {shqt(redirect_url)}')r_code = os.system(wget_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 wget.If an API key limit is reached, generating a new API key and using it can fix the issue. no"""output_path = Noneurl_dl = url + f"?token={civitai_api_key}"if not civ_filename:wget_command = (f'wget -c -nv 'f'-P {shqt(dir_)} {shqt(url_dl)}')os.system(wget_command)else:output_path = os.path.join(dir_, civ_filename)if not os.path.exists(output_path):wget_command = (f'wget -c -nv 'f'-O {shqt(output_path)} {shqt(url_dl)}')os.system(wget_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:os.system(f'wget -c -nv 'f'--header={shqt(f"Authorization: Bearer {hf_token}")} 'f'-O {shqt(output_path)} {shqt(url)}')else:os.system(f'wget -c -nv 'f'-O {shqt(output_path)} {shqt(url)}')return output_pathdef download_things(directory, url, hf_token="", civitai_api_key="", romanize=False):url = url.strip()if not url:return Nonetry:url = validate_url(url)except Exception as e:msg = f"Download blocked: {e}"print(f"\033[91m{msg}\033[0m")gr.Warning(msg)return Nonehostname = (urllib.parse.urlparse(url).hostname or "").lower()downloaded_file_path = Noneif hostname == "drive.google.com" or hostname.endswith(".drive.google.com"):downloaded_file_path = drive_down(url, directory)elif hostname in ("huggingface.co", "hf.co") or hostname.endswith((".huggingface.co", ".hf.co")):downloaded_file_path = hf_down(url, directory, hf_token, romanize)elif hostname == "civitai.com" or hostname.endswith(".civitai.com"):url = url.replace("civitai.red", "civitai.com")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'wget -c -nv 'f'-P {shqt(directory)} {shqt(url)}')return downloaded_file_pathdef 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_listdef extract_parameters(input_string):parameters = {}if "Negative prompt:" not in input_string:if "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:")parameters["neg_prompt"] = parm[0].strip()input_string = "Steps:" + parm[1]input_string = input_string.replace("\n", "").strip()# Extracting Stepssteps_match = re.search(r'Steps: (\d+)', input_string)if steps_match:parameters['Steps'] = int(steps_match.group(1))# Extracting Sizesize_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'] = widthparameters['height'] = height# Extracting other parametersother_parameters = re.findall(r'([^,:]+): (.*?)(?=, [^,:]+:|$)', input_string)for param in other_parameters:parameters[param[0].strip()] = param[1].strip('"')return parametersdef 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_LORASmsg_lora = "Downloaded"if l_name:msg_lora += f": <b>{escape_html(os.path.basename(l_name))}</b>"print(msg_lora)try:# Works with non-Civitai loras.json_data = read_safetensors_header_from_file(l_name)metadata_lora = LoraHeaderInformation(json_data)msg_lora += "<br>" + metadata_lora.to_html()except Exception:passreturn 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 modeldefault = "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.tagsfor tag in tags:if tag in MODEL_TYPE_CLASS.keys():return MODEL_TYPE_CLASS.get(tag, default)except Exception:return defaultreturn defaultdef 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 npimport timetime.sleep(0.5)transparent_image = img["layers"][0]# Extract the alpha channelalpha_channel = np.array(transparent_image)[:, :, 3]# Create a binary mask by thresholding the alpha channelbinary_mask = alpha_channel > 1if invert:print("Invert")# Invert the binary mask so that the drawn shape is white and the rest is blackbinary_mask = np.invert(binary_mask)# Convert the binary mask to a 3-channel RGB maskrgb_mask = np.stack((binary_mask,) * 3, axis=-1)# Convert the mask to uint8rgb_mask = rgb_mask.astype(np.uint8) * 255return img["background"], rgb_maskdef download_diffuser_repo(repo_name: str, model_type: str, revision: str = "main", token=True):variant = Noneif token is True and not os.environ.get("HF_TOKEN"):token = Noneif 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_folderdef 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_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 = 999print(f"Error while retrieving the used storage: {e}.")return used_gbdef 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 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):shutil.rmtree(CACHE_HF, ignore_errors=True)print(f"Hugging Face cache cleared: {CACHE_HF}")else:print(f"No Hugging Face cache found at: {CACHE_HF}")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))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."""if text is None:return ""return esc(str(text), quote=True).replace("\n", "<br>")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485import 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 subprocessUSER_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 Noneexcept Exception as e:print(f"Error: {e}")return Noneclass 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 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}")return downloaded_file_pathdef 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_listdef 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_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:")parameters["neg_prompt"] = parm[0].strip()input_string = "Steps:" + parm[1]# Extracting Stepssteps_match = re.search(r'Steps: (\d+)', input_string)if steps_match:parameters['Steps'] = int(steps_match.group(1))# Extracting Sizesize_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'] = widthparameters['height'] = height# Extracting other parametersother_parameters = re.findall(r'([^,:]+): (.*?)(?=, [^,:]+:|$)', input_string)for param in other_parameters:parameters[param[0].strip()] = param[1].strip('"')return parametersdef 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_LORASmsg_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 modeldefault = "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.tagsfor tag in tags:if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)except Exception:return defaultreturn defaultdef 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 npimport timetime.sleep(0.5)transparent_image = img["layers"][0]# Extract the alpha channelalpha_channel = np.array(transparent_image)[:, :, 3]# Create a binary mask by thresholding the alpha channelbinary_mask = alpha_channel > 1if invert:print("Invert")# Invert the binary mask so that the drawn shape is white and the rest is blackbinary_mask = np.invert(binary_mask)# Convert the binary mask to a 3-channel RGB maskrgb_mask = np.stack((binary_mask,) * 3, axis=-1)# Convert the mask to uint8rgb_mask = rgb_mask.astype(np.uint8) * 255return img["background"], rgb_maskdef download_diffuser_repo(repo_name: str, model_type: str, revision: str = "main", token=True):variant = Noneif token is True and not os.environ.get("HF_TOKEN"):token = Noneif 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_folderdef 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_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 = 999print(f"Error while retrieving the used storage: {e}.")return used_gbdef 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 widthpercentage = 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>")
.gitignoreDeleted-207
README.md+1-2
app.py+217-443
constants.py+34-89
image_processor.py+2-2
packages.txt+1
pre-requirements.txtDeleted-1
requirements.txt+3-12
utils.py+485-779