Spaces:
Running on Zero
Running on Zero
Upload 5 files
#7
by Legolas490 - opened
Files changed (13)
- .gitignoreDeleted-207
- README.md+1-4
- app.py
- constants.pyDeleted-640
- image_processor.pyDeleted-130
- lora_dict.jsonAdded
- model_dict.jsonAdded
- modutils.pyAdded+1290
- packages.txt+1
- pre-requirements.txtDeleted-1
- requirements.txt+3-13
- stablepy_model.pyAdded
- utils.py+49-778
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 lines45678789101113141213143 unmodified linescolorFrom: redcolorTo: pinksdk: gradiosdk_version: 6.10.0python_version: '3.12'sdk_version: 4.31.3app_file: app.pypinned: truelicense: mitshort_description: Stunning images using stable diffusion.preload_from_hub: - madebyollin/sdxl-vae-fp16-fix config.json,diffusion_pytorch_model.safetensors---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640import osfrom stablepy.diffusers_vanilla.constants import FLUX_CN_UNION_MODESfrom stablepy import ( scheduler_names, SD15_TASKS, SDXL_TASKS, ALL_BUILTIN_UPSCALERS, IP_ADAPTERS_SD, IP_ADAPTERS_SDXL, 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', 'terminusresearch/FluxBooru-v0.3', 'black-forest-labs/FLUX.1-schnell', # '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', 'Laxhar/noobai-XL-Vpred-0.9r', 'Laxhar/noobai-XL-Vpred-0.75s', 'Laxhar/noobai-XL-Vpred-0.75', 'Laxhar/noobai-XL-Vpred-0.65s', 'Laxhar/noobai-XL-Vpred-0.65', 'Laxhar/noobai-XL-Vpred-0.6', 'John6666/cat-tower-noobai-xl-checkpoint-v14vpred-sdxl', 'John6666/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', 'John6666/chadmix-noobai075-illustrious01-v10-sdxl', 'OnomaAIResearch/Illustrious-xl-early-release-v0', 'John6666/illustriousxl-mmmix-v50-sdxl', 'John6666/illustrious-pencil-xl-v200-sdxl', 'John6666/obsession-illustriousxl-v21-sdxl', 'John6666/obsession-illustriousxl-v30-sdxl', 'John6666/obsession-illustriousxl-v31-sdxl', 'John6666/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', 'misri/newrealityxlAllInOne_Newreality40', 'gsdf/CounterfeitXL', 'WhiteAiZ/autismmixSDXL_autismmixConfetti_diffusers', 'kitty7779/ponyDiffusionV6XL', 'GraydientPlatformAPI/aniverse-pony', 'John6666/ras-real-anime-screencap-v1-sdxl', 'John6666/duchaiten-pony-xl-no-score-v60-sdxl', 'John6666/mistoon-anime-ponyalpha-sdxl', 'John6666/mistoon-xl-copper-v20fast-sdxl', 'John6666/ebara-mfcg-pony-mix-v12-sdxl', 'John6666/t-ponynai3-v51-sdxl', 'John6666/t-ponynai3-v65-sdxl', 'John6666/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', 'John6666/wai-shuffle-pdxl-v2-sdxl', 'John6666/wai-c-v6-sdxl', 'John6666/iniverse-mix-xl-sfwnsfw-pony-guofeng-v43-sdxl', 'John6666/sifw-annihilation-xl-v2-sdxl', 'John6666/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', 'John6666/aimz-dream-real-pony-mix-v3-sdxl', 'John6666/prefectious-xl-nsfw-v10-sdxl', 'GraydientPlatformAPI/iniverseponyRealGuofeng49', 'John6666/duchaiten-pony-real-v11fix-sdxl', 'John6666/duchaiten-pony-real-v20-sdxl', 'John6666/duchaiten-pony-xl-no-score-v70-sdxl', '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', 'digiplay/DreamShaper_8', 'digiplay/BeautifulArt_v1', 'digiplay/DarkSushi2.5D_v1', 'digiplay/darkphoenix3D_v1.1', 'digiplay/BeenYouLiteL11_diffusers', 'GraydientPlatformAPI/rev-animated2', 'myxlmynx/cyberrealistic_classic40', 'GraydientPlatformAPI/cyberreal6', 'GraydientPlatformAPI/cyberreal5', 'youknownothing/deliberate-v6', 'GraydientPlatformAPI/deliberate-cyber3', 'GraydientPlatformAPI/picx-real', 'GraydientPlatformAPI/perfectworld6', 'emilianJR/epiCRealism', 'votepurchase/counterfeitV30_v30', 'votepurchase/ChilloutMix', 'Meina/MeinaMix_V11', 'Meina/MeinaUnreal_V5', 'Meina/MeinaPastel_V7', 'GraydientPlatformAPI/realcartoon3d-17', 'GraydientPlatformAPI/realcartoon-pixar11', 'GraydientPlatformAPI/realcartoon-real17',]
DIFFUSERS_FORMAT_LORAS = [ "nerijs/animation2k-flux", "XLabs-AI/flux-RealismLora", "Shakker-Labs/FLUX.1-dev-LoRA-Logo-Design",]
DOWNLOAD_EMBEDS = [ 'https://huggingface.co/datasets/Nerfgun3/bad_prompt/blob/main/bad_prompt_version2.pt', # 'https://huggingface.co/embed/negative/resolve/main/EasyNegativeV2.safetensors', # 'https://huggingface.co/embed/negative/resolve/main/bad-hands-5.pt',]
CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")HF_TOKEN = os.environ.get("HF_READ_TOKEN")
DIRECTORY_MODELS = 'models'DIRECTORY_LORAS = 'loras'DIRECTORY_VAES = 'vaes'DIRECTORY_EMBEDS = 'embedings'DIRECTORY_UPSCALERS = 'upscalers'
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_HF
TASK_STABLEPY = { 'txt2img': 'txt2img', 'img2img': 'img2img', 'inpaint': 'inpaint', # 'canny T2I Adapter': 'sdxl_canny_t2i', # NO HAVE STEP CALLBACK PARAMETERS SO NOT WORKS WITH DIFFUSERS 0.29.0 # 'sketch T2I Adapter': 'sdxl_sketch_t2i', # 'lineart T2I Adapter': 'sdxl_lineart_t2i', # 'depth-midas T2I Adapter': 'sdxl_depth-midas_t2i', # 'openpose T2I Adapter': 'sdxl_openpose_t2i', 'openpose ControlNet': 'openpose', 'canny ControlNet': 'canny', 'mlsd ControlNet': 'mlsd', 'scribble ControlNet': 'scribble', 'softedge ControlNet': 'softedge', 'segmentation ControlNet': 'segmentation', 'depth ControlNet': 'depth', 'normalbae ControlNet': 'normalbae', 'lineart ControlNet': 'lineart', 'lineart_anime ControlNet': 'lineart_anime', 'shuffle ControlNet': 'shuffle', 'ip2p ControlNet': 'ip2p', 'optical pattern ControlNet': 'pattern', 'recolor ControlNet': 'recolor', 'tile ControlNet': 'tile', 'repaint ControlNet': 'repaint',}
TASK_MODEL_LIST = list(TASK_STABLEPY.keys())
UPSCALER_DICT_GUI = { None: None, **{bu: bu for bu in ALL_BUILTIN_UPSCALERS if bu not in ["HAT x4", "DAT x4", "DAT x3", "DAT x2", "SwinIR 4x"]}, # "RealESRGAN_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth", "RealESRNet_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth", # "RealESRGAN_x4plus_anime_6B": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth", # "RealESRGAN_x2plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth", # "realesr-animevideov3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth", # "realesr-general-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth", # "realesr-general-wdn-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth", "4x-UltraSharp": "https://huggingface.co/Shandypur/ESRGAN-4x-UltraSharp/resolve/main/4x-UltraSharp.pth", "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", "lollypop": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/lollypop.pth", "RealisticRescaler4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/RealisticRescaler%204x.pth", "NickelbackFS4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/NickelbackFS%204x.pth"}
UPSCALER_KEYS = list(UPSCALER_DICT_GUI.keys())
DIFFUSERS_CONTROLNET_MODEL = [ "Automatic",
"brad-twinkl/controlnet-union-sdxl-1.0-promax", "xinsir/controlnet-union-sdxl-1.0", "xinsir/anime-painter", "Eugeoter/noob-sdxl-controlnet-canny", "Eugeoter/noob-sdxl-controlnet-lineart_anime", "Eugeoter/noob-sdxl-controlnet-depth", "Eugeoter/noob-sdxl-controlnet-normal", "Eugeoter/noob-sdxl-controlnet-softedge_hed", "Eugeoter/noob-sdxl-controlnet-scribble_pidinet", "Eugeoter/noob-sdxl-controlnet-scribble_hed", "Eugeoter/noob-sdxl-controlnet-manga_line", "Eugeoter/noob-sdxl-controlnet-lineart_realistic", "Eugeoter/noob-sdxl-controlnet-depth_midas-v1-1", "dimitribarbot/controlnet-openpose-sdxl-1.0-safetensors", "r3gm/controlnet-openpose-sdxl-1.0-fp16", "r3gm/controlnet-canny-scribble-integrated-sdxl-v2-fp16", "r3gm/controlnet-union-sdxl-1.0-fp16", "r3gm/controlnet-lineart-anime-sdxl-fp16", "r3gm/control_v1p_sdxl_qrcode_monster_fp16", "r3gm/controlnet-tile-sdxl-1.0-fp16", "r3gm/controlnet-recolor-sdxl-fp16", "r3gm/controlnet-openpose-twins-sdxl-1.0-fp16", "r3gm/controlnet-qr-pattern-sdxl-fp16", "Yakonrus/SDXL_Controlnet_Tile_Realistic_v2", "TheMistoAI/MistoLine", "briaai/BRIA-2.3-ControlNet-Recoloring", "briaai/BRIA-2.3-ControlNet-Canny",
"lllyasviel/control_v11p_sd15_openpose", "lllyasviel/control_v11p_sd15_canny", "lllyasviel/control_v11p_sd15_mlsd", "lllyasviel/control_v11p_sd15_scribble", "lllyasviel/control_v11p_sd15_softedge", "lllyasviel/control_v11p_sd15_seg", "lllyasviel/control_v11f1p_sd15_depth", "lllyasviel/control_v11p_sd15_normalbae", "lllyasviel/control_v11p_sd15_lineart", "lllyasviel/control_v11p_sd15s2_lineart_anime", "lllyasviel/control_v11e_sd15_shuffle", "lllyasviel/control_v11e_sd15_ip2p", "lllyasviel/control_v11p_sd15_inpaint", "monster-labs/control_v1p_sd15_qrcode_monster", "lllyasviel/control_v11f1e_sd15_tile", "latentcat/control_v1p_sd15_brightness", "yuanqiuye/qrcode_controlnet_v3",
"Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro", # "Shakker-Labs/FLUX.1-dev-ControlNet-Pose", # "Shakker-Labs/FLUX.1-dev-ControlNet-Depth", # "jasperai/Flux.1-dev-Controlnet-Upscaler", # "jasperai/Flux.1-dev-Controlnet-Depth", # "jasperai/Flux.1-dev-Controlnet-Surface-Normals", # "XLabs-AI/flux-controlnet-canny-diffusers", # "XLabs-AI/flux-controlnet-hed-diffusers", # "XLabs-AI/flux-controlnet-depth-diffusers", # "InstantX/FLUX.1-dev-Controlnet-Union", # "InstantX/FLUX.1-dev-Controlnet-Canny",]
PROMPT_W_OPTIONS = [(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" " VAE can lead to poor results, like blurriness in the generated images.")
SDXL_TASK = [k for k, v in TASK_STABLEPY.items() if v in SDXL_TASKS]SD_TASK = [k for k, v in TASK_STABLEPY.items() if v in SD15_TASKS]FLUX_TASK = list(TASK_STABLEPY.keys())[:3] + [k for k, v in TASK_STABLEPY.items() if v in FLUX_CN_UNION_MODES.keys()]
MODEL_TYPE_TASK = { "SD 1.5": SD_TASK, "SDXL": SDXL_TASK, "FLUX": FLUX_TASK,}
MODEL_TYPE_CLASS = { "diffusers:StableDiffusionPipeline": "SD 1.5", "diffusers:StableDiffusionXLPipeline": "SDXL", "diffusers:FluxPipeline": "FLUX",}
DIFFUSECRAFT_CHECKPOINT_NAME = { "sd1.5": "SD 1.5", "sdxl": "SDXL", "flux-dev": "FLUX", "flux-schnell": "FLUX",}
POST_PROCESSING_SAMPLER = ["Use same sampler"] + [ name_s for name_s in scheduler_names if "Auto-Loader" not in name_s]
IP_MODELS = []ALL_IPA = sorted(set(IP_ADAPTERS_SD + IP_ADAPTERS_SDXL))
for origin_name in ALL_IPA: suffixes = [] if origin_name in IP_ADAPTERS_SD: suffixes.append("sd1.5") if origin_name in IP_ADAPTERS_SDXL: suffixes.append("sdxl") ref_name = f"{origin_name} ({'/'.join(suffixes)})" IP_MODELS.append((ref_name, origin_name))
MODE_IP_OPTIONS = ["original", "style", "layout", "style+layout"]
SUBTITLE_GUI = ( "### This demo uses [diffusers](https://github.com/huggingface/diffusers)" " to perform different tasks in image generation.")
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. """)
EXAMPLES_GUI_HELP = ( """### The following examples perform specific tasks: 1. Generation with SDXL and upscale 2. Generation with FLUX dev 3. ControlNet Canny SDXL 4. Optical pattern (Optical illusion) SDXL 5. Convert an image to a coloring drawing 6. V prediction model inference 7. V prediction model sd_embed variant inference 8. ControlNet OpenPose SD 1.5 and Latent upscale
- Different tasks can be performed, such as img2img or using the IP adapter, to preserve a person's appearance or a specific style based on an image. """)
EXAMPLES_GUI = [ [ "splatter paint theme, 1girl, frame center, pretty face, face with artistic paint artwork, feminism, long hair, upper body view, futuristic expression illustrative painted background, origami, stripes, explosive paint splashes behind her, hand on cheek pose, strobe lighting, masterpiece photography creative artwork, golden morning light, highly detailed, masterpiece, best quality, very aesthetic, absurdres", "logo, artist name, (worst quality, normal quality), bad-artist, ((bad anatomy)), ((bad hands)), ((bad proportions)), ((duplicate limbs)), ((fused limbs)), ((interlocking fingers)), ((poorly drawn face)), high contrast., score_6, score_5, score_4, lowres, (bad), text, error, fewer, extra, missing, worst quality, jpeg artifacts, low quality, watermark, unfinished, displeasing, oldest, early, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]", 28, 5.0, -1, "None", 0.33, "DPM++ 2M SDE", 1152, 896, "John6666/noobai-xl-nai-xl-epsilonpred10version-sdxl", "txt2img", "image.webp", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Classic-no_norm", "Nearest", 45, False, ], [ "a digital illustration of a movie poster titled 'Finding Emo', finding nemo parody poster, featuring a depressed cartoon clownfish with black emo hair, eyeliner, and piercings, bored expression, swimming in a dark underwater scene, in the background, movie title in a dripping, grungy font, moody blue and purple color palette", "", 24, 3.5, -1, "None", 0.33, "FlowMatch Euler", 1152, 896, "black-forest-labs/FLUX.1-dev", "txt2img", None, # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Classic", None, 70, True, ], [ "((masterpiece)), best quality, blonde disco girl, detailed face, realistic face, realistic hair, dynamic pose, pink pvc, intergalactic disco background, pastel lights, dynamic contrast, airbrush, fine detail, 70s vibe, midriff", "(worst quality:1.2), (bad quality:1.2), (poor quality:1.2), (missing fingers:1.2), bad-artist-anime, bad-artist, bad-picture-chill-75v", 48, 3.5, -1, "None", 0.33, "DPM++ 2M SDE Ef", 1024, 1024, "John6666/epicrealism-xl-v10kiss2-sdxl", "canny ControlNet", "image.webp", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Classic", None, 44, False, ], [ "cinematic scenery old city ruins", "(worst quality, low quality, illustration, 3d, 2d, painting, cartoons, sketch), (illustration, 3d, 2d, painting, cartoons, sketch, blurry, film grain, noise), (low quality, worst quality:1.2)", 50, 4.0, -1, "None", 0.33, "Euler a", 1024, 1024, "SG161222/RealVisXL_V5.0", "optical pattern ControlNet", "spiral_no_transparent.png", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.05, # cn start 0.8, # cn end "Classic", None, 35, False, ], [ "black and white, line art, coloring drawing, clean line art, black strokes, no background, white, black, free lines, black scribbles, on paper, A blend of comic book art and lineart full of black and white color, masterpiece, high-resolution, trending on Pixiv fan box, palette knife, brush strokes, two-dimensional, planar vector, T-shirt design, stickers, and T-shirt design, vector art, fantasy art, Adobe Illustrator, hand-painted, digital painting, low polygon, soft lighting, aerial view, isometric style, retro aesthetics, 8K resolution, black sketch lines, monochrome, invert color", "color, red, green, yellow, colored, duplicate, blurry, abstract, disfigured, deformed, animated, toy, figure, framed, 3d, bad art, poorly drawn, extra limbs, close up, b&w, weird colors, blurry, watermark, blur haze, 2 heads, long neck, watermark, elongated body, cropped image, out of frame, draft, deformed hands, twisted fingers, double image, malformed hands, multiple heads, extra limb, ugly, poorly drawn hands, missing limb, cut-off, over satured, grain, lowères, bad anatomy, poorly drawn face, mutation, mutated, floating limbs, disconnected limbs, out of focus, long body, disgusting, extra fingers, groos proportions, missing arms, mutated hands, cloned face, missing legs, ugly, tiling, poorly drawn hands, poorly drawn feet, poorly drawn face, out of frame, extra limbs, disfigured, deformed, body out of frame, blurry, bad anatomy, blurred, watermark, grainy, signature, cut off, draft, deformed, blurry, bad anatomy, disfigured, poorly drawn face, mutation, bluelish, blue", 20, 4.0, -1, ("loras/Coloring_book_-_LineArt.safetensors" if os.path.exists("loras/Coloring_book_-_LineArt.safetensors") else "None"), 1.0, "DPM++ 2M SDE", 1024, 1024, "eienmojiki/Anything-XL", "lineart ControlNet", "color_image.png", # img conttol 896, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Compel", None, 35, False, ], [ "[mochizuki_shiina], [syuri22], newest, reimu, solo, outdoors, water, flower, lantern", "worst quality, normal quality, old, sketch,", 28, 7.0, -1, "None", 0.33, "DPM 3M Ef", 1600, 1024, "Laxhar/noobai-XL-Vpred-1.0", "txt2img", "color_image.png", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Classic", None, 30, False, ], [ "[mochizuki_shiina], [syuri22], newest, multiple girls, 2girls, earrings, jewelry, gloves, purple eyes, black hair, looking at viewer, nail polish, hat, smile, open mouth, fingerless gloves, sleeveless, :d, upper body, blue eyes, closed mouth, black gloves, hands up, long hair, shirt, bare shoulders, white headwear, blush, black headwear, blue nails, upper teeth only, short hair, white gloves, white shirt, teeth, rabbit hat, star earrings, purple nails, pink hair, detached sleeves, fingernails, fake animal ears, animal hat, sleeves past wrists, black shirt, medium hair, fur trim, sleeveless shirt, turtleneck, long sleeves, rabbit ears, star \\(symbol\\)", "worst quality, normal quality, old, sketch,", 28, 7.0, -1, "None", 0.33, "DPM 3M Ef", 1600, 1024, "Laxhar/noobai-XL-Vpred-1.0", "txt2img", "color_image.png", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 1.0, # cn end "Classic-sd_embed", None, 30, False, ], [ "1girl,face,curly hair,red hair,white background,", "(worst quality:2),(low quality:2),(normal quality:2),lowres,watermark,", 38, 5.0, -1, "None", 0.33, "DPM++ 2M SDE", 512, 512, "digiplay/majicMIX_realistic_v7", "openpose ControlNet", "image.webp", # img conttol 1024, # img resolution 0.35, # strength 1.0, # cn scale 0.0, # cn start 0.9, # cn end "Classic-original", "Latent (antialiased)", 46, False, ],]
RESOURCES = ( """### Resources - John6666's space has some great features you might find helpful [link](https://huggingface.co/spaces/John6666/DiffuseCraftMod). - 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). """)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130import spacesimport gradio as grfrom stablepy import Preprocessor
PREPROCESSOR_TASKS_LIST = [ "Canny", "Openpose", "DPT", "Midas", "ZoeDepth", "DepthAnything", "HED", "PidiNet", "TEED", "Lineart", "LineartAnime", "Anyline", "Lineart standard", "SegFormer", "UPerNet", "ContentShuffle", "Recolor", "Blur", "MLSD", "NormalBae",]
preprocessor = Preprocessor()
def process_inputs( image, name, resolution, precessor_resolution, low_threshold, high_threshold, value_threshod, distance_threshold, recolor_mode, recolor_gamma_correction, blur_k_size, pre_openpose_extra, hed_scribble, pre_pidinet_safe, pre_lineart_coarse, use_cuda,): if not image: raise ValueError("To use this, simply upload an image.")
preprocessor.load(name, False)
params = dict( image_resolution=resolution, detect_resolution=precessor_resolution, low_threshold=low_threshold, high_threshold=high_threshold, thr_v=value_threshod, thr_d=distance_threshold, mode=recolor_mode, gamma_correction=recolor_gamma_correction, blur_sigma=blur_k_size, hand_and_face=pre_openpose_extra, scribble=hed_scribble, safe=pre_pidinet_safe, coarse=pre_lineart_coarse, )
if use_cuda: @spaces.GPU(duration=15) def wrapped_func(): preprocessor.to("cuda") return preprocessor(image, **params) return wrapped_func()
return preprocessor(image, **params)
def preprocessor_tab(): with gr.Row(): with gr.Column(): pre_image = gr.Image(label="Image", type="pil", sources=["upload"]) pre_options = gr.Dropdown(label="Preprocessor", choices=PREPROCESSOR_TASKS_LIST, value=PREPROCESSOR_TASKS_LIST[0]) pre_img_resolution = gr.Slider( minimum=64, maximum=4096, step=64, value=1024, label="Image Resolution", info="The maximum proportional size of the generated image based on the uploaded image." ) pre_start = gr.Button(value="PROCESS IMAGE", variant="primary") with gr.Accordion("Advanced Settings", open=False): with gr.Column(): pre_processor_resolution = gr.Slider(minimum=64, maximum=2048, step=64, value=512, label="Preprocessor Resolution") pre_low_threshold = gr.Slider(minimum=1, maximum=255, step=1, value=100, label="'CANNY' low threshold") pre_high_threshold = gr.Slider(minimum=1, maximum=255, step=1, value=200, label="'CANNY' high threshold") pre_value_threshold = gr.Slider(minimum=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") pre_openpose_extra = gr.Checkbox(value=True, label="'OPENPOSE' face and hand") pre_hed_scribble = gr.Checkbox(value=False, label="'HED' scribble") pre_pidinet_safe = gr.Checkbox(value=False, label="'PIDINET' safe") pre_lineart_coarse = gr.Checkbox(value=False, label="'LINEART' coarse") pre_use_cuda = gr.Checkbox(value=False, label="Use CUDA")
with gr.Column(): pre_result = gr.Image(label="Result", type="pil", interactive=False, format="png")
pre_start.click( fn=process_inputs, inputs=[ pre_image, pre_options, pre_img_resolution, pre_processor_resolution, pre_low_threshold, pre_high_threshold, pre_value_threshold, pre_distance_threshold, pre_recolor_mode, pre_recolor_gamma_correction, pre_blur_k_size, pre_openpose_extra, pre_hed_scribble, pre_pidinet_safe, pre_lineart_coarse, pre_use_cuda, ], outputs=[pre_result], )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290import spacesimport jsonimport gradio as grfrom huggingface_hub import HfApiimport osfrom pathlib import Pathfrom PIL import Image
from env import (HF_LORA_PRIVATE_REPOS1, HF_LORA_PRIVATE_REPOS2, HF_MODEL_USER_EX, HF_MODEL_USER_LIKES, DIFFUSERS_FORMAT_LORAS, directory_loras, hf_read_token, HF_TOKEN, CIVITAI_API_KEY)
MODEL_TYPE_DICT = { "diffusers:StableDiffusionPipeline": "SD 1.5", "diffusers:StableDiffusionXLPipeline": "SDXL", "diffusers:FluxPipeline": "FLUX",}
def get_user_agent(): return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'
def to_list(s): return [x.strip() for x in s.split(",") if not s == ""]
def list_uniq(l): return sorted(set(l), key=l.index)
def list_sub(a, b): return [e for e in a if e not in b]
def is_repo_name(s): import re return re.fullmatch(r'^[^/]+?/[^/]+?$', s)
from translatepy import Translatortranslator = Translator()def translate_to_en(input: str): try: output = str(translator.translate(input, 'English')) except Exception as e: output = input print(e) return output
def get_local_model_list(dir_path): model_list = [] valid_extensions = ('.ckpt', '.pt', '.pth', '.safetensors', '.bin') for file in Path(dir_path).glob("*"): if file.suffix in valid_extensions: file_path = str(Path(f"{dir_path}/{file.name}")) model_list.append(file_path) return model_list
def download_things(directory, url, hf_token="", civitai_api_key=""): url = url.strip() if "drive.google.com" in url: original_dir = os.getcwd() os.chdir(directory) os.system(f"gdown --fuzzy {url}") os.chdir(original_dir) elif "huggingface.co" in url: url = url.replace("?download=true", "") # url = urllib.parse.quote(url, safe=':/') # fix encoding if "/blob/" in url: url = url.replace("/blob/", "/resolve/") user_header = f'"Authorization: Bearer {hf_token}"' 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 {url.split('/')[-1]}") 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 {url.split('/')[-1]}") elif "civitai.com" in url: if "?" in url: url = url.split("?")[0] if civitai_api_key: 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: print("\033[91mYou need an API key to download Civitai models.\033[0m") else: os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
def escape_lora_basename(basename: str): return basename.replace(".", "_").replace(" ", "_").replace(",", "")
def to_lora_key(path: str): return escape_lora_basename(Path(path).stem)
def to_lora_path(key: str): if Path(key).is_file(): return key path = Path(f"{directory_loras}/{escape_lora_basename(key)}.safetensors") return str(path)
def safe_float(input): output = 1.0 try: output = float(input) except Exception: output = 1.0 return output
def save_images(images: list[Image.Image], metadatas: list[str]): from PIL import PngImagePlugin import uuid try: output_images = [] for image, metadata in zip(images, metadatas): info = PngImagePlugin.PngInfo() info.add_text("parameters", metadata) savefile = f"{str(uuid.uuid4())}.png" image.save(savefile, "PNG", pnginfo=info) output_images.append(str(Path(savefile).resolve())) return output_images except Exception as e: print(f"Failed to save image file: {e}") raise Exception(f"Failed to save image file:") from e
def save_gallery_images(images, progress=gr.Progress(track_tqdm=True)): from datetime import datetime, timezone, timedelta progress(0, desc="Updating gallery...") dt_now = datetime.now(timezone(timedelta(hours=9))) basename = dt_now.strftime('%Y%m%d_%H%M%S_') i = 1 if not images: return images, gr.update(visible=False) output_images = [] output_paths = [] for image in images: filename = basename + str(i) + ".png" i += 1 oldpath = Path(image[0]) newpath = oldpath try: if oldpath.exists(): newpath = oldpath.resolve().rename(Path(filename).resolve()) except Exception as e: print(e) finally: output_paths.append(str(newpath)) output_images.append((str(newpath), str(filename))) progress(1, desc="Gallery updated.") return gr.update(value=output_images), gr.update(value=output_paths, visible=True)
def download_private_repo(repo_id, dir_path, is_replace): from huggingface_hub import snapshot_download if not hf_read_token: return try: snapshot_download(repo_id=repo_id, local_dir=dir_path, allow_patterns=['*.ckpt', '*.pt', '*.pth', '*.safetensors', '*.bin'], use_auth_token=hf_read_token) except Exception as e: print(f"Error: Failed to download {repo_id}.") print(e) return if is_replace: for file in Path(dir_path).glob("*"): if file.exists() and "." in file.stem or " " in file.stem and file.suffix in ['.ckpt', '.pt', '.pth', '.safetensors', '.bin']: newpath = Path(f'{file.parent.name}/{escape_lora_basename(file.stem)}{file.suffix}') file.resolve().rename(newpath.resolve())
private_model_path_repo_dict = {} # {"local filepath": "huggingface repo_id", ...}
def get_private_model_list(repo_id, dir_path): global private_model_path_repo_dict api = HfApi() if not hf_read_token: return [] try: files = api.list_repo_files(repo_id, token=hf_read_token) except Exception as e: print(f"Error: Failed to list {repo_id}.") print(e) return [] model_list = [] for file in files: path = Path(f"{dir_path}/{file}") if path.suffix in ['.ckpt', '.pt', '.pth', '.safetensors', '.bin']: model_list.append(str(path)) for model in model_list: private_model_path_repo_dict[model] = repo_id return model_list
def download_private_file(repo_id, path, is_replace): from huggingface_hub import hf_hub_download file = Path(path) newpath = Path(f'{file.parent.name}/{escape_lora_basename(file.stem)}{file.suffix}') if is_replace else file if not hf_read_token or newpath.exists(): return filename = file.name dirname = file.parent.name try: hf_hub_download(repo_id=repo_id, filename=filename, local_dir=dirname, use_auth_token=hf_read_token) except Exception as e: print(f"Error: Failed to download {filename}.") print(e) return if is_replace: file.resolve().rename(newpath.resolve())
def download_private_file_from_somewhere(path, is_replace): if not path in private_model_path_repo_dict.keys(): return repo_id = private_model_path_repo_dict.get(path, None) download_private_file(repo_id, path, is_replace)
model_id_list = []def get_model_id_list(): global model_id_list if len(model_id_list) != 0: return model_id_list api = HfApi() model_ids = [] try: models_likes = [] for author in HF_MODEL_USER_LIKES: models_likes.extend(api.list_models(author=author, task="text-to-image", cardData=True, sort="likes")) models_ex = [] for author in HF_MODEL_USER_EX: models_ex = api.list_models(author=author, task="text-to-image", cardData=True, sort="last_modified") except Exception as e: print(f"Error: Failed to list {author}'s models.") print(e) return model_ids for model in models_likes: model_ids.append(model.id) if not model.private else "" anime_models = [] real_models = [] anime_models_flux = [] real_models_flux = [] for model in models_ex: if not model.private and not model.gated: if "diffusers:FluxPipeline" in model.tags: anime_models_flux.append(model.id) if "anime" in model.tags else real_models_flux.append(model.id) else: anime_models.append(model.id) if "anime" in model.tags else real_models.append(model.id) model_ids.extend(anime_models) model_ids.extend(real_models) model_ids.extend(anime_models_flux) model_ids.extend(real_models_flux) model_id_list = model_ids.copy() return model_ids
model_id_list = get_model_id_list()
def get_t2i_model_info(repo_id: str): api = HfApi(token=HF_TOKEN) try: if not is_repo_name(repo_id): return "" model = api.model_info(repo_id=repo_id, timeout=5.0) except Exception as e: print(f"Error: Failed to get {repo_id}'s info.") print(e) return "" if model.private or model.gated: return "" tags = model.tags info = [] url = f"https://huggingface.co/{repo_id}/" if not 'diffusers' in tags: return "" for k, v in MODEL_TYPE_DICT.items(): if k in tags: info.append(v) if model.card_data and model.card_data.tags: info.extend(list_sub(model.card_data.tags, ['text-to-image', 'stable-diffusion', 'stable-diffusion-api', 'safetensors', 'stable-diffusion-xl'])) info.append(f"DLs: {model.downloads}") info.append(f"likes: {model.likes}") info.append(model.last_modified.strftime("lastmod: %Y-%m-%d")) md = f"Model Info: {', '.join(info)}, [Model Repo]({url})" return gr.update(value=md)
def get_tupled_model_list(model_list): if not model_list: return [] tupled_list = [] for repo_id in model_list: api = HfApi() try: if not api.repo_exists(repo_id): continue model = api.model_info(repo_id=repo_id) except Exception as e: print(e) continue if model.private or model.gated: continue tags = model.tags info = [] if not 'diffusers' in tags: continue for k, v in MODEL_TYPE_DICT.items(): if k in tags: info.append(v) if model.card_data and model.card_data.tags: info.extend(list_sub(model.card_data.tags, ['text-to-image', 'stable-diffusion', 'stable-diffusion-api', 'safetensors', 'stable-diffusion-xl'])) if "pony" in info: info.remove("pony") name = f"{repo_id} (Pony🐴, {', '.join(info)})" else: name = f"{repo_id} ({', '.join(info)})" tupled_list.append((name, repo_id)) return tupled_list
private_lora_dict = {}try: with open('lora_dict.json', encoding='utf-8') as f: d = json.load(f) for k, v in d.items(): private_lora_dict[escape_lora_basename(k)] = vexcept Exception as e: print(e)loras_dict = {"None": ["", "", "", "", ""], "": ["", "", "", "", ""]} | private_lora_dict.copy()civitai_not_exists_list = []loras_url_to_path_dict = {} # {"URL to download": "local filepath", ...}civitai_lora_last_results = {} # {"URL to download": {search results}, ...}all_lora_list = []
private_lora_model_list = []def get_private_lora_model_lists(): global private_lora_model_list if len(private_lora_model_list) != 0: return private_lora_model_list models1 = [] models2 = [] for repo in HF_LORA_PRIVATE_REPOS1: models1.extend(get_private_model_list(repo, directory_loras)) for repo in HF_LORA_PRIVATE_REPOS2: models2.extend(get_private_model_list(repo, directory_loras)) models = list_uniq(models1 + sorted(models2)) private_lora_model_list = models.copy() return models
private_lora_model_list = get_private_lora_model_lists()
def get_civitai_info(path): global civitai_not_exists_list import requests from urllib3.util import Retry from requests.adapters import HTTPAdapter if path in set(civitai_not_exists_list): return ["", "", "", "", ""] if not Path(path).exists(): return None user_agent = get_user_agent() headers = {'User-Agent': user_agent, 'content-type': 'application/json'} base_url = 'https://civitai.com/api/v1/model-versions/by-hash/' params = {} session = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504]) session.mount("https://", HTTPAdapter(max_retries=retries)) import hashlib with open(path, 'rb') as file: file_data = file.read() hash_sha256 = hashlib.sha256(file_data).hexdigest() url = base_url + hash_sha256 try: r = session.get(url, params=params, headers=headers, stream=True, timeout=(3.0, 15)) except Exception as e: print(e) return ["", "", "", "", ""] if not r.ok: return None json = r.json() if not 'baseModel' in json: civitai_not_exists_list.append(path) return ["", "", "", "", ""] items = [] items.append(" / ".join(json['trainedWords'])) items.append(json['baseModel']) items.append(json['model']['name']) items.append(f"https://civitai.com/models/{json['modelId']}") items.append(json['images'][0]['url']) return items
def get_lora_model_list(): loras = list_uniq(get_private_lora_model_lists() + get_local_model_list(directory_loras) + DIFFUSERS_FORMAT_LORAS) loras.insert(0, "None") loras.insert(0, "") return loras
def get_all_lora_list(): global all_lora_list loras = get_lora_model_list() all_lora_list = loras.copy() return loras
def get_all_lora_tupled_list(): global loras_dict models = get_all_lora_list() if not models: return [] tupled_list = [] for model in models: #if not model: continue # to avoid GUI-related bug basename = Path(model).stem key = to_lora_key(model) items = None if key in loras_dict.keys(): items = loras_dict.get(key, None) else: items = get_civitai_info(model) if items != None: loras_dict[key] = items name = basename value = model if items and items[2] != "": if items[1] == "Pony": name = f"{basename} (for {items[1]}🐴, {items[2]})" else: name = f"{basename} (for {items[1]}, {items[2]})" tupled_list.append((name, value)) return tupled_list
def update_lora_dict(path): global loras_dict key = escape_lora_basename(Path(path).stem) if key in loras_dict.keys(): return items = get_civitai_info(path) if items == None: return loras_dict[key] = items
def download_lora(dl_urls: str): global loras_url_to_path_dict dl_path = "" before = get_local_model_list(directory_loras) urls = [] for url in [url.strip() for url in dl_urls.split(',')]: local_path = f"{directory_loras}/{url.split('/')[-1]}" if not Path(local_path).exists(): download_things(directory_loras, url, HF_TOKEN, CIVITAI_API_KEY) urls.append(url) after = get_local_model_list(directory_loras) new_files = list_sub(after, before) i = 0 for file in new_files: path = Path(file) if path.exists(): new_path = Path(f'{path.parent.name}/{escape_lora_basename(path.stem)}{path.suffix}') path.resolve().rename(new_path.resolve()) loras_url_to_path_dict[urls[i]] = str(new_path) update_lora_dict(str(new_path)) dl_path = str(new_path) i += 1 return dl_path
def copy_lora(path: str, new_path: str): import shutil if path == new_path: return new_path cpath = Path(path) npath = Path(new_path) if cpath.exists(): try: shutil.copy(str(cpath.resolve()), str(npath.resolve())) except Exception as e: print(e) return None update_lora_dict(str(npath)) return new_path else: return None
def download_my_lora(dl_urls: str, lora1: str, lora2: str, lora3: str, lora4: str, lora5: str): path = download_lora(dl_urls) if path: if not lora1 or lora1 == "None": lora1 = path elif not lora2 or lora2 == "None": lora2 = path elif not lora3 or lora3 == "None": lora3 = path elif not lora4 or lora4 == "None": lora4 = path elif not lora5 or lora5 == "None": lora5 = path choices = get_all_lora_tupled_list() return gr.update(value=lora1, choices=choices), gr.update(value=lora2, choices=choices), gr.update(value=lora3, choices=choices),\ gr.update(value=lora4, choices=choices), gr.update(value=lora5, choices=choices)
def get_valid_lora_name(query: str, model_name: str): path = "None" if not query or query == "None": return "None" if to_lora_key(query) in loras_dict.keys(): return query if query in loras_url_to_path_dict.keys(): path = loras_url_to_path_dict[query] else: path = to_lora_path(query.strip().split('/')[-1]) if Path(path).exists(): return path elif "http" in query: dl_file = download_lora(query) if dl_file and Path(dl_file).exists(): return dl_file else: dl_file = find_similar_lora(query, model_name) if dl_file and Path(dl_file).exists(): return dl_file return "None"
def get_valid_lora_path(query: str): path = None if not query or query == "None": return None if to_lora_key(query) in loras_dict.keys(): return query if Path(path).exists(): return path else: return None
def get_valid_lora_wt(prompt: str, lora_path: str, lora_wt: float): import re wt = lora_wt result = re.findall(f'<lora:{to_lora_key(lora_path)}:(.+?)>', prompt) if not result: return wt wt = safe_float(result[0][0]) return wt
def set_prompt_loras(prompt, prompt_syntax, model_name, lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt): import re if not "Classic" in str(prompt_syntax): return lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt lora1 = get_valid_lora_name(lora1, model_name) lora2 = get_valid_lora_name(lora2, model_name) lora3 = get_valid_lora_name(lora3, model_name) lora4 = get_valid_lora_name(lora4, model_name) lora5 = get_valid_lora_name(lora5, model_name) if not "<lora" in prompt: return lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt lora1_wt = get_valid_lora_wt(prompt, lora1, lora1_wt) lora2_wt = get_valid_lora_wt(prompt, lora2, lora2_wt) lora3_wt = get_valid_lora_wt(prompt, lora3, lora3_wt) lora4_wt = get_valid_lora_wt(prompt, lora4, lora4_wt) lora5_wt = get_valid_lora_wt(prompt, lora5, lora5_wt) on1, label1, tag1, md1 = get_lora_info(lora1) on2, label2, tag2, md2 = get_lora_info(lora2) on3, label3, tag3, md3 = get_lora_info(lora3) on4, label4, tag4, md4 = get_lora_info(lora4) on5, label5, tag5, md5 = get_lora_info(lora5) lora_paths = [lora1, lora2, lora3, lora4, lora5] prompts = prompt.split(",") if prompt else [] for p in prompts: p = str(p).strip() if "<lora" in p: result = re.findall(r'<lora:(.+?):(.+?)>', p) if not result: continue key = result[0][0] wt = result[0][1] path = to_lora_path(key) if not key in loras_dict.keys() or not path: path = get_valid_lora_name(path) if not path or path == "None": continue if path in lora_paths: continue elif not on1: lora1 = path lora_paths = [lora1, lora2, lora3, lora4, lora5] lora1_wt = safe_float(wt) on1 = True elif not on2: lora2 = path lora_paths = [lora1, lora2, lora3, lora4, lora5] lora2_wt = safe_float(wt) on2 = True elif not on3: lora3 = path lora_paths = [lora1, lora2, lora3, lora4, lora5] lora3_wt = safe_float(wt) on3 = True elif not on4: lora4 = path lora_paths = [lora1, lora2, lora3, lora4, lora5] lora4_wt = safe_float(wt) on4, label4, tag4, md4 = get_lora_info(lora4) elif not on5: lora5 = path lora_paths = [lora1, lora2, lora3, lora4, lora5] lora5_wt = safe_float(wt) on5 = True return lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt
def get_lora_info(lora_path: str): is_valid = False tag = "" label = "" md = "None" if not lora_path or lora_path == "None": print("LoRA file not found.") return is_valid, label, tag, md path = Path(lora_path) new_path = Path(f'{path.parent.name}/{escape_lora_basename(path.stem)}{path.suffix}') if not to_lora_key(str(new_path)) in loras_dict.keys() and str(path) not in set(get_all_lora_list()): print("LoRA file is not registered.") return tag, label, tag, md if not new_path.exists(): download_private_file_from_somewhere(str(path), True) basename = new_path.stem label = f'Name: {basename}' items = loras_dict.get(basename, None) if items == None: items = get_civitai_info(str(new_path)) if items != None: loras_dict[basename] = items if items and items[2] != "": tag = items[0] label = f'Name: {basename}' if items[1] == "Pony": label = f'Name: {basename} (for Pony🐴)' if items[4]: md = f'<img src="{items[4]}" alt="thumbnail" width="150" height="240"><br>[LoRA Model URL]({items[3]})' elif items[3]: md = f'[LoRA Model URL]({items[3]})' is_valid = True return is_valid, label, tag, md
def normalize_prompt_list(tags: list[str]): prompts = [] for tag in tags: tag = str(tag).strip() if tag: prompts.append(tag) return prompts
def apply_lora_prompt(prompt: str = "", lora_info: str = ""): if lora_info == "None": return gr.update(value=prompt) tags = prompt.split(",") if prompt else [] prompts = normalize_prompt_list(tags)
lora_tag = lora_info.replace("/",",") lora_tags = lora_tag.split(",") if str(lora_info) != "None" else [] lora_prompts = normalize_prompt_list(lora_tags) empty = [""] prompt = ", ".join(list_uniq(prompts + lora_prompts) + empty) return gr.update(value=prompt)
def update_loras(prompt, prompt_syntax, lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt): import re on1, label1, tag1, md1 = get_lora_info(lora1) on2, label2, tag2, md2 = get_lora_info(lora2) on3, label3, tag3, md3 = get_lora_info(lora3) on4, label4, tag4, md4 = get_lora_info(lora4) on5, label5, tag5, md5 = get_lora_info(lora5) lora_paths = [lora1, lora2, lora3, lora4, lora5]
output_prompt = prompt if "Classic" in str(prompt_syntax): prompts = prompt.split(",") if prompt else [] output_prompts = [] for p in prompts: p = str(p).strip() if "<lora" in p: result = re.findall(r'<lora:(.+?):(.+?)>', p) if not result: continue key = result[0][0] wt = result[0][1] path = to_lora_path(key) if not key in loras_dict.keys() or not path: continue if path in lora_paths: output_prompts.append(f"<lora:{to_lora_key(path)}:{safe_float(wt):.2f}>") elif p: output_prompts.append(p) lora_prompts = [] if on1: lora_prompts.append(f"<lora:{to_lora_key(lora1)}:{lora1_wt:.2f}>") if on2: lora_prompts.append(f"<lora:{to_lora_key(lora2)}:{lora2_wt:.2f}>") if on3: lora_prompts.append(f"<lora:{to_lora_key(lora3)}:{lora3_wt:.2f}>") if on4: lora_prompts.append(f"<lora:{to_lora_key(lora4)}:{lora4_wt:.2f}>") if on5: lora_prompts.append(f"<lora:{to_lora_key(lora5)}:{lora5_wt:.2f}>") output_prompt = ", ".join(list_uniq(output_prompts + lora_prompts + [""])) choices = get_all_lora_tupled_list()
return gr.update(value=output_prompt), gr.update(value=lora1, choices=choices), gr.update(value=lora1_wt),\ gr.update(value=tag1, label=label1, visible=on1), gr.update(visible=on1), gr.update(value=md1, visible=on1),\ gr.update(value=lora2, choices=choices), gr.update(value=lora2_wt),\ gr.update(value=tag2, label=label2, visible=on2), gr.update(visible=on2), gr.update(value=md2, visible=on2),\ gr.update(value=lora3, choices=choices), gr.update(value=lora3_wt),\ gr.update(value=tag3, label=label3, visible=on3), gr.update(visible=on3), gr.update(value=md3, visible=on3),\ gr.update(value=lora4, choices=choices), gr.update(value=lora4_wt),\ gr.update(value=tag4, label=label4, visible=on4), gr.update(visible=on4), gr.update(value=md4, visible=on4),\ gr.update(value=lora5, choices=choices), gr.update(value=lora5_wt),\ gr.update(value=tag5, label=label5, visible=on5), gr.update(visible=on5), gr.update(value=md5, visible=on5)
def get_my_lora(link_url): from pathlib import Path before = get_local_model_list(directory_loras) for url in [url.strip() for url in link_url.split(',')]: if not Path(f"{directory_loras}/{url.split('/')[-1]}").exists(): download_things(directory_loras, url, HF_TOKEN, CIVITAI_API_KEY) after = get_local_model_list(directory_loras) new_files = list_sub(after, before) for file in new_files: path = Path(file) if path.exists(): new_path = Path(f'{path.parent.name}/{escape_lora_basename(path.stem)}{path.suffix}') path.resolve().rename(new_path.resolve()) update_lora_dict(str(new_path)) new_lora_model_list = get_lora_model_list() new_lora_tupled_list = get_all_lora_tupled_list() return gr.update( choices=new_lora_tupled_list, value=new_lora_model_list[-1] ), gr.update( choices=new_lora_tupled_list ), gr.update( choices=new_lora_tupled_list ), gr.update( choices=new_lora_tupled_list ), gr.update( choices=new_lora_tupled_list )
def upload_file_lora(files, progress=gr.Progress(track_tqdm=True)): progress(0, desc="Uploading...") file_paths = [file.name for file in files] progress(1, desc="Uploaded.") return gr.update(value=file_paths, visible=True), gr.update(visible=True)
def move_file_lora(filepaths): import shutil for file in filepaths: path = Path(shutil.move(Path(file).resolve(), Path(f"./{directory_loras}").resolve())) newpath = Path(f'{path.parent.name}/{escape_lora_basename(path.stem)}{path.suffix}') path.resolve().rename(newpath.resolve()) update_lora_dict(str(newpath))
new_lora_model_list = get_lora_model_list() new_lora_tupled_list = get_all_lora_tupled_list() return gr.update( choices=new_lora_tupled_list, value=new_lora_model_list[-1] ), gr.update( choices=new_lora_tupled_list ), gr.update( choices=new_lora_tupled_list ), gr.update( choices=new_lora_tupled_list ), gr.update( choices=new_lora_tupled_list )
def get_civitai_info(path): global civitai_not_exists_list, loras_url_to_path_dict import requests from requests.adapters import HTTPAdapter from urllib3.util import Retry default = ["", "", "", "", ""] if path in set(civitai_not_exists_list): return default if not Path(path).exists(): return None user_agent = get_user_agent() headers = {'User-Agent': user_agent, 'content-type': 'application/json'} base_url = 'https://civitai.com/api/v1/model-versions/by-hash/' params = {} session = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504]) session.mount("https://", HTTPAdapter(max_retries=retries)) import hashlib with open(path, 'rb') as file: file_data = file.read() hash_sha256 = hashlib.sha256(file_data).hexdigest() url = base_url + hash_sha256 try: r = session.get(url, params=params, headers=headers, stream=True, timeout=(3.0, 15)) except Exception as e: print(e) return default else: if not r.ok: return None json = r.json() if 'baseModel' not in json: civitai_not_exists_list.append(path) return default items = [] items.append(" / ".join(json['trainedWords'])) # The words (prompts) used to trigger the model items.append(json['baseModel']) # Base model (SDXL1.0, Pony, ...) items.append(json['model']['name']) # The name of the model version items.append(f"https://civitai.com/models/{json['modelId']}") # The repo url for the model items.append(json['images'][0]['url']) # The url for a sample image loras_url_to_path_dict[path] = json['downloadUrl'] # The download url to get the model file for this specific version return items
def search_lora_on_civitai(query: str, allow_model: list[str] = ["Pony", "SDXL 1.0"], limit: int = 100, sort: str = "Highest Rated", period: str = "AllTime", tag: str = ""): import requests from requests.adapters import HTTPAdapter from urllib3.util import Retry user_agent = get_user_agent() headers = {'User-Agent': user_agent, 'content-type': 'application/json'} base_url = 'https://civitai.com/api/v1/models' params = {'types': ['LORA'], 'sort': sort, 'period': period, 'limit': limit, 'nsfw': 'true'} if query: params["query"] = query if tag: params["tag"] = tag session = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504]) session.mount("https://", HTTPAdapter(max_retries=retries)) try: r = session.get(base_url, params=params, headers=headers, stream=True, timeout=(3.0, 30)) except Exception as e: print(e) return None else: if not r.ok: return None json = r.json() if 'items' not in json: return None items = [] for j in json['items']: for model in j['modelVersions']: item = {} if model['baseModel'] not in set(allow_model): continue item['name'] = j['name'] item['creator'] = j['creator']['username'] item['tags'] = j['tags'] item['model_name'] = model['name'] item['base_model'] = model['baseModel'] item['dl_url'] = model['downloadUrl'] item['md'] = f'<img src="{model["images"][0]["url"]}" alt="thumbnail" width="150" height="240"><br>[LoRA Model URL](https://civitai.com/models/{j["id"]})' items.append(item) return items
def search_civitai_lora(query, base_model, sort="Highest Rated", period="AllTime", tag=""): global civitai_lora_last_results items = search_lora_on_civitai(query, base_model, 100, sort, period, tag) if not items: return gr.update(choices=[("", "")], value="", visible=False),\ gr.update(value="", visible=False), gr.update(visible=True), gr.update(visible=True) civitai_lora_last_results = {} choices = [] for item in items: base_model_name = "Pony🐴" if item['base_model'] == "Pony" else item['base_model'] name = f"{item['name']} (for {base_model_name} / By: {item['creator']} / Tags: {', '.join(item['tags'])})" value = item['dl_url'] choices.append((name, value)) civitai_lora_last_results[value] = item if not choices: return gr.update(choices=[("", "")], value="", visible=False),\ gr.update(value="", visible=False), gr.update(visible=True), gr.update(visible=True) result = civitai_lora_last_results.get(choices[0][1], "None") md = result['md'] if result else "" return gr.update(choices=choices, value=choices[0][1], visible=True), gr.update(value=md, visible=True),\ gr.update(visible=True), gr.update(visible=True)
def select_civitai_lora(search_result): if not "http" in search_result: return gr.update(value=""), gr.update(value="None", visible=True) result = civitai_lora_last_results.get(search_result, "None") md = result['md'] if result else "" return gr.update(value=search_result), gr.update(value=md, visible=True)
LORA_BASE_MODEL_DICT = { "diffusers:StableDiffusionPipeline": ["SD 1.5"], "diffusers:StableDiffusionXLPipeline": ["Pony", "SDXL 1.0"], "diffusers:FluxPipeline": ["Flux.1 D", "Flux.1 S"],}
def get_lora_base_model(model_name: str): api = HfApi(token=HF_TOKEN) default = ["Pony", "SDXL 1.0"] try: model = api.model_info(repo_id=model_name, timeout=5.0) tags = model.tags for tag in tags: if tag in LORA_BASE_MODEL_DICT.keys(): return LORA_BASE_MODEL_DICT.get(tag, default) except Exception: return default return default
def find_similar_lora(q: str, model_name: str): from rapidfuzz.process import extractOne from rapidfuzz.utils import default_process query = to_lora_key(q) print(f"Finding <lora:{query}:...>...") keys = list(private_lora_dict.keys()) values = [x[2] for x in list(private_lora_dict.values())] s = default_process(query) e1 = extractOne(s, keys + values, processor=default_process, score_cutoff=80.0) key = "" if e1: e = e1[0] if e in set(keys): key = e elif e in set(values): key = keys[values.index(e)] if key: path = to_lora_path(key) new_path = to_lora_path(query) if not Path(path).exists(): if not Path(new_path).exists(): download_private_file_from_somewhere(path, True) if Path(path).exists() and copy_lora(path, new_path): return new_path print(f"Finding <lora:{query}:...> on Civitai...") civitai_query = Path(query).stem if Path(query).is_file() else query civitai_query = civitai_query.replace("_", " ").replace("-", " ") base_model = get_lora_base_model(model_name) items = search_lora_on_civitai(civitai_query, base_model, 1) if items: item = items[0] path = download_lora(item['dl_url']) new_path = query if Path(query).is_file() else to_lora_path(query) if path and copy_lora(path, new_path): return new_path return None
def change_interface_mode(mode: str): if mode == "Fast": return gr.update(open=False), gr.update(visible=True), gr.update(open=False), gr.update(open=False),\ gr.update(visible=True), gr.update(open=False), gr.update(visible=True), gr.update(open=False),\ gr.update(visible=True), gr.update(value="Fast") elif mode == "Simple": # t2i mode return gr.update(open=True), gr.update(visible=True), gr.update(open=False), gr.update(open=False),\ gr.update(visible=True), gr.update(open=False), gr.update(visible=False), gr.update(open=True),\ gr.update(visible=False), gr.update(value="Standard") elif mode == "LoRA": # t2i LoRA mode return gr.update(open=True), gr.update(visible=True), gr.update(open=True), gr.update(open=False),\ gr.update(visible=True), gr.update(open=True), gr.update(visible=True), gr.update(open=False),\ gr.update(visible=False), gr.update(value="Standard") else: # Standard return gr.update(open=False), gr.update(visible=True), gr.update(open=False), gr.update(open=False),\ gr.update(visible=True), gr.update(open=False), gr.update(visible=True), gr.update(open=False),\ gr.update(visible=True), gr.update(value="Standard")
quality_prompt_list = [ { "name": "None", "prompt": "", "negative_prompt": "lowres", }, { "name": "Animagine Common", "prompt": "anime artwork, anime style, vibrant, studio anime, highly detailed, masterpiece, best quality, very aesthetic, absurdres", "negative_prompt": "lowres, (bad), text, error, fewer, extra, missing, worst quality, jpeg artifacts, low quality, watermark, unfinished, displeasing, oldest, early, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]", }, { "name": "Pony Anime Common", "prompt": "source_anime, score_9, score_8_up, score_7_up, masterpiece, best quality, very aesthetic, absurdres", "negative_prompt": "source_pony, source_furry, source_cartoon, score_6, score_5, score_4, busty, ugly face, mutated hands, low res, blurry face, black and white, the simpsons, overwatch, apex legends", }, { "name": "Pony Common", "prompt": "source_anime, score_9, score_8_up, score_7_up", "negative_prompt": "source_pony, source_furry, source_cartoon, score_6, score_5, score_4, busty, ugly face, mutated hands, low res, blurry face, black and white, the simpsons, overwatch, apex legends", }, { "name": "Animagine Standard v3.0", "prompt": "masterpiece, best quality", "negative_prompt": "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, artist name", }, { "name": "Animagine Standard v3.1", "prompt": "masterpiece, best quality, very aesthetic, absurdres", "negative_prompt": "lowres, (bad), text, error, fewer, extra, missing, worst quality, jpeg artifacts, low quality, watermark, unfinished, displeasing, oldest, early, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]", }, { "name": "Animagine Light v3.1", "prompt": "(masterpiece), best quality, very aesthetic, perfect face", "negative_prompt": "(low quality, worst quality:1.2), very displeasing, 3d, watermark, signature, ugly, poorly drawn", }, { "name": "Animagine Heavy v3.1", "prompt": "(masterpiece), (best quality), (ultra-detailed), very aesthetic, illustration, disheveled hair, perfect composition, moist skin, intricate details", "negative_prompt": "longbody, lowres, bad anatomy, bad hands, missing fingers, pubic hair, extra digit, fewer digits, cropped, worst quality, low quality, very displeasing", },]
style_list = [ { "name": "None", "prompt": "", "negative_prompt": "", }, { "name": "Cinematic", "prompt": "cinematic still, emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy", "negative_prompt": "cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured", }, { "name": "Photographic", "prompt": "cinematic photo, 35mm photograph, film, bokeh, professional, 4k, highly detailed", "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly", }, { "name": "Anime", "prompt": "anime artwork, anime style, vibrant, studio anime, highly detailed", "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast", }, { "name": "Manga", "prompt": "manga style, vibrant, high-energy, detailed, iconic, Japanese comic style", "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, Western comic style", }, { "name": "Digital Art", "prompt": "concept art, digital artwork, illustrative, painterly, matte painting, highly detailed", "negative_prompt": "photo, photorealistic, realism, ugly", }, { "name": "Pixel art", "prompt": "pixel-art, low-res, blocky, pixel art style, 8-bit graphics", "negative_prompt": "sloppy, messy, blurry, noisy, highly detailed, ultra textured, photo, realistic", }, { "name": "Fantasy art", "prompt": "ethereal fantasy concept art, magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy", "negative_prompt": "photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white", }, { "name": "Neonpunk", "prompt": "neonpunk style, cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional", "negative_prompt": "painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured", }, { "name": "3D Model", "prompt": "professional 3d model, octane render, highly detailed, volumetric, dramatic lighting", "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting", },]
optimization_list = { "None": [28, 7., 'Euler a', False, 'None', 1.], "Default": [28, 7., 'Euler a', False, 'None', 1.], "SPO": [28, 7., 'Euler a', True, 'loras/spo_sdxl_10ep_4k-data_lora_diffusers.safetensors', 1.], "DPO": [28, 7., 'Euler a', True, 'loras/sdxl-DPO-LoRA.safetensors', 1.], "DPO Turbo": [8, 2.5, 'LCM', True, 'loras/sd_xl_dpo_turbo_lora_v1-128dim.safetensors', 1.], "SDXL Turbo": [8, 2.5, 'LCM', True, 'loras/sd_xl_turbo_lora_v1.safetensors', 1.], "Hyper-SDXL 12step": [12, 5., 'TCD', True, 'loras/Hyper-SDXL-12steps-CFG-lora.safetensors', 1.], "Hyper-SDXL 8step": [8, 5., 'TCD', True, 'loras/Hyper-SDXL-8steps-CFG-lora.safetensors', 1.], "Hyper-SDXL 4step": [4, 0, 'TCD', True, 'loras/Hyper-SDXL-4steps-lora.safetensors', 1.], "Hyper-SDXL 2step": [2, 0, 'TCD', True, 'loras/Hyper-SDXL-2steps-lora.safetensors', 1.], "Hyper-SDXL 1step": [1, 0, 'TCD', True, 'loras/Hyper-SDXL-1steps-lora.safetensors', 1.], "PCM 16step": [16, 4., 'Euler a trailing', True, 'loras/pcm_sdxl_normalcfg_16step_converted.safetensors', 1.], "PCM 8step": [8, 4., 'Euler a trailing', True, 'loras/pcm_sdxl_normalcfg_8step_converted.safetensors', 1.], "PCM 4step": [4, 2., 'Euler a trailing', True, 'loras/pcm_sdxl_smallcfg_4step_converted.safetensors', 1.], "PCM 2step": [2, 1., 'Euler a trailing', True, 'loras/pcm_sdxl_smallcfg_2step_converted.safetensors', 1.],}
def set_optimization(opt, steps_gui, cfg_gui, sampler_gui, clip_skip_gui, lora_gui, lora_scale_gui): if not opt in list(optimization_list.keys()): opt = "None" def_steps_gui = 28 def_cfg_gui = 7. steps = optimization_list.get(opt, "None")[0] cfg = optimization_list.get(opt, "None")[1] sampler = optimization_list.get(opt, "None")[2] clip_skip = optimization_list.get(opt, "None")[3] lora = optimization_list.get(opt, "None")[4] lora_scale = optimization_list.get(opt, "None")[5] if opt == "None": steps = max(steps_gui, def_steps_gui) cfg = max(cfg_gui, def_cfg_gui) clip_skip = clip_skip_gui elif opt == "SPO" or opt == "DPO": steps = max(steps_gui, def_steps_gui) cfg = max(cfg_gui, def_cfg_gui)
return gr.update(value=steps), gr.update(value=cfg), gr.update(value=sampler),\ gr.update(value=clip_skip), gr.update(value=lora), gr.update(value=lora_scale),
# [sampler_gui, steps_gui, cfg_gui, clip_skip_gui, img_width_gui, img_height_gui, optimization_gui]preset_sampler_setting = { "None": ["Euler a", 28, 7., True, 1024, 1024, "None"], "Anime 3:4 Fast": ["LCM", 8, 2.5, True, 896, 1152, "DPO Turbo"], "Anime 3:4 Standard": ["Euler a", 28, 7., True, 896, 1152, "None"], "Anime 3:4 Heavy": ["Euler a", 40, 7., True, 896, 1152, "None"], "Anime 1:1 Fast": ["LCM", 8, 2.5, True, 1024, 1024, "DPO Turbo"], "Anime 1:1 Standard": ["Euler a", 28, 7., True, 1024, 1024, "None"], "Anime 1:1 Heavy": ["Euler a", 40, 7., True, 1024, 1024, "None"], "Photo 3:4 Fast": ["LCM", 8, 2.5, False, 896, 1152, "DPO Turbo"], "Photo 3:4 Standard": ["DPM++ 2M Karras", 28, 7., False, 896, 1152, "None"], "Photo 3:4 Heavy": ["DPM++ 2M Karras", 40, 7., False, 896, 1152, "None"], "Photo 1:1 Fast": ["LCM", 8, 2.5, False, 1024, 1024, "DPO Turbo"], "Photo 1:1 Standard": ["DPM++ 2M Karras", 28, 7., False, 1024, 1024, "None"], "Photo 1:1 Heavy": ["DPM++ 2M Karras", 40, 7., False, 1024, 1024, "None"],}
def set_sampler_settings(sampler_setting): if not sampler_setting in list(preset_sampler_setting.keys()) or sampler_setting == "None": return gr.update(value="Euler a"), gr.update(value=28), gr.update(value=7.), gr.update(value=True),\ gr.update(value=1024), gr.update(value=1024), gr.update(value="None") v = preset_sampler_setting.get(sampler_setting, ["Euler a", 28, 7., True, 1024, 1024]) # sampler, steps, cfg, clip_skip, width, height, optimization return gr.update(value=v[0]), gr.update(value=v[1]), gr.update(value=v[2]), gr.update(value=v[3]),\ gr.update(value=v[4]), gr.update(value=v[5]), gr.update(value=v[6])
preset_styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}preset_quality = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in quality_prompt_list}
def process_style_prompt(prompt: str, neg_prompt: str, styles_key: str = "None", quality_key: str = "None", type: str = "Auto"): def to_list(s): return [x.strip() for x in s.split(",") if not s == ""] def list_sub(a, b): return [e for e in a if e not in b] def list_uniq(l): return sorted(set(l), key=l.index)
animagine_ps = to_list("anime artwork, anime style, vibrant, studio anime, highly detailed, masterpiece, best quality, very aesthetic, absurdres") animagine_nps = to_list("lowres, (bad), text, error, fewer, extra, missing, worst quality, jpeg artifacts, low quality, watermark, unfinished, displeasing, oldest, early, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]") pony_ps = to_list("source_anime, score_9, score_8_up, score_7_up, masterpiece, best quality, very aesthetic, absurdres") pony_nps = to_list("source_pony, source_furry, source_cartoon, score_6, score_5, score_4, busty, ugly face, mutated hands, low res, blurry face, black and white, the simpsons, overwatch, apex legends") prompts = to_list(prompt) neg_prompts = to_list(neg_prompt)
all_styles_ps = [] all_styles_nps = [] for d in style_list: all_styles_ps.extend(to_list(str(d.get("prompt", "")))) all_styles_nps.extend(to_list(str(d.get("negative_prompt", ""))))
all_quality_ps = [] all_quality_nps = [] for d in quality_prompt_list: all_quality_ps.extend(to_list(str(d.get("prompt", "")))) all_quality_nps.extend(to_list(str(d.get("negative_prompt", ""))))
quality_ps = to_list(preset_quality[quality_key][0]) quality_nps = to_list(preset_quality[quality_key][1]) styles_ps = to_list(preset_styles[styles_key][0]) styles_nps = to_list(preset_styles[styles_key][1])
prompts = list_sub(prompts, animagine_ps + pony_ps + all_styles_ps + all_quality_ps) neg_prompts = list_sub(neg_prompts, animagine_nps + pony_nps + all_styles_nps + all_quality_nps)
last_empty_p = [""] if not prompts and type != "None" and type != "Auto" and styles_key != "None" and quality_key != "None" else [] last_empty_np = [""] if not neg_prompts and type != "None" and type != "Auto" and styles_key != "None" and quality_key != "None" else []
if type == "Animagine": prompts = prompts + animagine_ps neg_prompts = neg_prompts + animagine_nps elif type == "Pony": prompts = prompts + pony_ps neg_prompts = neg_prompts + pony_nps
prompts = prompts + styles_ps + quality_ps neg_prompts = neg_prompts + styles_nps + quality_nps
prompt = ", ".join(list_uniq(prompts) + last_empty_p) neg_prompt = ", ".join(list_uniq(neg_prompts) + last_empty_np)
return gr.update(value=prompt), gr.update(value=neg_prompt), gr.update(value=type)
def set_quick_presets(genre:str = "None", type:str = "Auto", speed:str = "None", aspect:str = "None"): quality = "None" style = "None" sampler = "None" opt = "None"
if genre == "Anime": if type != "None" and type != "Auto": style = "Anime" if aspect == "1:1": if speed == "Heavy": sampler = "Anime 1:1 Heavy" elif speed == "Fast": sampler = "Anime 1:1 Fast" else: sampler = "Anime 1:1 Standard" elif aspect == "3:4": if speed == "Heavy": sampler = "Anime 3:4 Heavy" elif speed == "Fast": sampler = "Anime 3:4 Fast" else: sampler = "Anime 3:4 Standard" if type == "Pony": quality = "Pony Anime Common" elif type == "Animagine": quality = "Animagine Common" else: quality = "None" elif genre == "Photo": if type != "None" and type != "Auto": style = "Photographic" if aspect == "1:1": if speed == "Heavy": sampler = "Photo 1:1 Heavy" elif speed == "Fast": sampler = "Photo 1:1 Fast" else: sampler = "Photo 1:1 Standard" elif aspect == "3:4": if speed == "Heavy": sampler = "Photo 3:4 Heavy" elif speed == "Fast": sampler = "Photo 3:4 Fast" else: sampler = "Photo 3:4 Standard" if type == "Pony": quality = "Pony Common" else: quality = "None"
if speed == "Fast": opt = "DPO Turbo" if genre == "Anime" and type != "Pony" and type != "Auto": quality = "Animagine Light v3.1"
return gr.update(value=quality), gr.update(value=style), gr.update(value=sampler), gr.update(value=opt), gr.update(value=type)
textual_inversion_dict = {}try: with open('textual_inversion_dict.json', encoding='utf-8') as f: textual_inversion_dict = json.load(f)except Exception: passtextual_inversion_file_token_list = []
def get_tupled_embed_list(embed_list): global textual_inversion_file_list tupled_list = [] for file in embed_list: token = textual_inversion_dict.get(Path(file).name, [Path(file).stem.replace(",",""), False])[0] tupled_list.append((token, file)) textual_inversion_file_token_list.append(token) return tupled_list
def set_textual_inversion_prompt(textual_inversion_gui, prompt_gui, neg_prompt_gui, prompt_syntax_gui): ti_tags = list(textual_inversion_dict.values()) + textual_inversion_file_token_list tags = prompt_gui.split(",") if prompt_gui else [] prompts = [] for tag in tags: tag = str(tag).strip() if tag and not tag in ti_tags: prompts.append(tag) ntags = neg_prompt_gui.split(",") if neg_prompt_gui else [] neg_prompts = [] for tag in ntags: tag = str(tag).strip() if tag and not tag in ti_tags: neg_prompts.append(tag) ti_prompts = [] ti_neg_prompts = [] for ti in textual_inversion_gui: tokens = textual_inversion_dict.get(Path(ti).name, [Path(ti).stem.replace(",",""), False]) is_positive = tokens[1] == True or "positive" in Path(ti).parent.name if is_positive: # positive prompt ti_prompts.append(tokens[0]) else: # negative prompt (default) ti_neg_prompts.append(tokens[0]) empty = [""] prompt = ", ".join(prompts + ti_prompts + empty) neg_prompt = ", ".join(neg_prompts + ti_neg_prompts + empty) return gr.update(value=prompt), gr.update(value=neg_prompt),
def get_model_pipeline(repo_id: str): from huggingface_hub import HfApi api = HfApi(token=HF_TOKEN) default = "StableDiffusionPipeline" try: if not is_repo_name(repo_id): return default model = api.model_info(repo_id=repo_id, timeout=5.0) except Exception: return default if model.private or model.gated: return default tags = model.tags if not 'diffusers' in tags: return default if 'diffusers:FluxPipeline' in tags: return "FluxPipeline" if 'diffusers:StableDiffusionXLPipeline' in tags: return "StableDiffusionXLPipeline" elif 'diffusers:StableDiffusionPipeline' in tags: return "StableDiffusionPipeline" else: return default
123git-lfsaria2 -yffmpeg1pip>=23.0.01231235678910111213144stablepy==0.6.5torch==2.8.0diffusersgit+https://github.com/R3gm/stablepy.git@flux_betatorch==2.2.0gdownopencv-pythonunidecode# pydantic==2.10.6huggingface_hubhf_transferhf_xetspacesgradio==6.10.0matplotlib-inlinemediapipe==0.10.13opencv-python123451789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import os
import re
import ipaddress
import urllib.parse
from shlex import quote as shqt
import gradio as gr
from 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_download
from diffusers import DiffusionPipeline
from huggingface_hub import model_info as model_info_data
from diffusers.pipelines.pipeline_loading_utils import variant_compatible_siblings
from stablepy.diffusers_vanilla.utils import checkpoint_model_type
from pathlib import PosixPath
from unidecode import unidecode
import copy
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
import shutil
import subprocess
import json
from html import escape as esc
IS_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 endpoints
if hostname in ("localhost", "0.0.0.0", "127.0.0.1", "::1"):
raise ValueError("Restricted address.")
# Restrict private IP addresses
try:
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 alias
if hostname == "civitai.red" or hostname.endswith(".civitai.red"):
url = url.replace("civitai.red", "civitai.com")
return url
def 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 length
resp = 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 JSON
end = 8 + header_len - 1
resp = 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 length
header_len = int.from_bytes(f.read(8), "little")
# Step 2: read header JSON
header_json = f.read(header_len).decode("utf-8")
return json.loads(header_json)
class LoraHeaderInformation:
"""
Encapsulates parsed info from a LoRA JSON header and provides
a 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 mapping
try:
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 values
self.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} # Info
if base_model_hash:
self.base_model += f" hash={base_model_hash}"
# Extract tags
try:
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 info
in 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_snippet
def request_json_data(url):
model_version_id = url.split('/')[-1]
if "?modelVersionId=" in model_version_id:
match = re.search(r'modelVersionId=(\d+)', url)
model_version_id = match.group(1)
endpoint_url = f"https://civitai.com/api/v1/model-versions/{model_version_id}"
params = {}
headers = {'User-Agent': USER_AGENT, 'content-type': 'application/json'}
session = requests.Session()
retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
session.mount("https://", HTTPAdapter(max_retries=retries))
try:
result = session.get(endpoint_url, params=params, headers=headers, stream=True, timeout=(3.0, 15))
result.raise_for_status()
json_data = result.json()
return json_data if json_data else None
except Exception as e:
print(f"Error: {e}")
return None
class ModelInformation:
def __init__(self, json_data):
self.model_version_id = json_data.get("id", "")
self.model_id = json_data.get("modelId", "")
self.download_url = json_data.get("downloadUrl", "")
self.model_url = f"https://civitai.com/models/{self.model_id}?modelVersionId={self.model_version_id}"
self.filename_url = next(
(v.get("name", "") for v in json_data.get("files", []) if str(self.model_version_id) in v.get("downloadUrl", "") and v.get("type", "Model") == "Model"), ""
)
self.filename_url = self.filename_url if self.filename_url else ""
self.description = json_data.get("description", "")
if self.description is None:
self.description = ""
self.model_name = json_data.get("model", {}).get("name", "")
self.model_type = json_data.get("model", {}).get("type", "")
self.nsfw = json_data.get("model", {}).get("nsfw", False)
self.poi = json_data.get("model", {}).get("poi", False)
self.images = [img.get("url", "") for img in json_data.get("images", [])]
self.example_prompt = json_data.get("trainedWords", [""])[0] if json_data.get("trainedWords") else ""
self.original_json = copy.deepcopy(json_data)
def 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_url
else:
ValueError("Invalid Civitai model URL")
except Exception as e:
print(f"Error retrieving Civitai metadata: {e} — fallback to direct download")
return url, None, None
def civ_redirect_down(url, dir_, civitai_api_key, romanize, alternative_name):
filename_base = filename = None
if 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 URL
curl_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" 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 redirect: {filename}")
filename_base = alternative_name if alternative_name else filename
if not filename_base:
return None, None
elif os.path.exists(os.path.join(dir_, filename_base)):
return os.path.join(dir_, filename_base), filename_base
wget_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_base
return output_path, filename_base
def 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 = None
url_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_path
def drive_down(url, dir_):
import gdown
output_path = None
drive_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)
break
if 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_path
def hf_down(url, dir_, hf_token, romanize):
url = url.replace("?download=true", "")
# url = urllib.parse.quote(url, safe=':/') # fix encoding
filename = 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_path
if "/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_path
def download_things(directory, url, hf_token="", civitai_api_key="", romanize=False):
url = url.strip()
if not url:
return None
try:
url = validate_url(url)
except Exception as e:
msg = f"Download blocked: {e}"
print(f"\033[91m{msg}\033[0m")
gr.Warning(msg)
return None
hostname = (urllib.parse.urlparse(url).hostname or "").lower()
downloaded_file_path = None
if 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 None
url, 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_path
def get_model_list(directory_path):
model_list = []
valid_extensions = {'.ckpt', '.pt', '.pth', '.safetensors', '.bin'}
for filename in os.listdir(directory_path):
if os.path.splitext(filename)[1] in valid_extensions:
# name_without_extension = os.path.splitext(filename)[0]
file_path = os.path.join(directory_path, filename)
# model_list.append((name_without_extension, file_path))
model_list.append(file_path)
print('\033[34mFILE: ' + file_path + '\033[0m')
return model_list
def extract_parameters(input_string):
parameters = {}
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_string
return parameters
parm = input_string.split("Negative prompt:")
parameters["prompt"] = parm[0].strip()
if "Steps:" not in parm[1]:
parameters["neg_prompt"] = parm[1].strip()
return parameters
parm = parm[1].split("Steps:")
parameters["neg_prompt"] = parm[0].strip()
input_string = "Steps:" + parm[1]
input_string = input_string.replace("\n", "").strip()
# Extracting Steps
steps_match = re.search(r'Steps: (\d+)', input_string)
if steps_match:
parameters['Steps'] = int(steps_match.group(1))
# Extracting Size
size_match = re.search(r'Size: (\d+x\d+)', input_string)
if size_match:
parameters['Size'] = size_match.group(1)
width, height = map(int, parameters['Size'].split('x'))
parameters['width'] = width
parameters['height'] = height
# Extracting other parameters
other_parameters = re.findall(r'([^,:]+): (.*?)(?=, [^,:]+:|$)', input_string)
for param in other_parameters:
parameters[param[0].strip()] = param[1].strip('"')
return parameters
def get_my_lora(link_url, romanize):
l_name = ""
for url in [url.strip() for url in link_url.split(',')]:
if not os.path.exists(f"./loras/{url.split('/')[-1]}"):
l_name = download_things(DIRECTORY_LORAS, url, HF_TOKEN, CIVITAI_API_KEY, romanize)
new_lora_model_list = get_model_list(DIRECTORY_LORAS)
new_lora_model_list.insert(0, "None")
new_lora_model_list = new_lora_model_list + DIFFUSERS_FORMAT_LORAS
msg_lora = "Downloaded"
if l_name:
msg_lora += f": <b>{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:
pass
return gr.update(
choices=new_lora_model_list
), gr.update(
choices=new_lora_model_list
), gr.update(
choices=new_lora_model_list
), gr.update(
choices=new_lora_model_list
), gr.update(
choices=new_lora_model_list
), gr.update(
choices=new_lora_model_list
), gr.update(
choices=new_lora_model_list
), gr.update(
value=msg_lora
)
def info_html(json_data, title, subtitle):
return f"""
<div style='padding: 0; border-radius: 10px;'>
<p style='margin: 0; font-weight: bold;'>{title}</p>
<details>
<summary>Details</summary>
<p style='margin: 0; font-weight: bold;'>{subtitle}</p>
</details>
</div>
"""
def get_model_type(repo_id: str):
api = HfApi(token=os.environ.get("HF_TOKEN")) # if use private or gated model
default = "SD 1.5"
try:
if os.path.exists(repo_id):
tag, _, _, _ = checkpoint_model_type(repo_id)
return DIFFUSECRAFT_CHECKPOINT_NAME[tag]
else:
model = api.model_info(repo_id=repo_id, timeout=5.0)
tags = model.tags
for tag in tags:
if tag in MODEL_TYPE_CLASS.keys():
return MODEL_TYPE_CLASS.get(tag, default)
except Exception:
return default
return default
def restart_space(repo_id: str, factory_reboot: bool):
api = HfApi(token=os.environ.get("HF_TOKEN"))
try:
runtime = api.get_space_runtime(repo_id=repo_id)
if runtime.stage == "RUNNING":
api.restart_space(repo_id=repo_id, factory_reboot=factory_reboot)
print(f"Restarting space: {repo_id}")
else:
print(f"Space {repo_id} is in stage: {runtime.stage}")
except Exception as e:
print(e)
def extract_exif_data(image):
if image is None:
return ""
try:
metadata_keys = ['parameters', 'metadata', 'prompt', 'Comment']
for key in metadata_keys:
if key in image.info:
return image.info[key]
return str(image.info)
except Exception as e:
return f"Error extracting metadata: {str(e)}"
def create_mask_now(img, invert):
import numpy as np
import time
time.sleep(0.5)
transparent_image = img["layers"][0]
# Extract the alpha channel
alpha_channel = np.array(transparent_image)[:, :, 3]
# Create a binary mask by thresholding the alpha channel
binary_mask = alpha_channel > 1
if invert:
print("Invert")
# Invert the binary mask so that the drawn shape is white and the rest is black
binary_mask = np.invert(binary_mask)
# Convert the binary mask to a 3-channel RGB mask
rgb_mask = np.stack((binary_mask,) * 3, axis=-1)
# Convert the mask to uint8
rgb_mask = rgb_mask.astype(np.uint8) * 255
return img["background"], rgb_mask
def download_diffuser_repo(repo_name: str, model_type: str, revision: str = "main", token=True):
variant = None
if token is True and not os.environ.get("HF_TOKEN"):
token = None
if model_type == "SDXL":
info = model_info_data(
repo_name,
token=token,
revision=revision,
timeout=5.0,
)
filenames = {sibling.rfilename for sibling in info.siblings}
model_filenames, variant_filenames = variant_compatible_siblings(
filenames, variant="fp16"
)
if len(variant_filenames):
variant = "fp16"
if model_type == "FLUX":
cached_folder = snapshot_download(
repo_id=repo_name,
allow_patterns="transformer/*"
)
else:
cached_folder = DiffusionPipeline.download(
pretrained_model_name=repo_name,
force_download=False,
token=token,
revision=revision,
# mirror="https://hf-mirror.com",
variant=variant,
use_safetensors=True,
trust_remote_code=False,
timeout=5.0,
)
if isinstance(cached_folder, PosixPath):
cached_folder = cached_folder.as_posix()
# Task model
# from huggingface_hub import hf_hub_download
# hf_hub_download(
# task_model,
# filename="diffusion_pytorch_model.safetensors", # fix fp16 variant
# )
return cached_folder
def get_folder_size_gb(folder_path):
result = subprocess.run(["du", "-s", folder_path], capture_output=True, text=True)
total_size_kb = int(result.stdout.split()[0])
total_size_gb = total_size_kb / (1024 ** 2)
return total_size_gb
def get_used_storage_gb(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 = 999
print(f"Error while retrieving the used storage: {e}.")
return used_gb
def delete_model(removal_candidate):
print(f"Removing: {removal_candidate}")
if os.path.exists(removal_candidate):
os.remove(removal_candidate)
else:
diffusers_model = f"{CACHE_HF}{DIRECTORY_MODELS}--{removal_candidate.replace('/', '--')}"
if os.path.isdir(diffusers_model):
shutil.rmtree(diffusers_model)
def 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 width
percentage = min(100, ((step / total) * 100))
return f"""
<div style="position: relative; width: 100%; background-color: gray; border-radius: 5px; overflow: hidden;">
<div style="width: {percentage}%; height: 17px; background-color: #800080; transition: width 0.5s;"></div>
<div style="position: absolute; width: 100%; text-align: center; color: white; top: 0; line-height: 19px; font-size: 13px;">
{int(percentage)}%
</div>
</div>
"""
def html_template_message(msg):
return f"""
<div style="position: relative; width: 100%; background-color: gray; border-radius: 5px; overflow: hidden;">
<div style="width: 0%; height: 17px; background-color: #800080; transition: width 0.5s;"></div>
<div style="position: absolute; width: 100%; text-align: center; color: white; top: 0; line-height: 19px; font-size: 14px; font-weight: bold; text-shadow: 1px 1px 2px black;">
{msg}
</div>
</div>
"""
def escape_html(text):
"""Escapes HTML special characters in the input text."""
if text is None:
return ""
return esc(str(text), quote=True).replace("\n", "<br>")from dartrs.v2 import AspectRatioTag, LengthTag, RatingTag, IdentityTag
V2_ASPECT_RATIO_OPTIONS: list[AspectRatioTag] = [
"ultra_wide",
"wide",
"square",
"tall",
"ultra_tall",
]
V2_RATING_OPTIONS: list[RatingTag] = [
"sfw",
"general",
"sensitive",
"nsfw",
"questionable",
"explicit",
]
V2_LENGTH_OPTIONS: list[LengthTag] = [
"very_short",
"short",
"medium",
"long",
"very_long",
]
V2_IDENTITY_OPTIONS: list[IdentityTag] = [
"none",
"lax",
"strict",
]
# ref: https://qiita.com/tregu148/items/fccccbbc47d966dd2fc2
def gradio_copy_text(_text: None):
gr.Info("Copied!")
COPY_ACTION_JS = """\
(inputs, _outputs) => {
// inputs is the string value of the input_text
if (inputs.trim() !== "") {
navigator.clipboard.writeText(inputs);
}
}"""
def gradio_copy_prompt(prompt: str):
gr.Info("Copied!")
return prompt.gitignoreDeleted-207
README.md+1-4
app.py
constants.pyDeleted-640
image_processor.pyDeleted-130
lora_dict.jsonAdded
model_dict.jsonAdded
modutils.pyAdded+1290
packages.txt+1
pre-requirements.txtDeleted-1
requirements.txt+3-13
stablepy_model.pyAdded
utils.py+49-778